/lib_duktape/src/duktape.c

https://bitbucket.org/xixs/lua · C · 72672 lines · 49043 code · 8974 blank · 14655 comment · 7498 complexity · 871478a7f12eae76e32e32eceff98bb8 MD5 · raw file

  1. /*
  2. * Single file autogenerated distributable for Duktape 1.2.2.
  3. * Git commit 5f4302c732d21b3b721db3d3473db32e4eb92470 (v1.2.2).
  4. *
  5. * See Duktape AUTHORS.rst and LICENSE.txt for copyright and
  6. * licensing information.
  7. */
  8. /* LICENSE.txt */
  9. /*
  10. * ===============
  11. * Duktape license
  12. * ===============
  13. *
  14. * (http://opensource.org/licenses/MIT)
  15. *
  16. * Copyright (c) 2013-2015 by Duktape authors (see AUTHORS.rst)
  17. *
  18. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19. * of this software and associated documentation files (the "Software"), to deal
  20. * in the Software without restriction, including without limitation the rights
  21. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  22. * copies of the Software, and to permit persons to whom the Software is
  23. * furnished to do so, subject to the following conditions:
  24. *
  25. * The above copyright notice and this permission notice shall be included in
  26. * all copies or substantial portions of the Software.
  27. *
  28. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  30. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  31. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  32. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  33. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  34. * THE SOFTWARE.
  35. *
  36. */
  37. /* AUTHORS.rst */
  38. /*
  39. * ===============
  40. * Duktape authors
  41. * ===============
  42. *
  43. * Copyright
  44. * =========
  45. *
  46. * Duktape copyrights are held by its authors. Each author has a copyright
  47. * to their contribution, and agrees to irrevocably license the contribution
  48. * under the Duktape ``LICENSE.txt``.
  49. *
  50. * Authors
  51. * =======
  52. *
  53. * Please include an e-mail address, a link to your GitHub profile, or something
  54. * similar to allow your contribution to be identified accurately.
  55. *
  56. * The following people have contributed code and agreed to irrevocably license
  57. * their contributions under the Duktape ``LICENSE.txt`` (in order of appearance):
  58. *
  59. * * Sami Vaarala <sami.vaarala@iki.fi>
  60. * * Niki Dobrev
  61. * * Andreas \u00d6man <andreas@lonelycoder.com>
  62. * * L\u00e1szl\u00f3 Lang\u00f3 <llango.u-szeged@partner.samsung.com>
  63. * * Legimet <legimet.calc@gmail.com>
  64. *
  65. * Other contributions
  66. * ===================
  67. *
  68. * The following people have contributed something other than code (e.g. reported
  69. * bugs, provided ideas, etc; roughly in order of appearance):
  70. *
  71. * * Greg Burns
  72. * * Anthony Rabine
  73. * * Carlos Costa
  74. * * Aur\u00e9lien Bouilland
  75. * * Preet Desai (Pris Matic)
  76. * * judofyr (http://www.reddit.com/user/judofyr)
  77. * * Jason Woofenden
  78. * * Micha\u0142 Przyby\u015b
  79. * * Anthony Howe
  80. * * Conrad Pankoff
  81. * * Jim Schimpf
  82. * * Rajaran Gaunker (https://github.com/zimbabao)
  83. * * Andreas \u00d6man
  84. * * Doug Sanden
  85. * * Josh Engebretson (https://github.com/JoshEngebretson)
  86. * * Remo Eichenberger (https://github.com/remoe)
  87. * * Mamod Mehyar (https://github.com/mamod)
  88. * * David Demelier (https://github.com/hftmarkand)
  89. * * Tim Caswell (https://github.com/creationix)
  90. * * Mitchell Blank Jr (https://github.com/mitchblank)
  91. * * https://github.com/yushli
  92. * * Seo Sanghyeon (https://github.com/sanxiyn)
  93. * * Han ChoongWoo (https://github.com/tunz)
  94. * * Joshua Peek (https://github.com/josh)
  95. * * Bruce E. Pascoe (https://github.com/fatcerberus)
  96. * * https://github.com/Kelledin
  97. *
  98. * If you are accidentally missing from this list, send me an e-mail
  99. * (``sami.vaarala@iki.fi``) and I'll fix the omission.
  100. */
  101. #line 1 "duk_internal.h"
  102. /*
  103. * Top-level include file to be used for all (internal) source files.
  104. *
  105. * Source files should not include individual header files, as they
  106. * have not been designed to be individually included.
  107. */
  108. #ifndef DUK_INTERNAL_H_INCLUDED
  109. #define DUK_INTERNAL_H_INCLUDED
  110. /*
  111. * The 'duktape.h' header provides the public API, but also handles all
  112. * compiler and platform specific feature detection, Duktape feature
  113. * resolution, inclusion of system headers, etc. These have been merged
  114. * because the public API is also dependent on e.g. detecting appropriate
  115. * C types which is quite platform/compiler specific especially for a non-C99
  116. * build. The public API is also dependent on the resolved feature set.
  117. *
  118. * Some actions taken by the merged header (such as including system headers)
  119. * are not appropriate for building a user application. The define
  120. * DUK_COMPILING_DUKTAPE allows the merged header to skip/include some
  121. * sections depending on what is being built.
  122. */
  123. #define DUK_COMPILING_DUKTAPE
  124. #include "duktape.h"
  125. /*
  126. * User declarations, e.g. prototypes for user functions used by Duktape
  127. * macros. Concretely, if DUK_OPT_PANIC_HANDLER is used and the macro
  128. * value calls a user function, it needs to be declared for Duktape
  129. * compilation to avoid warnings.
  130. */
  131. DUK_USE_USER_DECLARE()
  132. /*
  133. * Duktape includes (other than duk_features.h)
  134. *
  135. * The header files expect to be included in an order which satisfies header
  136. * dependencies correctly (the headers themselves don't include any other
  137. * includes). Forward declarations are used to break circular struct/typedef
  138. * dependencies.
  139. */
  140. #line 1 "duk_replacements.h"
  141. #ifndef DUK_REPLACEMENTS_H_INCLUDED
  142. #define DUK_REPLACEMENTS_H_INCLUDED
  143. #ifdef DUK_USE_REPL_FPCLASSIFY
  144. DUK_INTERNAL_DECL int duk_repl_fpclassify(double x);
  145. #endif
  146. #ifdef DUK_USE_REPL_SIGNBIT
  147. DUK_INTERNAL_DECL int duk_repl_signbit(double x);
  148. #endif
  149. #ifdef DUK_USE_REPL_ISFINITE
  150. DUK_INTERNAL_DECL int duk_repl_isfinite(double x);
  151. #endif
  152. #ifdef DUK_USE_REPL_ISNAN
  153. DUK_INTERNAL_DECL int duk_repl_isnan(double x);
  154. #endif
  155. #ifdef DUK_USE_REPL_ISINF
  156. DUK_INTERNAL_DECL int duk_repl_isinf(double x);
  157. #endif
  158. #endif /* DUK_REPLACEMENTS_H_INCLUDED */
  159. #line 1 "duk_jmpbuf.h"
  160. /*
  161. * Wrapper for jmp_buf.
  162. *
  163. * This is used because jmp_buf is an array type for backward compatibility.
  164. * Wrapping jmp_buf in a struct makes pointer references, sizeof, etc,
  165. * behave more intuitively.
  166. *
  167. * http://en.wikipedia.org/wiki/Setjmp.h#Member_types
  168. */
  169. #ifndef DUK_JMPBUF_H_INCLUDED
  170. #define DUK_JMPBUF_H_INCLUDED
  171. struct duk_jmpbuf {
  172. #if defined(DUK_USE_SETJMP) || defined(DUK_USE_UNDERSCORE_SETJMP)
  173. jmp_buf jb;
  174. #elif defined(DUK_USE_SIGSETJMP)
  175. sigjmp_buf jb;
  176. #else
  177. #error internal error, no long control transfer provider
  178. #endif
  179. };
  180. #endif /* DUK_JMPBUF_H_INCLUDED */
  181. #line 1 "duk_forwdecl.h"
  182. /*
  183. * Forward declarations for all Duktape structures.
  184. */
  185. #ifndef DUK_FORWDECL_H_INCLUDED
  186. #define DUK_FORWDECL_H_INCLUDED
  187. /*
  188. * Forward declarations
  189. */
  190. struct duk_jmpbuf;
  191. /* duk_tval intentionally skipped */
  192. struct duk_heaphdr;
  193. struct duk_heaphdr_string;
  194. struct duk_hstring;
  195. struct duk_hstring_external;
  196. struct duk_hobject;
  197. struct duk_hcompiledfunction;
  198. struct duk_hnativefunction;
  199. struct duk_hthread;
  200. struct duk_hbuffer;
  201. struct duk_hbuffer_fixed;
  202. struct duk_hbuffer_dynamic;
  203. struct duk_propaccessor;
  204. union duk_propvalue;
  205. struct duk_propdesc;
  206. struct duk_heap;
  207. struct duk_breakpoint;
  208. struct duk_activation;
  209. struct duk_catcher;
  210. struct duk_strcache;
  211. struct duk_ljstate;
  212. struct duk_strtab_entry;
  213. #ifdef DUK_USE_DEBUG
  214. struct duk_fixedbuffer;
  215. #endif
  216. struct duk_bitdecoder_ctx;
  217. struct duk_bitencoder_ctx;
  218. struct duk_token;
  219. struct duk_re_token;
  220. struct duk_lexer_point;
  221. struct duk_lexer_ctx;
  222. struct duk_compiler_instr;
  223. struct duk_compiler_func;
  224. struct duk_compiler_ctx;
  225. struct duk_re_matcher_ctx;
  226. struct duk_re_compiler_ctx;
  227. typedef struct duk_jmpbuf duk_jmpbuf;
  228. /* duk_tval intentionally skipped */
  229. typedef struct duk_heaphdr duk_heaphdr;
  230. typedef struct duk_heaphdr_string duk_heaphdr_string;
  231. typedef struct duk_hstring duk_hstring;
  232. typedef struct duk_hstring_external duk_hstring_external;
  233. typedef struct duk_hobject duk_hobject;
  234. typedef struct duk_hcompiledfunction duk_hcompiledfunction;
  235. typedef struct duk_hnativefunction duk_hnativefunction;
  236. typedef struct duk_hthread duk_hthread;
  237. typedef struct duk_hbuffer duk_hbuffer;
  238. typedef struct duk_hbuffer_fixed duk_hbuffer_fixed;
  239. typedef struct duk_hbuffer_dynamic duk_hbuffer_dynamic;
  240. typedef struct duk_propaccessor duk_propaccessor;
  241. typedef union duk_propvalue duk_propvalue;
  242. typedef struct duk_propdesc duk_propdesc;
  243. typedef struct duk_heap duk_heap;
  244. typedef struct duk_breakpoint duk_breakpoint;
  245. typedef struct duk_activation duk_activation;
  246. typedef struct duk_catcher duk_catcher;
  247. typedef struct duk_strcache duk_strcache;
  248. typedef struct duk_ljstate duk_ljstate;
  249. typedef struct duk_strtab_entry duk_strtab_entry;
  250. #ifdef DUK_USE_DEBUG
  251. typedef struct duk_fixedbuffer duk_fixedbuffer;
  252. #endif
  253. typedef struct duk_bitdecoder_ctx duk_bitdecoder_ctx;
  254. typedef struct duk_bitencoder_ctx duk_bitencoder_ctx;
  255. typedef struct duk_token duk_token;
  256. typedef struct duk_re_token duk_re_token;
  257. typedef struct duk_lexer_point duk_lexer_point;
  258. typedef struct duk_lexer_ctx duk_lexer_ctx;
  259. typedef struct duk_compiler_instr duk_compiler_instr;
  260. typedef struct duk_compiler_func duk_compiler_func;
  261. typedef struct duk_compiler_ctx duk_compiler_ctx;
  262. typedef struct duk_re_matcher_ctx duk_re_matcher_ctx;
  263. typedef struct duk_re_compiler_ctx duk_re_compiler_ctx;
  264. #endif /* DUK_FORWDECL_H_INCLUDED */
  265. #line 1 "duk_builtins.h"
  266. /*
  267. * Automatically generated by genbuiltins.py, do not edit!
  268. */
  269. #ifndef DUK_BUILTINS_H_INCLUDED
  270. #define DUK_BUILTINS_H_INCLUDED
  271. #if defined(DUK_USE_DOUBLE_LE)
  272. #if !defined(DUK_SINGLE_FILE)
  273. DUK_INTERNAL_DECL const duk_uint8_t duk_strings_data[1943];
  274. #endif /* !DUK_SINGLE_FILE */
  275. #define DUK_STRDATA_DATA_LENGTH 1943
  276. #define DUK_STRDATA_MAX_STRLEN 24
  277. #define DUK_STRIDX_UC_LOGGER 0 /* 'Logger' */
  278. #define DUK_STRIDX_UC_THREAD 1 /* 'Thread' */
  279. #define DUK_STRIDX_UC_POINTER 2 /* 'Pointer' */
  280. #define DUK_STRIDX_UC_BUFFER 3 /* 'Buffer' */
  281. #define DUK_STRIDX_DEC_ENV 4 /* 'DecEnv' */
  282. #define DUK_STRIDX_OBJ_ENV 5 /* 'ObjEnv' */
  283. #define DUK_STRIDX_EMPTY_STRING 6 /* '' */
  284. #define DUK_STRIDX_GLOBAL 7 /* 'global' */
  285. #define DUK_STRIDX_UC_ARGUMENTS 8 /* 'Arguments' */
  286. #define DUK_STRIDX_JSON 9 /* 'JSON' */
  287. #define DUK_STRIDX_MATH 10 /* 'Math' */
  288. #define DUK_STRIDX_UC_ERROR 11 /* 'Error' */
  289. #define DUK_STRIDX_REG_EXP 12 /* 'RegExp' */
  290. #define DUK_STRIDX_DATE 13 /* 'Date' */
  291. #define DUK_STRIDX_UC_NUMBER 14 /* 'Number' */
  292. #define DUK_STRIDX_UC_BOOLEAN 15 /* 'Boolean' */
  293. #define DUK_STRIDX_UC_STRING 16 /* 'String' */
  294. #define DUK_STRIDX_ARRAY 17 /* 'Array' */
  295. #define DUK_STRIDX_UC_FUNCTION 18 /* 'Function' */
  296. #define DUK_STRIDX_UC_OBJECT 19 /* 'Object' */
  297. #define DUK_STRIDX_UC_NULL 20 /* 'Null' */
  298. #define DUK_STRIDX_UC_UNDEFINED 21 /* 'Undefined' */
  299. #define DUK_STRIDX_JSON_EXT_FUNCTION2 22 /* '{_func:true}' */
  300. #define DUK_STRIDX_JSON_EXT_FUNCTION1 23 /* '{"_func":true}' */
  301. #define DUK_STRIDX_JSON_EXT_NEGINF 24 /* '{"_ninf":true}' */
  302. #define DUK_STRIDX_JSON_EXT_POSINF 25 /* '{"_inf":true}' */
  303. #define DUK_STRIDX_JSON_EXT_NAN 26 /* '{"_nan":true}' */
  304. #define DUK_STRIDX_JSON_EXT_UNDEFINED 27 /* '{"_undef":true}' */
  305. #define DUK_STRIDX_TO_LOG_STRING 28 /* 'toLogString' */
  306. #define DUK_STRIDX_CLOG 29 /* 'clog' */
  307. #define DUK_STRIDX_LC_L 30 /* 'l' */
  308. #define DUK_STRIDX_LC_N 31 /* 'n' */
  309. #define DUK_STRIDX_LC_FATAL 32 /* 'fatal' */
  310. #define DUK_STRIDX_LC_ERROR 33 /* 'error' */
  311. #define DUK_STRIDX_LC_WARN 34 /* 'warn' */
  312. #define DUK_STRIDX_LC_DEBUG 35 /* 'debug' */
  313. #define DUK_STRIDX_LC_TRACE 36 /* 'trace' */
  314. #define DUK_STRIDX_RAW 37 /* 'raw' */
  315. #define DUK_STRIDX_FMT 38 /* 'fmt' */
  316. #define DUK_STRIDX_CURRENT 39 /* 'current' */
  317. #define DUK_STRIDX_RESUME 40 /* 'resume' */
  318. #define DUK_STRIDX_COMPACT 41 /* 'compact' */
  319. #define DUK_STRIDX_JC 42 /* 'jc' */
  320. #define DUK_STRIDX_JX 43 /* 'jx' */
  321. #define DUK_STRIDX_BASE64 44 /* 'base64' */
  322. #define DUK_STRIDX_HEX 45 /* 'hex' */
  323. #define DUK_STRIDX_DEC 46 /* 'dec' */
  324. #define DUK_STRIDX_ENC 47 /* 'enc' */
  325. #define DUK_STRIDX_FIN 48 /* 'fin' */
  326. #define DUK_STRIDX_GC 49 /* 'gc' */
  327. #define DUK_STRIDX_ACT 50 /* 'act' */
  328. #define DUK_STRIDX_LC_INFO 51 /* 'info' */
  329. #define DUK_STRIDX_VERSION 52 /* 'version' */
  330. #define DUK_STRIDX_ENV 53 /* 'env' */
  331. #define DUK_STRIDX_MOD_LOADED 54 /* 'modLoaded' */
  332. #define DUK_STRIDX_MOD_SEARCH 55 /* 'modSearch' */
  333. #define DUK_STRIDX_ERR_THROW 56 /* 'errThrow' */
  334. #define DUK_STRIDX_ERR_CREATE 57 /* 'errCreate' */
  335. #define DUK_STRIDX_COMPILE 58 /* 'compile' */
  336. #define DUK_STRIDX_INT_REGBASE 59 /* '\x00Regbase' */
  337. #define DUK_STRIDX_INT_THREAD 60 /* '\x00Thread' */
  338. #define DUK_STRIDX_INT_HANDLER 61 /* '\x00Handler' */
  339. #define DUK_STRIDX_INT_FINALIZER 62 /* '\x00Finalizer' */
  340. #define DUK_STRIDX_INT_CALLEE 63 /* '\x00Callee' */
  341. #define DUK_STRIDX_INT_MAP 64 /* '\x00Map' */
  342. #define DUK_STRIDX_INT_ARGS 65 /* '\x00Args' */
  343. #define DUK_STRIDX_INT_THIS 66 /* '\x00This' */
  344. #define DUK_STRIDX_INT_PC2LINE 67 /* '\x00Pc2line' */
  345. #define DUK_STRIDX_INT_SOURCE 68 /* '\x00Source' */
  346. #define DUK_STRIDX_INT_VARENV 69 /* '\x00Varenv' */
  347. #define DUK_STRIDX_INT_LEXENV 70 /* '\x00Lexenv' */
  348. #define DUK_STRIDX_INT_VARMAP 71 /* '\x00Varmap' */
  349. #define DUK_STRIDX_INT_FORMALS 72 /* '\x00Formals' */
  350. #define DUK_STRIDX_INT_BYTECODE 73 /* '\x00Bytecode' */
  351. #define DUK_STRIDX_INT_NEXT 74 /* '\x00Next' */
  352. #define DUK_STRIDX_INT_TARGET 75 /* '\x00Target' */
  353. #define DUK_STRIDX_INT_VALUE 76 /* '\x00Value' */
  354. #define DUK_STRIDX_LC_POINTER 77 /* 'pointer' */
  355. #define DUK_STRIDX_LC_BUFFER 78 /* 'buffer' */
  356. #define DUK_STRIDX_INT_TRACEDATA 79 /* '\x00Tracedata' */
  357. #define DUK_STRIDX_LINE_NUMBER 80 /* 'lineNumber' */
  358. #define DUK_STRIDX_FILE_NAME 81 /* 'fileName' */
  359. #define DUK_STRIDX_PC 82 /* 'pc' */
  360. #define DUK_STRIDX_STACK 83 /* 'stack' */
  361. #define DUK_STRIDX_THROW_TYPE_ERROR 84 /* 'ThrowTypeError' */
  362. #define DUK_STRIDX_DUKTAPE 85 /* 'Duktape' */
  363. #define DUK_STRIDX_ID 86 /* 'id' */
  364. #define DUK_STRIDX_REQUIRE 87 /* 'require' */
  365. #define DUK_STRIDX___PROTO__ 88 /* '__proto__' */
  366. #define DUK_STRIDX_SET_PROTOTYPE_OF 89 /* 'setPrototypeOf' */
  367. #define DUK_STRIDX_OWN_KEYS 90 /* 'ownKeys' */
  368. #define DUK_STRIDX_ENUMERATE 91 /* 'enumerate' */
  369. #define DUK_STRIDX_DELETE_PROPERTY 92 /* 'deleteProperty' */
  370. #define DUK_STRIDX_HAS 93 /* 'has' */
  371. #define DUK_STRIDX_PROXY 94 /* 'Proxy' */
  372. #define DUK_STRIDX_CALLEE 95 /* 'callee' */
  373. #define DUK_STRIDX_INVALID_DATE 96 /* 'Invalid Date' */
  374. #define DUK_STRIDX_BRACKETED_ELLIPSIS 97 /* '[...]' */
  375. #define DUK_STRIDX_NEWLINE_TAB 98 /* '\n\t' */
  376. #define DUK_STRIDX_SPACE 99 /* ' ' */
  377. #define DUK_STRIDX_COMMA 100 /* ',' */
  378. #define DUK_STRIDX_MINUS_ZERO 101 /* '-0' */
  379. #define DUK_STRIDX_PLUS_ZERO 102 /* '+0' */
  380. #define DUK_STRIDX_ZERO 103 /* '0' */
  381. #define DUK_STRIDX_MINUS_INFINITY 104 /* '-Infinity' */
  382. #define DUK_STRIDX_PLUS_INFINITY 105 /* '+Infinity' */
  383. #define DUK_STRIDX_INFINITY 106 /* 'Infinity' */
  384. #define DUK_STRIDX_LC_OBJECT 107 /* 'object' */
  385. #define DUK_STRIDX_LC_STRING 108 /* 'string' */
  386. #define DUK_STRIDX_LC_NUMBER 109 /* 'number' */
  387. #define DUK_STRIDX_LC_BOOLEAN 110 /* 'boolean' */
  388. #define DUK_STRIDX_LC_UNDEFINED 111 /* 'undefined' */
  389. #define DUK_STRIDX_STRINGIFY 112 /* 'stringify' */
  390. #define DUK_STRIDX_TAN 113 /* 'tan' */
  391. #define DUK_STRIDX_SQRT 114 /* 'sqrt' */
  392. #define DUK_STRIDX_SIN 115 /* 'sin' */
  393. #define DUK_STRIDX_ROUND 116 /* 'round' */
  394. #define DUK_STRIDX_RANDOM 117 /* 'random' */
  395. #define DUK_STRIDX_POW 118 /* 'pow' */
  396. #define DUK_STRIDX_MIN 119 /* 'min' */
  397. #define DUK_STRIDX_MAX 120 /* 'max' */
  398. #define DUK_STRIDX_LOG 121 /* 'log' */
  399. #define DUK_STRIDX_FLOOR 122 /* 'floor' */
  400. #define DUK_STRIDX_EXP 123 /* 'exp' */
  401. #define DUK_STRIDX_COS 124 /* 'cos' */
  402. #define DUK_STRIDX_CEIL 125 /* 'ceil' */
  403. #define DUK_STRIDX_ATAN2 126 /* 'atan2' */
  404. #define DUK_STRIDX_ATAN 127 /* 'atan' */
  405. #define DUK_STRIDX_ASIN 128 /* 'asin' */
  406. #define DUK_STRIDX_ACOS 129 /* 'acos' */
  407. #define DUK_STRIDX_ABS 130 /* 'abs' */
  408. #define DUK_STRIDX_SQRT2 131 /* 'SQRT2' */
  409. #define DUK_STRIDX_SQRT1_2 132 /* 'SQRT1_2' */
  410. #define DUK_STRIDX_PI 133 /* 'PI' */
  411. #define DUK_STRIDX_LOG10E 134 /* 'LOG10E' */
  412. #define DUK_STRIDX_LOG2E 135 /* 'LOG2E' */
  413. #define DUK_STRIDX_LN2 136 /* 'LN2' */
  414. #define DUK_STRIDX_LN10 137 /* 'LN10' */
  415. #define DUK_STRIDX_E 138 /* 'E' */
  416. #define DUK_STRIDX_MESSAGE 139 /* 'message' */
  417. #define DUK_STRIDX_NAME 140 /* 'name' */
  418. #define DUK_STRIDX_INPUT 141 /* 'input' */
  419. #define DUK_STRIDX_INDEX 142 /* 'index' */
  420. #define DUK_STRIDX_ESCAPED_EMPTY_REGEXP 143 /* '(?:)' */
  421. #define DUK_STRIDX_LAST_INDEX 144 /* 'lastIndex' */
  422. #define DUK_STRIDX_MULTILINE 145 /* 'multiline' */
  423. #define DUK_STRIDX_IGNORE_CASE 146 /* 'ignoreCase' */
  424. #define DUK_STRIDX_SOURCE 147 /* 'source' */
  425. #define DUK_STRIDX_TEST 148 /* 'test' */
  426. #define DUK_STRIDX_EXEC 149 /* 'exec' */
  427. #define DUK_STRIDX_TO_GMT_STRING 150 /* 'toGMTString' */
  428. #define DUK_STRIDX_SET_YEAR 151 /* 'setYear' */
  429. #define DUK_STRIDX_GET_YEAR 152 /* 'getYear' */
  430. #define DUK_STRIDX_TO_JSON 153 /* 'toJSON' */
  431. #define DUK_STRIDX_TO_ISO_STRING 154 /* 'toISOString' */
  432. #define DUK_STRIDX_TO_UTC_STRING 155 /* 'toUTCString' */
  433. #define DUK_STRIDX_SET_UTC_FULL_YEAR 156 /* 'setUTCFullYear' */
  434. #define DUK_STRIDX_SET_FULL_YEAR 157 /* 'setFullYear' */
  435. #define DUK_STRIDX_SET_UTC_MONTH 158 /* 'setUTCMonth' */
  436. #define DUK_STRIDX_SET_MONTH 159 /* 'setMonth' */
  437. #define DUK_STRIDX_SET_UTC_DATE 160 /* 'setUTCDate' */
  438. #define DUK_STRIDX_SET_DATE 161 /* 'setDate' */
  439. #define DUK_STRIDX_SET_UTC_HOURS 162 /* 'setUTCHours' */
  440. #define DUK_STRIDX_SET_HOURS 163 /* 'setHours' */
  441. #define DUK_STRIDX_SET_UTC_MINUTES 164 /* 'setUTCMinutes' */
  442. #define DUK_STRIDX_SET_MINUTES 165 /* 'setMinutes' */
  443. #define DUK_STRIDX_SET_UTC_SECONDS 166 /* 'setUTCSeconds' */
  444. #define DUK_STRIDX_SET_SECONDS 167 /* 'setSeconds' */
  445. #define DUK_STRIDX_SET_UTC_MILLISECONDS 168 /* 'setUTCMilliseconds' */
  446. #define DUK_STRIDX_SET_MILLISECONDS 169 /* 'setMilliseconds' */
  447. #define DUK_STRIDX_SET_TIME 170 /* 'setTime' */
  448. #define DUK_STRIDX_GET_TIMEZONE_OFFSET 171 /* 'getTimezoneOffset' */
  449. #define DUK_STRIDX_GET_UTC_MILLISECONDS 172 /* 'getUTCMilliseconds' */
  450. #define DUK_STRIDX_GET_MILLISECONDS 173 /* 'getMilliseconds' */
  451. #define DUK_STRIDX_GET_UTC_SECONDS 174 /* 'getUTCSeconds' */
  452. #define DUK_STRIDX_GET_SECONDS 175 /* 'getSeconds' */
  453. #define DUK_STRIDX_GET_UTC_MINUTES 176 /* 'getUTCMinutes' */
  454. #define DUK_STRIDX_GET_MINUTES 177 /* 'getMinutes' */
  455. #define DUK_STRIDX_GET_UTC_HOURS 178 /* 'getUTCHours' */
  456. #define DUK_STRIDX_GET_HOURS 179 /* 'getHours' */
  457. #define DUK_STRIDX_GET_UTC_DAY 180 /* 'getUTCDay' */
  458. #define DUK_STRIDX_GET_DAY 181 /* 'getDay' */
  459. #define DUK_STRIDX_GET_UTC_DATE 182 /* 'getUTCDate' */
  460. #define DUK_STRIDX_GET_DATE 183 /* 'getDate' */
  461. #define DUK_STRIDX_GET_UTC_MONTH 184 /* 'getUTCMonth' */
  462. #define DUK_STRIDX_GET_MONTH 185 /* 'getMonth' */
  463. #define DUK_STRIDX_GET_UTC_FULL_YEAR 186 /* 'getUTCFullYear' */
  464. #define DUK_STRIDX_GET_FULL_YEAR 187 /* 'getFullYear' */
  465. #define DUK_STRIDX_GET_TIME 188 /* 'getTime' */
  466. #define DUK_STRIDX_TO_LOCALE_TIME_STRING 189 /* 'toLocaleTimeString' */
  467. #define DUK_STRIDX_TO_LOCALE_DATE_STRING 190 /* 'toLocaleDateString' */
  468. #define DUK_STRIDX_TO_TIME_STRING 191 /* 'toTimeString' */
  469. #define DUK_STRIDX_TO_DATE_STRING 192 /* 'toDateString' */
  470. #define DUK_STRIDX_NOW 193 /* 'now' */
  471. #define DUK_STRIDX_UTC 194 /* 'UTC' */
  472. #define DUK_STRIDX_PARSE 195 /* 'parse' */
  473. #define DUK_STRIDX_TO_PRECISION 196 /* 'toPrecision' */
  474. #define DUK_STRIDX_TO_EXPONENTIAL 197 /* 'toExponential' */
  475. #define DUK_STRIDX_TO_FIXED 198 /* 'toFixed' */
  476. #define DUK_STRIDX_POSITIVE_INFINITY 199 /* 'POSITIVE_INFINITY' */
  477. #define DUK_STRIDX_NEGATIVE_INFINITY 200 /* 'NEGATIVE_INFINITY' */
  478. #define DUK_STRIDX_NAN 201 /* 'NaN' */
  479. #define DUK_STRIDX_MIN_VALUE 202 /* 'MIN_VALUE' */
  480. #define DUK_STRIDX_MAX_VALUE 203 /* 'MAX_VALUE' */
  481. #define DUK_STRIDX_SUBSTR 204 /* 'substr' */
  482. #define DUK_STRIDX_TRIM 205 /* 'trim' */
  483. #define DUK_STRIDX_TO_LOCALE_UPPER_CASE 206 /* 'toLocaleUpperCase' */
  484. #define DUK_STRIDX_TO_UPPER_CASE 207 /* 'toUpperCase' */
  485. #define DUK_STRIDX_TO_LOCALE_LOWER_CASE 208 /* 'toLocaleLowerCase' */
  486. #define DUK_STRIDX_TO_LOWER_CASE 209 /* 'toLowerCase' */
  487. #define DUK_STRIDX_SUBSTRING 210 /* 'substring' */
  488. #define DUK_STRIDX_SPLIT 211 /* 'split' */
  489. #define DUK_STRIDX_SEARCH 212 /* 'search' */
  490. #define DUK_STRIDX_REPLACE 213 /* 'replace' */
  491. #define DUK_STRIDX_MATCH 214 /* 'match' */
  492. #define DUK_STRIDX_LOCALE_COMPARE 215 /* 'localeCompare' */
  493. #define DUK_STRIDX_CHAR_CODE_AT 216 /* 'charCodeAt' */
  494. #define DUK_STRIDX_CHAR_AT 217 /* 'charAt' */
  495. #define DUK_STRIDX_FROM_CHAR_CODE 218 /* 'fromCharCode' */
  496. #define DUK_STRIDX_REDUCE_RIGHT 219 /* 'reduceRight' */
  497. #define DUK_STRIDX_REDUCE 220 /* 'reduce' */
  498. #define DUK_STRIDX_FILTER 221 /* 'filter' */
  499. #define DUK_STRIDX_MAP 222 /* 'map' */
  500. #define DUK_STRIDX_FOR_EACH 223 /* 'forEach' */
  501. #define DUK_STRIDX_SOME 224 /* 'some' */
  502. #define DUK_STRIDX_EVERY 225 /* 'every' */
  503. #define DUK_STRIDX_LAST_INDEX_OF 226 /* 'lastIndexOf' */
  504. #define DUK_STRIDX_INDEX_OF 227 /* 'indexOf' */
  505. #define DUK_STRIDX_UNSHIFT 228 /* 'unshift' */
  506. #define DUK_STRIDX_SPLICE 229 /* 'splice' */
  507. #define DUK_STRIDX_SORT 230 /* 'sort' */
  508. #define DUK_STRIDX_SLICE 231 /* 'slice' */
  509. #define DUK_STRIDX_SHIFT 232 /* 'shift' */
  510. #define DUK_STRIDX_REVERSE 233 /* 'reverse' */
  511. #define DUK_STRIDX_PUSH 234 /* 'push' */
  512. #define DUK_STRIDX_POP 235 /* 'pop' */
  513. #define DUK_STRIDX_JOIN 236 /* 'join' */
  514. #define DUK_STRIDX_CONCAT 237 /* 'concat' */
  515. #define DUK_STRIDX_IS_ARRAY 238 /* 'isArray' */
  516. #define DUK_STRIDX_LC_ARGUMENTS 239 /* 'arguments' */
  517. #define DUK_STRIDX_CALLER 240 /* 'caller' */
  518. #define DUK_STRIDX_BIND 241 /* 'bind' */
  519. #define DUK_STRIDX_CALL 242 /* 'call' */
  520. #define DUK_STRIDX_APPLY 243 /* 'apply' */
  521. #define DUK_STRIDX_PROPERTY_IS_ENUMERABLE 244 /* 'propertyIsEnumerable' */
  522. #define DUK_STRIDX_IS_PROTOTYPE_OF 245 /* 'isPrototypeOf' */
  523. #define DUK_STRIDX_HAS_OWN_PROPERTY 246 /* 'hasOwnProperty' */
  524. #define DUK_STRIDX_VALUE_OF 247 /* 'valueOf' */
  525. #define DUK_STRIDX_TO_LOCALE_STRING 248 /* 'toLocaleString' */
  526. #define DUK_STRIDX_TO_STRING 249 /* 'toString' */
  527. #define DUK_STRIDX_CONSTRUCTOR 250 /* 'constructor' */
  528. #define DUK_STRIDX_SET 251 /* 'set' */
  529. #define DUK_STRIDX_GET 252 /* 'get' */
  530. #define DUK_STRIDX_ENUMERABLE 253 /* 'enumerable' */
  531. #define DUK_STRIDX_CONFIGURABLE 254 /* 'configurable' */
  532. #define DUK_STRIDX_WRITABLE 255 /* 'writable' */
  533. #define DUK_STRIDX_VALUE 256 /* 'value' */
  534. #define DUK_STRIDX_KEYS 257 /* 'keys' */
  535. #define DUK_STRIDX_IS_EXTENSIBLE 258 /* 'isExtensible' */
  536. #define DUK_STRIDX_IS_FROZEN 259 /* 'isFrozen' */
  537. #define DUK_STRIDX_IS_SEALED 260 /* 'isSealed' */
  538. #define DUK_STRIDX_PREVENT_EXTENSIONS 261 /* 'preventExtensions' */
  539. #define DUK_STRIDX_FREEZE 262 /* 'freeze' */
  540. #define DUK_STRIDX_SEAL 263 /* 'seal' */
  541. #define DUK_STRIDX_DEFINE_PROPERTIES 264 /* 'defineProperties' */
  542. #define DUK_STRIDX_DEFINE_PROPERTY 265 /* 'defineProperty' */
  543. #define DUK_STRIDX_CREATE 266 /* 'create' */
  544. #define DUK_STRIDX_GET_OWN_PROPERTY_NAMES 267 /* 'getOwnPropertyNames' */
  545. #define DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR 268 /* 'getOwnPropertyDescriptor' */
  546. #define DUK_STRIDX_GET_PROTOTYPE_OF 269 /* 'getPrototypeOf' */
  547. #define DUK_STRIDX_PROTOTYPE 270 /* 'prototype' */
  548. #define DUK_STRIDX_LENGTH 271 /* 'length' */
  549. #define DUK_STRIDX_ALERT 272 /* 'alert' */
  550. #define DUK_STRIDX_PRINT 273 /* 'print' */
  551. #define DUK_STRIDX_UNESCAPE 274 /* 'unescape' */
  552. #define DUK_STRIDX_ESCAPE 275 /* 'escape' */
  553. #define DUK_STRIDX_ENCODE_URI_COMPONENT 276 /* 'encodeURIComponent' */
  554. #define DUK_STRIDX_ENCODE_URI 277 /* 'encodeURI' */
  555. #define DUK_STRIDX_DECODE_URI_COMPONENT 278 /* 'decodeURIComponent' */
  556. #define DUK_STRIDX_DECODE_URI 279 /* 'decodeURI' */
  557. #define DUK_STRIDX_IS_FINITE 280 /* 'isFinite' */
  558. #define DUK_STRIDX_IS_NAN 281 /* 'isNaN' */
  559. #define DUK_STRIDX_PARSE_FLOAT 282 /* 'parseFloat' */
  560. #define DUK_STRIDX_PARSE_INT 283 /* 'parseInt' */
  561. #define DUK_STRIDX_EVAL 284 /* 'eval' */
  562. #define DUK_STRIDX_URI_ERROR 285 /* 'URIError' */
  563. #define DUK_STRIDX_TYPE_ERROR 286 /* 'TypeError' */
  564. #define DUK_STRIDX_SYNTAX_ERROR 287 /* 'SyntaxError' */
  565. #define DUK_STRIDX_REFERENCE_ERROR 288 /* 'ReferenceError' */
  566. #define DUK_STRIDX_RANGE_ERROR 289 /* 'RangeError' */
  567. #define DUK_STRIDX_EVAL_ERROR 290 /* 'EvalError' */
  568. #define DUK_STRIDX_BREAK 291 /* 'break' */
  569. #define DUK_STRIDX_CASE 292 /* 'case' */
  570. #define DUK_STRIDX_CATCH 293 /* 'catch' */
  571. #define DUK_STRIDX_CONTINUE 294 /* 'continue' */
  572. #define DUK_STRIDX_DEBUGGER 295 /* 'debugger' */
  573. #define DUK_STRIDX_DEFAULT 296 /* 'default' */
  574. #define DUK_STRIDX_DELETE 297 /* 'delete' */
  575. #define DUK_STRIDX_DO 298 /* 'do' */
  576. #define DUK_STRIDX_ELSE 299 /* 'else' */
  577. #define DUK_STRIDX_FINALLY 300 /* 'finally' */
  578. #define DUK_STRIDX_FOR 301 /* 'for' */
  579. #define DUK_STRIDX_LC_FUNCTION 302 /* 'function' */
  580. #define DUK_STRIDX_IF 303 /* 'if' */
  581. #define DUK_STRIDX_IN 304 /* 'in' */
  582. #define DUK_STRIDX_INSTANCEOF 305 /* 'instanceof' */
  583. #define DUK_STRIDX_NEW 306 /* 'new' */
  584. #define DUK_STRIDX_RETURN 307 /* 'return' */
  585. #define DUK_STRIDX_SWITCH 308 /* 'switch' */
  586. #define DUK_STRIDX_THIS 309 /* 'this' */
  587. #define DUK_STRIDX_THROW 310 /* 'throw' */
  588. #define DUK_STRIDX_TRY 311 /* 'try' */
  589. #define DUK_STRIDX_TYPEOF 312 /* 'typeof' */
  590. #define DUK_STRIDX_VAR 313 /* 'var' */
  591. #define DUK_STRIDX_VOID 314 /* 'void' */
  592. #define DUK_STRIDX_WHILE 315 /* 'while' */
  593. #define DUK_STRIDX_WITH 316 /* 'with' */
  594. #define DUK_STRIDX_CLASS 317 /* 'class' */
  595. #define DUK_STRIDX_CONST 318 /* 'const' */
  596. #define DUK_STRIDX_ENUM 319 /* 'enum' */
  597. #define DUK_STRIDX_EXPORT 320 /* 'export' */
  598. #define DUK_STRIDX_EXTENDS 321 /* 'extends' */
  599. #define DUK_STRIDX_IMPORT 322 /* 'import' */
  600. #define DUK_STRIDX_SUPER 323 /* 'super' */
  601. #define DUK_STRIDX_LC_NULL 324 /* 'null' */
  602. #define DUK_STRIDX_TRUE 325 /* 'true' */
  603. #define DUK_STRIDX_FALSE 326 /* 'false' */
  604. #define DUK_STRIDX_IMPLEMENTS 327 /* 'implements' */
  605. #define DUK_STRIDX_INTERFACE 328 /* 'interface' */
  606. #define DUK_STRIDX_LET 329 /* 'let' */
  607. #define DUK_STRIDX_PACKAGE 330 /* 'package' */
  608. #define DUK_STRIDX_PRIVATE 331 /* 'private' */
  609. #define DUK_STRIDX_PROTECTED 332 /* 'protected' */
  610. #define DUK_STRIDX_PUBLIC 333 /* 'public' */
  611. #define DUK_STRIDX_STATIC 334 /* 'static' */
  612. #define DUK_STRIDX_YIELD 335 /* 'yield' */
  613. #define DUK_HEAP_STRING_UC_LOGGER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_LOGGER)
  614. #define DUK_HTHREAD_STRING_UC_LOGGER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_LOGGER)
  615. #define DUK_HEAP_STRING_UC_THREAD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_THREAD)
  616. #define DUK_HTHREAD_STRING_UC_THREAD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_THREAD)
  617. #define DUK_HEAP_STRING_UC_POINTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_POINTER)
  618. #define DUK_HTHREAD_STRING_UC_POINTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_POINTER)
  619. #define DUK_HEAP_STRING_UC_BUFFER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_BUFFER)
  620. #define DUK_HTHREAD_STRING_UC_BUFFER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_BUFFER)
  621. #define DUK_HEAP_STRING_DEC_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEC_ENV)
  622. #define DUK_HTHREAD_STRING_DEC_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEC_ENV)
  623. #define DUK_HEAP_STRING_OBJ_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_OBJ_ENV)
  624. #define DUK_HTHREAD_STRING_OBJ_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_OBJ_ENV)
  625. #define DUK_HEAP_STRING_EMPTY_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EMPTY_STRING)
  626. #define DUK_HTHREAD_STRING_EMPTY_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EMPTY_STRING)
  627. #define DUK_HEAP_STRING_GLOBAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GLOBAL)
  628. #define DUK_HTHREAD_STRING_GLOBAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GLOBAL)
  629. #define DUK_HEAP_STRING_UC_ARGUMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_ARGUMENTS)
  630. #define DUK_HTHREAD_STRING_UC_ARGUMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_ARGUMENTS)
  631. #define DUK_HEAP_STRING_JSON(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON)
  632. #define DUK_HTHREAD_STRING_JSON(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON)
  633. #define DUK_HEAP_STRING_MATH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MATH)
  634. #define DUK_HTHREAD_STRING_MATH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MATH)
  635. #define DUK_HEAP_STRING_UC_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_ERROR)
  636. #define DUK_HTHREAD_STRING_UC_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_ERROR)
  637. #define DUK_HEAP_STRING_REG_EXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REG_EXP)
  638. #define DUK_HTHREAD_STRING_REG_EXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REG_EXP)
  639. #define DUK_HEAP_STRING_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DATE)
  640. #define DUK_HTHREAD_STRING_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DATE)
  641. #define DUK_HEAP_STRING_UC_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_NUMBER)
  642. #define DUK_HTHREAD_STRING_UC_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_NUMBER)
  643. #define DUK_HEAP_STRING_UC_BOOLEAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_BOOLEAN)
  644. #define DUK_HTHREAD_STRING_UC_BOOLEAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_BOOLEAN)
  645. #define DUK_HEAP_STRING_UC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_STRING)
  646. #define DUK_HTHREAD_STRING_UC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_STRING)
  647. #define DUK_HEAP_STRING_ARRAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ARRAY)
  648. #define DUK_HTHREAD_STRING_ARRAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ARRAY)
  649. #define DUK_HEAP_STRING_UC_FUNCTION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_FUNCTION)
  650. #define DUK_HTHREAD_STRING_UC_FUNCTION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_FUNCTION)
  651. #define DUK_HEAP_STRING_UC_OBJECT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_OBJECT)
  652. #define DUK_HTHREAD_STRING_UC_OBJECT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_OBJECT)
  653. #define DUK_HEAP_STRING_UC_NULL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_NULL)
  654. #define DUK_HTHREAD_STRING_UC_NULL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_NULL)
  655. #define DUK_HEAP_STRING_UC_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_UNDEFINED)
  656. #define DUK_HTHREAD_STRING_UC_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_UNDEFINED)
  657. #define DUK_HEAP_STRING_JSON_EXT_FUNCTION2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_FUNCTION2)
  658. #define DUK_HTHREAD_STRING_JSON_EXT_FUNCTION2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_FUNCTION2)
  659. #define DUK_HEAP_STRING_JSON_EXT_FUNCTION1(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_FUNCTION1)
  660. #define DUK_HTHREAD_STRING_JSON_EXT_FUNCTION1(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_FUNCTION1)
  661. #define DUK_HEAP_STRING_JSON_EXT_NEGINF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_NEGINF)
  662. #define DUK_HTHREAD_STRING_JSON_EXT_NEGINF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_NEGINF)
  663. #define DUK_HEAP_STRING_JSON_EXT_POSINF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_POSINF)
  664. #define DUK_HTHREAD_STRING_JSON_EXT_POSINF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_POSINF)
  665. #define DUK_HEAP_STRING_JSON_EXT_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_NAN)
  666. #define DUK_HTHREAD_STRING_JSON_EXT_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_NAN)
  667. #define DUK_HEAP_STRING_JSON_EXT_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_UNDEFINED)
  668. #define DUK_HTHREAD_STRING_JSON_EXT_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_UNDEFINED)
  669. #define DUK_HEAP_STRING_TO_LOG_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOG_STRING)
  670. #define DUK_HTHREAD_STRING_TO_LOG_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOG_STRING)
  671. #define DUK_HEAP_STRING_CLOG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CLOG)
  672. #define DUK_HTHREAD_STRING_CLOG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CLOG)
  673. #define DUK_HEAP_STRING_LC_L(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_L)
  674. #define DUK_HTHREAD_STRING_LC_L(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_L)
  675. #define DUK_HEAP_STRING_LC_N(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_N)
  676. #define DUK_HTHREAD_STRING_LC_N(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_N)
  677. #define DUK_HEAP_STRING_LC_FATAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_FATAL)
  678. #define DUK_HTHREAD_STRING_LC_FATAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_FATAL)
  679. #define DUK_HEAP_STRING_LC_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_ERROR)
  680. #define DUK_HTHREAD_STRING_LC_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_ERROR)
  681. #define DUK_HEAP_STRING_LC_WARN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_WARN)
  682. #define DUK_HTHREAD_STRING_LC_WARN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_WARN)
  683. #define DUK_HEAP_STRING_LC_DEBUG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_DEBUG)
  684. #define DUK_HTHREAD_STRING_LC_DEBUG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_DEBUG)
  685. #define DUK_HEAP_STRING_LC_TRACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_TRACE)
  686. #define DUK_HTHREAD_STRING_LC_TRACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_TRACE)
  687. #define DUK_HEAP_STRING_RAW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RAW)
  688. #define DUK_HTHREAD_STRING_RAW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RAW)
  689. #define DUK_HEAP_STRING_FMT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FMT)
  690. #define DUK_HTHREAD_STRING_FMT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FMT)
  691. #define DUK_HEAP_STRING_CURRENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CURRENT)
  692. #define DUK_HTHREAD_STRING_CURRENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CURRENT)
  693. #define DUK_HEAP_STRING_RESUME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RESUME)
  694. #define DUK_HTHREAD_STRING_RESUME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RESUME)
  695. #define DUK_HEAP_STRING_COMPACT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMPACT)
  696. #define DUK_HTHREAD_STRING_COMPACT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMPACT)
  697. #define DUK_HEAP_STRING_JC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JC)
  698. #define DUK_HTHREAD_STRING_JC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JC)
  699. #define DUK_HEAP_STRING_JX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JX)
  700. #define DUK_HTHREAD_STRING_JX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JX)
  701. #define DUK_HEAP_STRING_BASE64(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BASE64)
  702. #define DUK_HTHREAD_STRING_BASE64(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BASE64)
  703. #define DUK_HEAP_STRING_HEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HEX)
  704. #define DUK_HTHREAD_STRING_HEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HEX)
  705. #define DUK_HEAP_STRING_DEC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEC)
  706. #define DUK_HTHREAD_STRING_DEC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEC)
  707. #define DUK_HEAP_STRING_ENC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENC)
  708. #define DUK_HTHREAD_STRING_ENC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENC)
  709. #define DUK_HEAP_STRING_FIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FIN)
  710. #define DUK_HTHREAD_STRING_FIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FIN)
  711. #define DUK_HEAP_STRING_GC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GC)
  712. #define DUK_HTHREAD_STRING_GC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GC)
  713. #define DUK_HEAP_STRING_ACT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ACT)
  714. #define DUK_HTHREAD_STRING_ACT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ACT)
  715. #define DUK_HEAP_STRING_LC_INFO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_INFO)
  716. #define DUK_HTHREAD_STRING_LC_INFO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_INFO)
  717. #define DUK_HEAP_STRING_VERSION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VERSION)
  718. #define DUK_HTHREAD_STRING_VERSION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VERSION)
  719. #define DUK_HEAP_STRING_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENV)
  720. #define DUK_HTHREAD_STRING_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENV)
  721. #define DUK_HEAP_STRING_MOD_LOADED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MOD_LOADED)
  722. #define DUK_HTHREAD_STRING_MOD_LOADED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MOD_LOADED)
  723. #define DUK_HEAP_STRING_MOD_SEARCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MOD_SEARCH)
  724. #define DUK_HTHREAD_STRING_MOD_SEARCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MOD_SEARCH)
  725. #define DUK_HEAP_STRING_ERR_THROW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ERR_THROW)
  726. #define DUK_HTHREAD_STRING_ERR_THROW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ERR_THROW)
  727. #define DUK_HEAP_STRING_ERR_CREATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ERR_CREATE)
  728. #define DUK_HTHREAD_STRING_ERR_CREATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ERR_CREATE)
  729. #define DUK_HEAP_STRING_COMPILE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMPILE)
  730. #define DUK_HTHREAD_STRING_COMPILE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMPILE)
  731. #define DUK_HEAP_STRING_INT_REGBASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_REGBASE)
  732. #define DUK_HTHREAD_STRING_INT_REGBASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_REGBASE)
  733. #define DUK_HEAP_STRING_INT_THREAD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_THREAD)
  734. #define DUK_HTHREAD_STRING_INT_THREAD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_THREAD)
  735. #define DUK_HEAP_STRING_INT_HANDLER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_HANDLER)
  736. #define DUK_HTHREAD_STRING_INT_HANDLER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_HANDLER)
  737. #define DUK_HEAP_STRING_INT_FINALIZER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_FINALIZER)
  738. #define DUK_HTHREAD_STRING_INT_FINALIZER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_FINALIZER)
  739. #define DUK_HEAP_STRING_INT_CALLEE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_CALLEE)
  740. #define DUK_HTHREAD_STRING_INT_CALLEE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_CALLEE)
  741. #define DUK_HEAP_STRING_INT_MAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_MAP)
  742. #define DUK_HTHREAD_STRING_INT_MAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_MAP)
  743. #define DUK_HEAP_STRING_INT_ARGS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_ARGS)
  744. #define DUK_HTHREAD_STRING_INT_ARGS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_ARGS)
  745. #define DUK_HEAP_STRING_INT_THIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_THIS)
  746. #define DUK_HTHREAD_STRING_INT_THIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_THIS)
  747. #define DUK_HEAP_STRING_INT_PC2LINE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_PC2LINE)
  748. #define DUK_HTHREAD_STRING_INT_PC2LINE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_PC2LINE)
  749. #define DUK_HEAP_STRING_INT_SOURCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_SOURCE)
  750. #define DUK_HTHREAD_STRING_INT_SOURCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_SOURCE)
  751. #define DUK_HEAP_STRING_INT_VARENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VARENV)
  752. #define DUK_HTHREAD_STRING_INT_VARENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VARENV)
  753. #define DUK_HEAP_STRING_INT_LEXENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_LEXENV)
  754. #define DUK_HTHREAD_STRING_INT_LEXENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_LEXENV)
  755. #define DUK_HEAP_STRING_INT_VARMAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VARMAP)
  756. #define DUK_HTHREAD_STRING_INT_VARMAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VARMAP)
  757. #define DUK_HEAP_STRING_INT_FORMALS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_FORMALS)
  758. #define DUK_HTHREAD_STRING_INT_FORMALS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_FORMALS)
  759. #define DUK_HEAP_STRING_INT_BYTECODE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_BYTECODE)
  760. #define DUK_HTHREAD_STRING_INT_BYTECODE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_BYTECODE)
  761. #define DUK_HEAP_STRING_INT_NEXT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_NEXT)
  762. #define DUK_HTHREAD_STRING_INT_NEXT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_NEXT)
  763. #define DUK_HEAP_STRING_INT_TARGET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_TARGET)
  764. #define DUK_HTHREAD_STRING_INT_TARGET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_TARGET)
  765. #define DUK_HEAP_STRING_INT_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VALUE)
  766. #define DUK_HTHREAD_STRING_INT_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VALUE)
  767. #define DUK_HEAP_STRING_LC_POINTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_POINTER)
  768. #define DUK_HTHREAD_STRING_LC_POINTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_POINTER)
  769. #define DUK_HEAP_STRING_LC_BUFFER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_BUFFER)
  770. #define DUK_HTHREAD_STRING_LC_BUFFER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_BUFFER)
  771. #define DUK_HEAP_STRING_INT_TRACEDATA(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_TRACEDATA)
  772. #define DUK_HTHREAD_STRING_INT_TRACEDATA(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_TRACEDATA)
  773. #define DUK_HEAP_STRING_LINE_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LINE_NUMBER)
  774. #define DUK_HTHREAD_STRING_LINE_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LINE_NUMBER)
  775. #define DUK_HEAP_STRING_FILE_NAME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FILE_NAME)
  776. #define DUK_HTHREAD_STRING_FILE_NAME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FILE_NAME)
  777. #define DUK_HEAP_STRING_PC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PC)
  778. #define DUK_HTHREAD_STRING_PC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PC)
  779. #define DUK_HEAP_STRING_STACK(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STACK)
  780. #define DUK_HTHREAD_STRING_STACK(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STACK)
  781. #define DUK_HEAP_STRING_THROW_TYPE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THROW_TYPE_ERROR)
  782. #define DUK_HTHREAD_STRING_THROW_TYPE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THROW_TYPE_ERROR)
  783. #define DUK_HEAP_STRING_DUKTAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DUKTAPE)
  784. #define DUK_HTHREAD_STRING_DUKTAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DUKTAPE)
  785. #define DUK_HEAP_STRING_ID(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ID)
  786. #define DUK_HTHREAD_STRING_ID(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ID)
  787. #define DUK_HEAP_STRING_REQUIRE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REQUIRE)
  788. #define DUK_HTHREAD_STRING_REQUIRE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REQUIRE)
  789. #define DUK_HEAP_STRING___PROTO__(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX___PROTO__)
  790. #define DUK_HTHREAD_STRING___PROTO__(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX___PROTO__)
  791. #define DUK_HEAP_STRING_SET_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_PROTOTYPE_OF)
  792. #define DUK_HTHREAD_STRING_SET_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_PROTOTYPE_OF)
  793. #define DUK_HEAP_STRING_OWN_KEYS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_OWN_KEYS)
  794. #define DUK_HTHREAD_STRING_OWN_KEYS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_OWN_KEYS)
  795. #define DUK_HEAP_STRING_ENUMERATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUMERATE)
  796. #define DUK_HTHREAD_STRING_ENUMERATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUMERATE)
  797. #define DUK_HEAP_STRING_DELETE_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DELETE_PROPERTY)
  798. #define DUK_HTHREAD_STRING_DELETE_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DELETE_PROPERTY)
  799. #define DUK_HEAP_STRING_HAS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HAS)
  800. #define DUK_HTHREAD_STRING_HAS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HAS)
  801. #define DUK_HEAP_STRING_PROXY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROXY)
  802. #define DUK_HTHREAD_STRING_PROXY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROXY)
  803. #define DUK_HEAP_STRING_CALLEE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALLEE)
  804. #define DUK_HTHREAD_STRING_CALLEE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALLEE)
  805. #define DUK_HEAP_STRING_INVALID_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INVALID_DATE)
  806. #define DUK_HTHREAD_STRING_INVALID_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INVALID_DATE)
  807. #define DUK_HEAP_STRING_BRACKETED_ELLIPSIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BRACKETED_ELLIPSIS)
  808. #define DUK_HTHREAD_STRING_BRACKETED_ELLIPSIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BRACKETED_ELLIPSIS)
  809. #define DUK_HEAP_STRING_NEWLINE_TAB(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEWLINE_TAB)
  810. #define DUK_HTHREAD_STRING_NEWLINE_TAB(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEWLINE_TAB)
  811. #define DUK_HEAP_STRING_SPACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPACE)
  812. #define DUK_HTHREAD_STRING_SPACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPACE)
  813. #define DUK_HEAP_STRING_COMMA(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMMA)
  814. #define DUK_HTHREAD_STRING_COMMA(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMMA)
  815. #define DUK_HEAP_STRING_MINUS_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MINUS_ZERO)
  816. #define DUK_HTHREAD_STRING_MINUS_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MINUS_ZERO)
  817. #define DUK_HEAP_STRING_PLUS_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PLUS_ZERO)
  818. #define DUK_HTHREAD_STRING_PLUS_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PLUS_ZERO)
  819. #define DUK_HEAP_STRING_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ZERO)
  820. #define DUK_HTHREAD_STRING_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ZERO)
  821. #define DUK_HEAP_STRING_MINUS_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MINUS_INFINITY)
  822. #define DUK_HTHREAD_STRING_MINUS_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MINUS_INFINITY)
  823. #define DUK_HEAP_STRING_PLUS_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PLUS_INFINITY)
  824. #define DUK_HTHREAD_STRING_PLUS_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PLUS_INFINITY)
  825. #define DUK_HEAP_STRING_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INFINITY)
  826. #define DUK_HTHREAD_STRING_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INFINITY)
  827. #define DUK_HEAP_STRING_LC_OBJECT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_OBJECT)
  828. #define DUK_HTHREAD_STRING_LC_OBJECT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_OBJECT)
  829. #define DUK_HEAP_STRING_LC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_STRING)
  830. #define DUK_HTHREAD_STRING_LC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_STRING)
  831. #define DUK_HEAP_STRING_LC_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_NUMBER)
  832. #define DUK_HTHREAD_STRING_LC_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_NUMBER)
  833. #define DUK_HEAP_STRING_LC_BOOLEAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_BOOLEAN)
  834. #define DUK_HTHREAD_STRING_LC_BOOLEAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_BOOLEAN)
  835. #define DUK_HEAP_STRING_LC_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_UNDEFINED)
  836. #define DUK_HTHREAD_STRING_LC_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_UNDEFINED)
  837. #define DUK_HEAP_STRING_STRINGIFY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STRINGIFY)
  838. #define DUK_HTHREAD_STRING_STRINGIFY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STRINGIFY)
  839. #define DUK_HEAP_STRING_TAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TAN)
  840. #define DUK_HTHREAD_STRING_TAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TAN)
  841. #define DUK_HEAP_STRING_SQRT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT)
  842. #define DUK_HTHREAD_STRING_SQRT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT)
  843. #define DUK_HEAP_STRING_SIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SIN)
  844. #define DUK_HTHREAD_STRING_SIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SIN)
  845. #define DUK_HEAP_STRING_ROUND(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ROUND)
  846. #define DUK_HTHREAD_STRING_ROUND(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ROUND)
  847. #define DUK_HEAP_STRING_RANDOM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RANDOM)
  848. #define DUK_HTHREAD_STRING_RANDOM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RANDOM)
  849. #define DUK_HEAP_STRING_POW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POW)
  850. #define DUK_HTHREAD_STRING_POW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POW)
  851. #define DUK_HEAP_STRING_MIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MIN)
  852. #define DUK_HTHREAD_STRING_MIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MIN)
  853. #define DUK_HEAP_STRING_MAX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAX)
  854. #define DUK_HTHREAD_STRING_MAX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAX)
  855. #define DUK_HEAP_STRING_LOG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG)
  856. #define DUK_HTHREAD_STRING_LOG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG)
  857. #define DUK_HEAP_STRING_FLOOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FLOOR)
  858. #define DUK_HTHREAD_STRING_FLOOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FLOOR)
  859. #define DUK_HEAP_STRING_EXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXP)
  860. #define DUK_HTHREAD_STRING_EXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXP)
  861. #define DUK_HEAP_STRING_COS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COS)
  862. #define DUK_HTHREAD_STRING_COS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COS)
  863. #define DUK_HEAP_STRING_CEIL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CEIL)
  864. #define DUK_HTHREAD_STRING_CEIL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CEIL)
  865. #define DUK_HEAP_STRING_ATAN2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ATAN2)
  866. #define DUK_HTHREAD_STRING_ATAN2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ATAN2)
  867. #define DUK_HEAP_STRING_ATAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ATAN)
  868. #define DUK_HTHREAD_STRING_ATAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ATAN)
  869. #define DUK_HEAP_STRING_ASIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ASIN)
  870. #define DUK_HTHREAD_STRING_ASIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ASIN)
  871. #define DUK_HEAP_STRING_ACOS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ACOS)
  872. #define DUK_HTHREAD_STRING_ACOS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ACOS)
  873. #define DUK_HEAP_STRING_ABS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ABS)
  874. #define DUK_HTHREAD_STRING_ABS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ABS)
  875. #define DUK_HEAP_STRING_SQRT2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT2)
  876. #define DUK_HTHREAD_STRING_SQRT2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT2)
  877. #define DUK_HEAP_STRING_SQRT1_2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT1_2)
  878. #define DUK_HTHREAD_STRING_SQRT1_2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT1_2)
  879. #define DUK_HEAP_STRING_PI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PI)
  880. #define DUK_HTHREAD_STRING_PI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PI)
  881. #define DUK_HEAP_STRING_LOG10E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG10E)
  882. #define DUK_HTHREAD_STRING_LOG10E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG10E)
  883. #define DUK_HEAP_STRING_LOG2E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG2E)
  884. #define DUK_HTHREAD_STRING_LOG2E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG2E)
  885. #define DUK_HEAP_STRING_LN2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LN2)
  886. #define DUK_HTHREAD_STRING_LN2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LN2)
  887. #define DUK_HEAP_STRING_LN10(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LN10)
  888. #define DUK_HTHREAD_STRING_LN10(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LN10)
  889. #define DUK_HEAP_STRING_E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_E)
  890. #define DUK_HTHREAD_STRING_E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_E)
  891. #define DUK_HEAP_STRING_MESSAGE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MESSAGE)
  892. #define DUK_HTHREAD_STRING_MESSAGE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MESSAGE)
  893. #define DUK_HEAP_STRING_NAME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NAME)
  894. #define DUK_HTHREAD_STRING_NAME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NAME)
  895. #define DUK_HEAP_STRING_INPUT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INPUT)
  896. #define DUK_HTHREAD_STRING_INPUT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INPUT)
  897. #define DUK_HEAP_STRING_INDEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INDEX)
  898. #define DUK_HTHREAD_STRING_INDEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INDEX)
  899. #define DUK_HEAP_STRING_ESCAPED_EMPTY_REGEXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ESCAPED_EMPTY_REGEXP)
  900. #define DUK_HTHREAD_STRING_ESCAPED_EMPTY_REGEXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ESCAPED_EMPTY_REGEXP)
  901. #define DUK_HEAP_STRING_LAST_INDEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LAST_INDEX)
  902. #define DUK_HTHREAD_STRING_LAST_INDEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LAST_INDEX)
  903. #define DUK_HEAP_STRING_MULTILINE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MULTILINE)
  904. #define DUK_HTHREAD_STRING_MULTILINE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MULTILINE)
  905. #define DUK_HEAP_STRING_IGNORE_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IGNORE_CASE)
  906. #define DUK_HTHREAD_STRING_IGNORE_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IGNORE_CASE)
  907. #define DUK_HEAP_STRING_SOURCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SOURCE)
  908. #define DUK_HTHREAD_STRING_SOURCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SOURCE)
  909. #define DUK_HEAP_STRING_TEST(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TEST)
  910. #define DUK_HTHREAD_STRING_TEST(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TEST)
  911. #define DUK_HEAP_STRING_EXEC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXEC)
  912. #define DUK_HTHREAD_STRING_EXEC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXEC)
  913. #define DUK_HEAP_STRING_TO_GMT_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_GMT_STRING)
  914. #define DUK_HTHREAD_STRING_TO_GMT_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_GMT_STRING)
  915. #define DUK_HEAP_STRING_SET_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_YEAR)
  916. #define DUK_HTHREAD_STRING_SET_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_YEAR)
  917. #define DUK_HEAP_STRING_GET_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_YEAR)
  918. #define DUK_HTHREAD_STRING_GET_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_YEAR)
  919. #define DUK_HEAP_STRING_TO_JSON(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_JSON)
  920. #define DUK_HTHREAD_STRING_TO_JSON(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_JSON)
  921. #define DUK_HEAP_STRING_TO_ISO_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_ISO_STRING)
  922. #define DUK_HTHREAD_STRING_TO_ISO_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_ISO_STRING)
  923. #define DUK_HEAP_STRING_TO_UTC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_UTC_STRING)
  924. #define DUK_HTHREAD_STRING_TO_UTC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_UTC_STRING)
  925. #define DUK_HEAP_STRING_SET_UTC_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_FULL_YEAR)
  926. #define DUK_HTHREAD_STRING_SET_UTC_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_FULL_YEAR)
  927. #define DUK_HEAP_STRING_SET_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_FULL_YEAR)
  928. #define DUK_HTHREAD_STRING_SET_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_FULL_YEAR)
  929. #define DUK_HEAP_STRING_SET_UTC_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MONTH)
  930. #define DUK_HTHREAD_STRING_SET_UTC_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MONTH)
  931. #define DUK_HEAP_STRING_SET_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MONTH)
  932. #define DUK_HTHREAD_STRING_SET_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MONTH)
  933. #define DUK_HEAP_STRING_SET_UTC_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_DATE)
  934. #define DUK_HTHREAD_STRING_SET_UTC_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_DATE)
  935. #define DUK_HEAP_STRING_SET_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_DATE)
  936. #define DUK_HTHREAD_STRING_SET_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_DATE)
  937. #define DUK_HEAP_STRING_SET_UTC_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_HOURS)
  938. #define DUK_HTHREAD_STRING_SET_UTC_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_HOURS)
  939. #define DUK_HEAP_STRING_SET_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_HOURS)
  940. #define DUK_HTHREAD_STRING_SET_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_HOURS)
  941. #define DUK_HEAP_STRING_SET_UTC_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MINUTES)
  942. #define DUK_HTHREAD_STRING_SET_UTC_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MINUTES)
  943. #define DUK_HEAP_STRING_SET_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MINUTES)
  944. #define DUK_HTHREAD_STRING_SET_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MINUTES)
  945. #define DUK_HEAP_STRING_SET_UTC_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_SECONDS)
  946. #define DUK_HTHREAD_STRING_SET_UTC_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_SECONDS)
  947. #define DUK_HEAP_STRING_SET_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_SECONDS)
  948. #define DUK_HTHREAD_STRING_SET_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_SECONDS)
  949. #define DUK_HEAP_STRING_SET_UTC_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MILLISECONDS)
  950. #define DUK_HTHREAD_STRING_SET_UTC_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MILLISECONDS)
  951. #define DUK_HEAP_STRING_SET_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MILLISECONDS)
  952. #define DUK_HTHREAD_STRING_SET_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MILLISECONDS)
  953. #define DUK_HEAP_STRING_SET_TIME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_TIME)
  954. #define DUK_HTHREAD_STRING_SET_TIME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_TIME)
  955. #define DUK_HEAP_STRING_GET_TIMEZONE_OFFSET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_TIMEZONE_OFFSET)
  956. #define DUK_HTHREAD_STRING_GET_TIMEZONE_OFFSET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_TIMEZONE_OFFSET)
  957. #define DUK_HEAP_STRING_GET_UTC_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MILLISECONDS)
  958. #define DUK_HTHREAD_STRING_GET_UTC_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MILLISECONDS)
  959. #define DUK_HEAP_STRING_GET_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MILLISECONDS)
  960. #define DUK_HTHREAD_STRING_GET_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MILLISECONDS)
  961. #define DUK_HEAP_STRING_GET_UTC_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_SECONDS)
  962. #define DUK_HTHREAD_STRING_GET_UTC_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_SECONDS)
  963. #define DUK_HEAP_STRING_GET_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_SECONDS)
  964. #define DUK_HTHREAD_STRING_GET_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_SECONDS)
  965. #define DUK_HEAP_STRING_GET_UTC_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MINUTES)
  966. #define DUK_HTHREAD_STRING_GET_UTC_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MINUTES)
  967. #define DUK_HEAP_STRING_GET_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MINUTES)
  968. #define DUK_HTHREAD_STRING_GET_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MINUTES)
  969. #define DUK_HEAP_STRING_GET_UTC_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_HOURS)
  970. #define DUK_HTHREAD_STRING_GET_UTC_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_HOURS)
  971. #define DUK_HEAP_STRING_GET_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_HOURS)
  972. #define DUK_HTHREAD_STRING_GET_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_HOURS)
  973. #define DUK_HEAP_STRING_GET_UTC_DAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_DAY)
  974. #define DUK_HTHREAD_STRING_GET_UTC_DAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_DAY)
  975. #define DUK_HEAP_STRING_GET_DAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_DAY)
  976. #define DUK_HTHREAD_STRING_GET_DAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_DAY)
  977. #define DUK_HEAP_STRING_GET_UTC_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_DATE)
  978. #define DUK_HTHREAD_STRING_GET_UTC_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_DATE)
  979. #define DUK_HEAP_STRING_GET_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_DATE)
  980. #define DUK_HTHREAD_STRING_GET_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_DATE)
  981. #define DUK_HEAP_STRING_GET_UTC_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MONTH)
  982. #define DUK_HTHREAD_STRING_GET_UTC_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MONTH)
  983. #define DUK_HEAP_STRING_GET_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MONTH)
  984. #define DUK_HTHREAD_STRING_GET_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MONTH)
  985. #define DUK_HEAP_STRING_GET_UTC_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_FULL_YEAR)
  986. #define DUK_HTHREAD_STRING_GET_UTC_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_FULL_YEAR)
  987. #define DUK_HEAP_STRING_GET_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_FULL_YEAR)
  988. #define DUK_HTHREAD_STRING_GET_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_FULL_YEAR)
  989. #define DUK_HEAP_STRING_GET_TIME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_TIME)
  990. #define DUK_HTHREAD_STRING_GET_TIME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_TIME)
  991. #define DUK_HEAP_STRING_TO_LOCALE_TIME_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_TIME_STRING)
  992. #define DUK_HTHREAD_STRING_TO_LOCALE_TIME_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_TIME_STRING)
  993. #define DUK_HEAP_STRING_TO_LOCALE_DATE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_DATE_STRING)
  994. #define DUK_HTHREAD_STRING_TO_LOCALE_DATE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_DATE_STRING)
  995. #define DUK_HEAP_STRING_TO_TIME_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_TIME_STRING)
  996. #define DUK_HTHREAD_STRING_TO_TIME_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_TIME_STRING)
  997. #define DUK_HEAP_STRING_TO_DATE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_DATE_STRING)
  998. #define DUK_HTHREAD_STRING_TO_DATE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_DATE_STRING)
  999. #define DUK_HEAP_STRING_NOW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NOW)
  1000. #define DUK_HTHREAD_STRING_NOW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NOW)
  1001. #define DUK_HEAP_STRING_UTC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UTC)
  1002. #define DUK_HTHREAD_STRING_UTC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UTC)
  1003. #define DUK_HEAP_STRING_PARSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE)
  1004. #define DUK_HTHREAD_STRING_PARSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE)
  1005. #define DUK_HEAP_STRING_TO_PRECISION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_PRECISION)
  1006. #define DUK_HTHREAD_STRING_TO_PRECISION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_PRECISION)
  1007. #define DUK_HEAP_STRING_TO_EXPONENTIAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_EXPONENTIAL)
  1008. #define DUK_HTHREAD_STRING_TO_EXPONENTIAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_EXPONENTIAL)
  1009. #define DUK_HEAP_STRING_TO_FIXED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_FIXED)
  1010. #define DUK_HTHREAD_STRING_TO_FIXED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_FIXED)
  1011. #define DUK_HEAP_STRING_POSITIVE_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POSITIVE_INFINITY)
  1012. #define DUK_HTHREAD_STRING_POSITIVE_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POSITIVE_INFINITY)
  1013. #define DUK_HEAP_STRING_NEGATIVE_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEGATIVE_INFINITY)
  1014. #define DUK_HTHREAD_STRING_NEGATIVE_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEGATIVE_INFINITY)
  1015. #define DUK_HEAP_STRING_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NAN)
  1016. #define DUK_HTHREAD_STRING_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NAN)
  1017. #define DUK_HEAP_STRING_MIN_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MIN_VALUE)
  1018. #define DUK_HTHREAD_STRING_MIN_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MIN_VALUE)
  1019. #define DUK_HEAP_STRING_MAX_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAX_VALUE)
  1020. #define DUK_HTHREAD_STRING_MAX_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAX_VALUE)
  1021. #define DUK_HEAP_STRING_SUBSTR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUBSTR)
  1022. #define DUK_HTHREAD_STRING_SUBSTR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUBSTR)
  1023. #define DUK_HEAP_STRING_TRIM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRIM)
  1024. #define DUK_HTHREAD_STRING_TRIM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRIM)
  1025. #define DUK_HEAP_STRING_TO_LOCALE_UPPER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_UPPER_CASE)
  1026. #define DUK_HTHREAD_STRING_TO_LOCALE_UPPER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_UPPER_CASE)
  1027. #define DUK_HEAP_STRING_TO_UPPER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_UPPER_CASE)
  1028. #define DUK_HTHREAD_STRING_TO_UPPER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_UPPER_CASE)
  1029. #define DUK_HEAP_STRING_TO_LOCALE_LOWER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_LOWER_CASE)
  1030. #define DUK_HTHREAD_STRING_TO_LOCALE_LOWER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_LOWER_CASE)
  1031. #define DUK_HEAP_STRING_TO_LOWER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOWER_CASE)
  1032. #define DUK_HTHREAD_STRING_TO_LOWER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOWER_CASE)
  1033. #define DUK_HEAP_STRING_SUBSTRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUBSTRING)
  1034. #define DUK_HTHREAD_STRING_SUBSTRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUBSTRING)
  1035. #define DUK_HEAP_STRING_SPLIT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPLIT)
  1036. #define DUK_HTHREAD_STRING_SPLIT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPLIT)
  1037. #define DUK_HEAP_STRING_SEARCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SEARCH)
  1038. #define DUK_HTHREAD_STRING_SEARCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SEARCH)
  1039. #define DUK_HEAP_STRING_REPLACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REPLACE)
  1040. #define DUK_HTHREAD_STRING_REPLACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REPLACE)
  1041. #define DUK_HEAP_STRING_MATCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MATCH)
  1042. #define DUK_HTHREAD_STRING_MATCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MATCH)
  1043. #define DUK_HEAP_STRING_LOCALE_COMPARE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOCALE_COMPARE)
  1044. #define DUK_HTHREAD_STRING_LOCALE_COMPARE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOCALE_COMPARE)
  1045. #define DUK_HEAP_STRING_CHAR_CODE_AT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CHAR_CODE_AT)
  1046. #define DUK_HTHREAD_STRING_CHAR_CODE_AT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CHAR_CODE_AT)
  1047. #define DUK_HEAP_STRING_CHAR_AT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CHAR_AT)
  1048. #define DUK_HTHREAD_STRING_CHAR_AT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CHAR_AT)
  1049. #define DUK_HEAP_STRING_FROM_CHAR_CODE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FROM_CHAR_CODE)
  1050. #define DUK_HTHREAD_STRING_FROM_CHAR_CODE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FROM_CHAR_CODE)
  1051. #define DUK_HEAP_STRING_REDUCE_RIGHT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REDUCE_RIGHT)
  1052. #define DUK_HTHREAD_STRING_REDUCE_RIGHT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REDUCE_RIGHT)
  1053. #define DUK_HEAP_STRING_REDUCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REDUCE)
  1054. #define DUK_HTHREAD_STRING_REDUCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REDUCE)
  1055. #define DUK_HEAP_STRING_FILTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FILTER)
  1056. #define DUK_HTHREAD_STRING_FILTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FILTER)
  1057. #define DUK_HEAP_STRING_MAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAP)
  1058. #define DUK_HTHREAD_STRING_MAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAP)
  1059. #define DUK_HEAP_STRING_FOR_EACH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FOR_EACH)
  1060. #define DUK_HTHREAD_STRING_FOR_EACH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FOR_EACH)
  1061. #define DUK_HEAP_STRING_SOME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SOME)
  1062. #define DUK_HTHREAD_STRING_SOME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SOME)
  1063. #define DUK_HEAP_STRING_EVERY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVERY)
  1064. #define DUK_HTHREAD_STRING_EVERY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVERY)
  1065. #define DUK_HEAP_STRING_LAST_INDEX_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LAST_INDEX_OF)
  1066. #define DUK_HTHREAD_STRING_LAST_INDEX_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LAST_INDEX_OF)
  1067. #define DUK_HEAP_STRING_INDEX_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INDEX_OF)
  1068. #define DUK_HTHREAD_STRING_INDEX_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INDEX_OF)
  1069. #define DUK_HEAP_STRING_UNSHIFT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UNSHIFT)
  1070. #define DUK_HTHREAD_STRING_UNSHIFT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UNSHIFT)
  1071. #define DUK_HEAP_STRING_SPLICE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPLICE)
  1072. #define DUK_HTHREAD_STRING_SPLICE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPLICE)
  1073. #define DUK_HEAP_STRING_SORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SORT)
  1074. #define DUK_HTHREAD_STRING_SORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SORT)
  1075. #define DUK_HEAP_STRING_SLICE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SLICE)
  1076. #define DUK_HTHREAD_STRING_SLICE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SLICE)
  1077. #define DUK_HEAP_STRING_SHIFT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SHIFT)
  1078. #define DUK_HTHREAD_STRING_SHIFT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SHIFT)
  1079. #define DUK_HEAP_STRING_REVERSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REVERSE)
  1080. #define DUK_HTHREAD_STRING_REVERSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REVERSE)
  1081. #define DUK_HEAP_STRING_PUSH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PUSH)
  1082. #define DUK_HTHREAD_STRING_PUSH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PUSH)
  1083. #define DUK_HEAP_STRING_POP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POP)
  1084. #define DUK_HTHREAD_STRING_POP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POP)
  1085. #define DUK_HEAP_STRING_JOIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JOIN)
  1086. #define DUK_HTHREAD_STRING_JOIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JOIN)
  1087. #define DUK_HEAP_STRING_CONCAT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONCAT)
  1088. #define DUK_HTHREAD_STRING_CONCAT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONCAT)
  1089. #define DUK_HEAP_STRING_IS_ARRAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_ARRAY)
  1090. #define DUK_HTHREAD_STRING_IS_ARRAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_ARRAY)
  1091. #define DUK_HEAP_STRING_LC_ARGUMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_ARGUMENTS)
  1092. #define DUK_HTHREAD_STRING_LC_ARGUMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_ARGUMENTS)
  1093. #define DUK_HEAP_STRING_CALLER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALLER)
  1094. #define DUK_HTHREAD_STRING_CALLER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALLER)
  1095. #define DUK_HEAP_STRING_BIND(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BIND)
  1096. #define DUK_HTHREAD_STRING_BIND(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BIND)
  1097. #define DUK_HEAP_STRING_CALL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALL)
  1098. #define DUK_HTHREAD_STRING_CALL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALL)
  1099. #define DUK_HEAP_STRING_APPLY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_APPLY)
  1100. #define DUK_HTHREAD_STRING_APPLY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_APPLY)
  1101. #define DUK_HEAP_STRING_PROPERTY_IS_ENUMERABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROPERTY_IS_ENUMERABLE)
  1102. #define DUK_HTHREAD_STRING_PROPERTY_IS_ENUMERABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROPERTY_IS_ENUMERABLE)
  1103. #define DUK_HEAP_STRING_IS_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_PROTOTYPE_OF)
  1104. #define DUK_HTHREAD_STRING_IS_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_PROTOTYPE_OF)
  1105. #define DUK_HEAP_STRING_HAS_OWN_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HAS_OWN_PROPERTY)
  1106. #define DUK_HTHREAD_STRING_HAS_OWN_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HAS_OWN_PROPERTY)
  1107. #define DUK_HEAP_STRING_VALUE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VALUE_OF)
  1108. #define DUK_HTHREAD_STRING_VALUE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VALUE_OF)
  1109. #define DUK_HEAP_STRING_TO_LOCALE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_STRING)
  1110. #define DUK_HTHREAD_STRING_TO_LOCALE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_STRING)
  1111. #define DUK_HEAP_STRING_TO_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_STRING)
  1112. #define DUK_HTHREAD_STRING_TO_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_STRING)
  1113. #define DUK_HEAP_STRING_CONSTRUCTOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONSTRUCTOR)
  1114. #define DUK_HTHREAD_STRING_CONSTRUCTOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONSTRUCTOR)
  1115. #define DUK_HEAP_STRING_SET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET)
  1116. #define DUK_HTHREAD_STRING_SET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET)
  1117. #define DUK_HEAP_STRING_GET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET)
  1118. #define DUK_HTHREAD_STRING_GET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET)
  1119. #define DUK_HEAP_STRING_ENUMERABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUMERABLE)
  1120. #define DUK_HTHREAD_STRING_ENUMERABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUMERABLE)
  1121. #define DUK_HEAP_STRING_CONFIGURABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONFIGURABLE)
  1122. #define DUK_HTHREAD_STRING_CONFIGURABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONFIGURABLE)
  1123. #define DUK_HEAP_STRING_WRITABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WRITABLE)
  1124. #define DUK_HTHREAD_STRING_WRITABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WRITABLE)
  1125. #define DUK_HEAP_STRING_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VALUE)
  1126. #define DUK_HTHREAD_STRING_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VALUE)
  1127. #define DUK_HEAP_STRING_KEYS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_KEYS)
  1128. #define DUK_HTHREAD_STRING_KEYS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_KEYS)
  1129. #define DUK_HEAP_STRING_IS_EXTENSIBLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_EXTENSIBLE)
  1130. #define DUK_HTHREAD_STRING_IS_EXTENSIBLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_EXTENSIBLE)
  1131. #define DUK_HEAP_STRING_IS_FROZEN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_FROZEN)
  1132. #define DUK_HTHREAD_STRING_IS_FROZEN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_FROZEN)
  1133. #define DUK_HEAP_STRING_IS_SEALED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_SEALED)
  1134. #define DUK_HTHREAD_STRING_IS_SEALED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_SEALED)
  1135. #define DUK_HEAP_STRING_PREVENT_EXTENSIONS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PREVENT_EXTENSIONS)
  1136. #define DUK_HTHREAD_STRING_PREVENT_EXTENSIONS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PREVENT_EXTENSIONS)
  1137. #define DUK_HEAP_STRING_FREEZE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FREEZE)
  1138. #define DUK_HTHREAD_STRING_FREEZE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FREEZE)
  1139. #define DUK_HEAP_STRING_SEAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SEAL)
  1140. #define DUK_HTHREAD_STRING_SEAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SEAL)
  1141. #define DUK_HEAP_STRING_DEFINE_PROPERTIES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFINE_PROPERTIES)
  1142. #define DUK_HTHREAD_STRING_DEFINE_PROPERTIES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFINE_PROPERTIES)
  1143. #define DUK_HEAP_STRING_DEFINE_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFINE_PROPERTY)
  1144. #define DUK_HTHREAD_STRING_DEFINE_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFINE_PROPERTY)
  1145. #define DUK_HEAP_STRING_CREATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CREATE)
  1146. #define DUK_HTHREAD_STRING_CREATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CREATE)
  1147. #define DUK_HEAP_STRING_GET_OWN_PROPERTY_NAMES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_OWN_PROPERTY_NAMES)
  1148. #define DUK_HTHREAD_STRING_GET_OWN_PROPERTY_NAMES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_OWN_PROPERTY_NAMES)
  1149. #define DUK_HEAP_STRING_GET_OWN_PROPERTY_DESCRIPTOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR)
  1150. #define DUK_HTHREAD_STRING_GET_OWN_PROPERTY_DESCRIPTOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR)
  1151. #define DUK_HEAP_STRING_GET_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_PROTOTYPE_OF)
  1152. #define DUK_HTHREAD_STRING_GET_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_PROTOTYPE_OF)
  1153. #define DUK_HEAP_STRING_PROTOTYPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROTOTYPE)
  1154. #define DUK_HTHREAD_STRING_PROTOTYPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROTOTYPE)
  1155. #define DUK_HEAP_STRING_LENGTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LENGTH)
  1156. #define DUK_HTHREAD_STRING_LENGTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LENGTH)
  1157. #define DUK_HEAP_STRING_ALERT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ALERT)
  1158. #define DUK_HTHREAD_STRING_ALERT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ALERT)
  1159. #define DUK_HEAP_STRING_PRINT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PRINT)
  1160. #define DUK_HTHREAD_STRING_PRINT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PRINT)
  1161. #define DUK_HEAP_STRING_UNESCAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UNESCAPE)
  1162. #define DUK_HTHREAD_STRING_UNESCAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UNESCAPE)
  1163. #define DUK_HEAP_STRING_ESCAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ESCAPE)
  1164. #define DUK_HTHREAD_STRING_ESCAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ESCAPE)
  1165. #define DUK_HEAP_STRING_ENCODE_URI_COMPONENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENCODE_URI_COMPONENT)
  1166. #define DUK_HTHREAD_STRING_ENCODE_URI_COMPONENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENCODE_URI_COMPONENT)
  1167. #define DUK_HEAP_STRING_ENCODE_URI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENCODE_URI)
  1168. #define DUK_HTHREAD_STRING_ENCODE_URI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENCODE_URI)
  1169. #define DUK_HEAP_STRING_DECODE_URI_COMPONENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DECODE_URI_COMPONENT)
  1170. #define DUK_HTHREAD_STRING_DECODE_URI_COMPONENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DECODE_URI_COMPONENT)
  1171. #define DUK_HEAP_STRING_DECODE_URI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DECODE_URI)
  1172. #define DUK_HTHREAD_STRING_DECODE_URI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DECODE_URI)
  1173. #define DUK_HEAP_STRING_IS_FINITE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_FINITE)
  1174. #define DUK_HTHREAD_STRING_IS_FINITE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_FINITE)
  1175. #define DUK_HEAP_STRING_IS_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_NAN)
  1176. #define DUK_HTHREAD_STRING_IS_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_NAN)
  1177. #define DUK_HEAP_STRING_PARSE_FLOAT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE_FLOAT)
  1178. #define DUK_HTHREAD_STRING_PARSE_FLOAT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE_FLOAT)
  1179. #define DUK_HEAP_STRING_PARSE_INT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE_INT)
  1180. #define DUK_HTHREAD_STRING_PARSE_INT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE_INT)
  1181. #define DUK_HEAP_STRING_EVAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVAL)
  1182. #define DUK_HTHREAD_STRING_EVAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVAL)
  1183. #define DUK_HEAP_STRING_URI_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_URI_ERROR)
  1184. #define DUK_HTHREAD_STRING_URI_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_URI_ERROR)
  1185. #define DUK_HEAP_STRING_TYPE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TYPE_ERROR)
  1186. #define DUK_HTHREAD_STRING_TYPE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TYPE_ERROR)
  1187. #define DUK_HEAP_STRING_SYNTAX_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SYNTAX_ERROR)
  1188. #define DUK_HTHREAD_STRING_SYNTAX_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SYNTAX_ERROR)
  1189. #define DUK_HEAP_STRING_REFERENCE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REFERENCE_ERROR)
  1190. #define DUK_HTHREAD_STRING_REFERENCE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REFERENCE_ERROR)
  1191. #define DUK_HEAP_STRING_RANGE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RANGE_ERROR)
  1192. #define DUK_HTHREAD_STRING_RANGE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RANGE_ERROR)
  1193. #define DUK_HEAP_STRING_EVAL_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVAL_ERROR)
  1194. #define DUK_HTHREAD_STRING_EVAL_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVAL_ERROR)
  1195. #define DUK_HEAP_STRING_BREAK(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BREAK)
  1196. #define DUK_HTHREAD_STRING_BREAK(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BREAK)
  1197. #define DUK_HEAP_STRING_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CASE)
  1198. #define DUK_HTHREAD_STRING_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CASE)
  1199. #define DUK_HEAP_STRING_CATCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CATCH)
  1200. #define DUK_HTHREAD_STRING_CATCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CATCH)
  1201. #define DUK_HEAP_STRING_CONTINUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONTINUE)
  1202. #define DUK_HTHREAD_STRING_CONTINUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONTINUE)
  1203. #define DUK_HEAP_STRING_DEBUGGER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEBUGGER)
  1204. #define DUK_HTHREAD_STRING_DEBUGGER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEBUGGER)
  1205. #define DUK_HEAP_STRING_DEFAULT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFAULT)
  1206. #define DUK_HTHREAD_STRING_DEFAULT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFAULT)
  1207. #define DUK_HEAP_STRING_DELETE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DELETE)
  1208. #define DUK_HTHREAD_STRING_DELETE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DELETE)
  1209. #define DUK_HEAP_STRING_DO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DO)
  1210. #define DUK_HTHREAD_STRING_DO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DO)
  1211. #define DUK_HEAP_STRING_ELSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ELSE)
  1212. #define DUK_HTHREAD_STRING_ELSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ELSE)
  1213. #define DUK_HEAP_STRING_FINALLY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FINALLY)
  1214. #define DUK_HTHREAD_STRING_FINALLY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FINALLY)
  1215. #define DUK_HEAP_STRING_FOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FOR)
  1216. #define DUK_HTHREAD_STRING_FOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FOR)
  1217. #define DUK_HEAP_STRING_LC_FUNCTION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_FUNCTION)
  1218. #define DUK_HTHREAD_STRING_LC_FUNCTION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_FUNCTION)
  1219. #define DUK_HEAP_STRING_IF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IF)
  1220. #define DUK_HTHREAD_STRING_IF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IF)
  1221. #define DUK_HEAP_STRING_IN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IN)
  1222. #define DUK_HTHREAD_STRING_IN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IN)
  1223. #define DUK_HEAP_STRING_INSTANCEOF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INSTANCEOF)
  1224. #define DUK_HTHREAD_STRING_INSTANCEOF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INSTANCEOF)
  1225. #define DUK_HEAP_STRING_NEW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEW)
  1226. #define DUK_HTHREAD_STRING_NEW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEW)
  1227. #define DUK_HEAP_STRING_RETURN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RETURN)
  1228. #define DUK_HTHREAD_STRING_RETURN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RETURN)
  1229. #define DUK_HEAP_STRING_SWITCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SWITCH)
  1230. #define DUK_HTHREAD_STRING_SWITCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SWITCH)
  1231. #define DUK_HEAP_STRING_THIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THIS)
  1232. #define DUK_HTHREAD_STRING_THIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THIS)
  1233. #define DUK_HEAP_STRING_THROW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THROW)
  1234. #define DUK_HTHREAD_STRING_THROW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THROW)
  1235. #define DUK_HEAP_STRING_TRY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRY)
  1236. #define DUK_HTHREAD_STRING_TRY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRY)
  1237. #define DUK_HEAP_STRING_TYPEOF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TYPEOF)
  1238. #define DUK_HTHREAD_STRING_TYPEOF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TYPEOF)
  1239. #define DUK_HEAP_STRING_VAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VAR)
  1240. #define DUK_HTHREAD_STRING_VAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VAR)
  1241. #define DUK_HEAP_STRING_VOID(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VOID)
  1242. #define DUK_HTHREAD_STRING_VOID(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VOID)
  1243. #define DUK_HEAP_STRING_WHILE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WHILE)
  1244. #define DUK_HTHREAD_STRING_WHILE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WHILE)
  1245. #define DUK_HEAP_STRING_WITH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WITH)
  1246. #define DUK_HTHREAD_STRING_WITH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WITH)
  1247. #define DUK_HEAP_STRING_CLASS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CLASS)
  1248. #define DUK_HTHREAD_STRING_CLASS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CLASS)
  1249. #define DUK_HEAP_STRING_CONST(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONST)
  1250. #define DUK_HTHREAD_STRING_CONST(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONST)
  1251. #define DUK_HEAP_STRING_ENUM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUM)
  1252. #define DUK_HTHREAD_STRING_ENUM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUM)
  1253. #define DUK_HEAP_STRING_EXPORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXPORT)
  1254. #define DUK_HTHREAD_STRING_EXPORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXPORT)
  1255. #define DUK_HEAP_STRING_EXTENDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXTENDS)
  1256. #define DUK_HTHREAD_STRING_EXTENDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXTENDS)
  1257. #define DUK_HEAP_STRING_IMPORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IMPORT)
  1258. #define DUK_HTHREAD_STRING_IMPORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IMPORT)
  1259. #define DUK_HEAP_STRING_SUPER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUPER)
  1260. #define DUK_HTHREAD_STRING_SUPER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUPER)
  1261. #define DUK_HEAP_STRING_LC_NULL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_NULL)
  1262. #define DUK_HTHREAD_STRING_LC_NULL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_NULL)
  1263. #define DUK_HEAP_STRING_TRUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRUE)
  1264. #define DUK_HTHREAD_STRING_TRUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRUE)
  1265. #define DUK_HEAP_STRING_FALSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FALSE)
  1266. #define DUK_HTHREAD_STRING_FALSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FALSE)
  1267. #define DUK_HEAP_STRING_IMPLEMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IMPLEMENTS)
  1268. #define DUK_HTHREAD_STRING_IMPLEMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IMPLEMENTS)
  1269. #define DUK_HEAP_STRING_INTERFACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INTERFACE)
  1270. #define DUK_HTHREAD_STRING_INTERFACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INTERFACE)
  1271. #define DUK_HEAP_STRING_LET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LET)
  1272. #define DUK_HTHREAD_STRING_LET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LET)
  1273. #define DUK_HEAP_STRING_PACKAGE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PACKAGE)
  1274. #define DUK_HTHREAD_STRING_PACKAGE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PACKAGE)
  1275. #define DUK_HEAP_STRING_PRIVATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PRIVATE)
  1276. #define DUK_HTHREAD_STRING_PRIVATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PRIVATE)
  1277. #define DUK_HEAP_STRING_PROTECTED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROTECTED)
  1278. #define DUK_HTHREAD_STRING_PROTECTED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROTECTED)
  1279. #define DUK_HEAP_STRING_PUBLIC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PUBLIC)
  1280. #define DUK_HTHREAD_STRING_PUBLIC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PUBLIC)
  1281. #define DUK_HEAP_STRING_STATIC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STATIC)
  1282. #define DUK_HTHREAD_STRING_STATIC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STATIC)
  1283. #define DUK_HEAP_STRING_YIELD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_YIELD)
  1284. #define DUK_HTHREAD_STRING_YIELD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_YIELD)
  1285. #define DUK_HEAP_NUM_STRINGS 336
  1286. #define DUK_STRIDX_START_RESERVED 291
  1287. #define DUK_STRIDX_START_STRICT_RESERVED 327
  1288. #define DUK_STRIDX_END_RESERVED 336 /* exclusive endpoint */
  1289. #if !defined(DUK_SINGLE_FILE)
  1290. DUK_INTERNAL_DECL const duk_c_function duk_bi_native_functions[128];
  1291. DUK_INTERNAL_DECL const duk_uint8_t duk_builtins_data[1341];
  1292. #ifdef DUK_USE_BUILTIN_INITJS
  1293. DUK_INTERNAL_DECL const duk_uint8_t duk_initjs_data[187];
  1294. #endif /* DUK_USE_BUILTIN_INITJS */
  1295. #endif /* !DUK_SINGLE_FILE */
  1296. #define DUK_BUILTINS_DATA_LENGTH 1341
  1297. #ifdef DUK_USE_BUILTIN_INITJS
  1298. #define DUK_BUILTIN_INITJS_DATA_LENGTH 187
  1299. #endif /* DUK_USE_BUILTIN_INITJS */
  1300. #define DUK_BIDX_GLOBAL 0
  1301. #define DUK_BIDX_GLOBAL_ENV 1
  1302. #define DUK_BIDX_OBJECT_CONSTRUCTOR 2
  1303. #define DUK_BIDX_OBJECT_PROTOTYPE 3
  1304. #define DUK_BIDX_FUNCTION_CONSTRUCTOR 4
  1305. #define DUK_BIDX_FUNCTION_PROTOTYPE 5
  1306. #define DUK_BIDX_ARRAY_CONSTRUCTOR 6
  1307. #define DUK_BIDX_ARRAY_PROTOTYPE 7
  1308. #define DUK_BIDX_STRING_CONSTRUCTOR 8
  1309. #define DUK_BIDX_STRING_PROTOTYPE 9
  1310. #define DUK_BIDX_BOOLEAN_CONSTRUCTOR 10
  1311. #define DUK_BIDX_BOOLEAN_PROTOTYPE 11
  1312. #define DUK_BIDX_NUMBER_CONSTRUCTOR 12
  1313. #define DUK_BIDX_NUMBER_PROTOTYPE 13
  1314. #define DUK_BIDX_DATE_CONSTRUCTOR 14
  1315. #define DUK_BIDX_DATE_PROTOTYPE 15
  1316. #define DUK_BIDX_REGEXP_CONSTRUCTOR 16
  1317. #define DUK_BIDX_REGEXP_PROTOTYPE 17
  1318. #define DUK_BIDX_ERROR_CONSTRUCTOR 18
  1319. #define DUK_BIDX_ERROR_PROTOTYPE 19
  1320. #define DUK_BIDX_EVAL_ERROR_CONSTRUCTOR 20
  1321. #define DUK_BIDX_EVAL_ERROR_PROTOTYPE 21
  1322. #define DUK_BIDX_RANGE_ERROR_CONSTRUCTOR 22
  1323. #define DUK_BIDX_RANGE_ERROR_PROTOTYPE 23
  1324. #define DUK_BIDX_REFERENCE_ERROR_CONSTRUCTOR 24
  1325. #define DUK_BIDX_REFERENCE_ERROR_PROTOTYPE 25
  1326. #define DUK_BIDX_SYNTAX_ERROR_CONSTRUCTOR 26
  1327. #define DUK_BIDX_SYNTAX_ERROR_PROTOTYPE 27
  1328. #define DUK_BIDX_TYPE_ERROR_CONSTRUCTOR 28
  1329. #define DUK_BIDX_TYPE_ERROR_PROTOTYPE 29
  1330. #define DUK_BIDX_URI_ERROR_CONSTRUCTOR 30
  1331. #define DUK_BIDX_URI_ERROR_PROTOTYPE 31
  1332. #define DUK_BIDX_MATH 32
  1333. #define DUK_BIDX_JSON 33
  1334. #define DUK_BIDX_TYPE_ERROR_THROWER 34
  1335. #define DUK_BIDX_PROXY_CONSTRUCTOR 35
  1336. #define DUK_BIDX_DUKTAPE 36
  1337. #define DUK_BIDX_THREAD_CONSTRUCTOR 37
  1338. #define DUK_BIDX_THREAD_PROTOTYPE 38
  1339. #define DUK_BIDX_BUFFER_CONSTRUCTOR 39
  1340. #define DUK_BIDX_BUFFER_PROTOTYPE 40
  1341. #define DUK_BIDX_POINTER_CONSTRUCTOR 41
  1342. #define DUK_BIDX_POINTER_PROTOTYPE 42
  1343. #define DUK_BIDX_LOGGER_CONSTRUCTOR 43
  1344. #define DUK_BIDX_LOGGER_PROTOTYPE 44
  1345. #define DUK_BIDX_DOUBLE_ERROR 45
  1346. #define DUK_NUM_BUILTINS 46
  1347. #elif defined(DUK_USE_DOUBLE_BE)
  1348. #if !defined(DUK_SINGLE_FILE)
  1349. DUK_INTERNAL_DECL const duk_uint8_t duk_strings_data[1943];
  1350. #endif /* !DUK_SINGLE_FILE */
  1351. #define DUK_STRDATA_DATA_LENGTH 1943
  1352. #define DUK_STRDATA_MAX_STRLEN 24
  1353. #define DUK_STRIDX_UC_LOGGER 0 /* 'Logger' */
  1354. #define DUK_STRIDX_UC_THREAD 1 /* 'Thread' */
  1355. #define DUK_STRIDX_UC_POINTER 2 /* 'Pointer' */
  1356. #define DUK_STRIDX_UC_BUFFER 3 /* 'Buffer' */
  1357. #define DUK_STRIDX_DEC_ENV 4 /* 'DecEnv' */
  1358. #define DUK_STRIDX_OBJ_ENV 5 /* 'ObjEnv' */
  1359. #define DUK_STRIDX_EMPTY_STRING 6 /* '' */
  1360. #define DUK_STRIDX_GLOBAL 7 /* 'global' */
  1361. #define DUK_STRIDX_UC_ARGUMENTS 8 /* 'Arguments' */
  1362. #define DUK_STRIDX_JSON 9 /* 'JSON' */
  1363. #define DUK_STRIDX_MATH 10 /* 'Math' */
  1364. #define DUK_STRIDX_UC_ERROR 11 /* 'Error' */
  1365. #define DUK_STRIDX_REG_EXP 12 /* 'RegExp' */
  1366. #define DUK_STRIDX_DATE 13 /* 'Date' */
  1367. #define DUK_STRIDX_UC_NUMBER 14 /* 'Number' */
  1368. #define DUK_STRIDX_UC_BOOLEAN 15 /* 'Boolean' */
  1369. #define DUK_STRIDX_UC_STRING 16 /* 'String' */
  1370. #define DUK_STRIDX_ARRAY 17 /* 'Array' */
  1371. #define DUK_STRIDX_UC_FUNCTION 18 /* 'Function' */
  1372. #define DUK_STRIDX_UC_OBJECT 19 /* 'Object' */
  1373. #define DUK_STRIDX_UC_NULL 20 /* 'Null' */
  1374. #define DUK_STRIDX_UC_UNDEFINED 21 /* 'Undefined' */
  1375. #define DUK_STRIDX_JSON_EXT_FUNCTION2 22 /* '{_func:true}' */
  1376. #define DUK_STRIDX_JSON_EXT_FUNCTION1 23 /* '{"_func":true}' */
  1377. #define DUK_STRIDX_JSON_EXT_NEGINF 24 /* '{"_ninf":true}' */
  1378. #define DUK_STRIDX_JSON_EXT_POSINF 25 /* '{"_inf":true}' */
  1379. #define DUK_STRIDX_JSON_EXT_NAN 26 /* '{"_nan":true}' */
  1380. #define DUK_STRIDX_JSON_EXT_UNDEFINED 27 /* '{"_undef":true}' */
  1381. #define DUK_STRIDX_TO_LOG_STRING 28 /* 'toLogString' */
  1382. #define DUK_STRIDX_CLOG 29 /* 'clog' */
  1383. #define DUK_STRIDX_LC_L 30 /* 'l' */
  1384. #define DUK_STRIDX_LC_N 31 /* 'n' */
  1385. #define DUK_STRIDX_LC_FATAL 32 /* 'fatal' */
  1386. #define DUK_STRIDX_LC_ERROR 33 /* 'error' */
  1387. #define DUK_STRIDX_LC_WARN 34 /* 'warn' */
  1388. #define DUK_STRIDX_LC_DEBUG 35 /* 'debug' */
  1389. #define DUK_STRIDX_LC_TRACE 36 /* 'trace' */
  1390. #define DUK_STRIDX_RAW 37 /* 'raw' */
  1391. #define DUK_STRIDX_FMT 38 /* 'fmt' */
  1392. #define DUK_STRIDX_CURRENT 39 /* 'current' */
  1393. #define DUK_STRIDX_RESUME 40 /* 'resume' */
  1394. #define DUK_STRIDX_COMPACT 41 /* 'compact' */
  1395. #define DUK_STRIDX_JC 42 /* 'jc' */
  1396. #define DUK_STRIDX_JX 43 /* 'jx' */
  1397. #define DUK_STRIDX_BASE64 44 /* 'base64' */
  1398. #define DUK_STRIDX_HEX 45 /* 'hex' */
  1399. #define DUK_STRIDX_DEC 46 /* 'dec' */
  1400. #define DUK_STRIDX_ENC 47 /* 'enc' */
  1401. #define DUK_STRIDX_FIN 48 /* 'fin' */
  1402. #define DUK_STRIDX_GC 49 /* 'gc' */
  1403. #define DUK_STRIDX_ACT 50 /* 'act' */
  1404. #define DUK_STRIDX_LC_INFO 51 /* 'info' */
  1405. #define DUK_STRIDX_VERSION 52 /* 'version' */
  1406. #define DUK_STRIDX_ENV 53 /* 'env' */
  1407. #define DUK_STRIDX_MOD_LOADED 54 /* 'modLoaded' */
  1408. #define DUK_STRIDX_MOD_SEARCH 55 /* 'modSearch' */
  1409. #define DUK_STRIDX_ERR_THROW 56 /* 'errThrow' */
  1410. #define DUK_STRIDX_ERR_CREATE 57 /* 'errCreate' */
  1411. #define DUK_STRIDX_COMPILE 58 /* 'compile' */
  1412. #define DUK_STRIDX_INT_REGBASE 59 /* '\x00Regbase' */
  1413. #define DUK_STRIDX_INT_THREAD 60 /* '\x00Thread' */
  1414. #define DUK_STRIDX_INT_HANDLER 61 /* '\x00Handler' */
  1415. #define DUK_STRIDX_INT_FINALIZER 62 /* '\x00Finalizer' */
  1416. #define DUK_STRIDX_INT_CALLEE 63 /* '\x00Callee' */
  1417. #define DUK_STRIDX_INT_MAP 64 /* '\x00Map' */
  1418. #define DUK_STRIDX_INT_ARGS 65 /* '\x00Args' */
  1419. #define DUK_STRIDX_INT_THIS 66 /* '\x00This' */
  1420. #define DUK_STRIDX_INT_PC2LINE 67 /* '\x00Pc2line' */
  1421. #define DUK_STRIDX_INT_SOURCE 68 /* '\x00Source' */
  1422. #define DUK_STRIDX_INT_VARENV 69 /* '\x00Varenv' */
  1423. #define DUK_STRIDX_INT_LEXENV 70 /* '\x00Lexenv' */
  1424. #define DUK_STRIDX_INT_VARMAP 71 /* '\x00Varmap' */
  1425. #define DUK_STRIDX_INT_FORMALS 72 /* '\x00Formals' */
  1426. #define DUK_STRIDX_INT_BYTECODE 73 /* '\x00Bytecode' */
  1427. #define DUK_STRIDX_INT_NEXT 74 /* '\x00Next' */
  1428. #define DUK_STRIDX_INT_TARGET 75 /* '\x00Target' */
  1429. #define DUK_STRIDX_INT_VALUE 76 /* '\x00Value' */
  1430. #define DUK_STRIDX_LC_POINTER 77 /* 'pointer' */
  1431. #define DUK_STRIDX_LC_BUFFER 78 /* 'buffer' */
  1432. #define DUK_STRIDX_INT_TRACEDATA 79 /* '\x00Tracedata' */
  1433. #define DUK_STRIDX_LINE_NUMBER 80 /* 'lineNumber' */
  1434. #define DUK_STRIDX_FILE_NAME 81 /* 'fileName' */
  1435. #define DUK_STRIDX_PC 82 /* 'pc' */
  1436. #define DUK_STRIDX_STACK 83 /* 'stack' */
  1437. #define DUK_STRIDX_THROW_TYPE_ERROR 84 /* 'ThrowTypeError' */
  1438. #define DUK_STRIDX_DUKTAPE 85 /* 'Duktape' */
  1439. #define DUK_STRIDX_ID 86 /* 'id' */
  1440. #define DUK_STRIDX_REQUIRE 87 /* 'require' */
  1441. #define DUK_STRIDX___PROTO__ 88 /* '__proto__' */
  1442. #define DUK_STRIDX_SET_PROTOTYPE_OF 89 /* 'setPrototypeOf' */
  1443. #define DUK_STRIDX_OWN_KEYS 90 /* 'ownKeys' */
  1444. #define DUK_STRIDX_ENUMERATE 91 /* 'enumerate' */
  1445. #define DUK_STRIDX_DELETE_PROPERTY 92 /* 'deleteProperty' */
  1446. #define DUK_STRIDX_HAS 93 /* 'has' */
  1447. #define DUK_STRIDX_PROXY 94 /* 'Proxy' */
  1448. #define DUK_STRIDX_CALLEE 95 /* 'callee' */
  1449. #define DUK_STRIDX_INVALID_DATE 96 /* 'Invalid Date' */
  1450. #define DUK_STRIDX_BRACKETED_ELLIPSIS 97 /* '[...]' */
  1451. #define DUK_STRIDX_NEWLINE_TAB 98 /* '\n\t' */
  1452. #define DUK_STRIDX_SPACE 99 /* ' ' */
  1453. #define DUK_STRIDX_COMMA 100 /* ',' */
  1454. #define DUK_STRIDX_MINUS_ZERO 101 /* '-0' */
  1455. #define DUK_STRIDX_PLUS_ZERO 102 /* '+0' */
  1456. #define DUK_STRIDX_ZERO 103 /* '0' */
  1457. #define DUK_STRIDX_MINUS_INFINITY 104 /* '-Infinity' */
  1458. #define DUK_STRIDX_PLUS_INFINITY 105 /* '+Infinity' */
  1459. #define DUK_STRIDX_INFINITY 106 /* 'Infinity' */
  1460. #define DUK_STRIDX_LC_OBJECT 107 /* 'object' */
  1461. #define DUK_STRIDX_LC_STRING 108 /* 'string' */
  1462. #define DUK_STRIDX_LC_NUMBER 109 /* 'number' */
  1463. #define DUK_STRIDX_LC_BOOLEAN 110 /* 'boolean' */
  1464. #define DUK_STRIDX_LC_UNDEFINED 111 /* 'undefined' */
  1465. #define DUK_STRIDX_STRINGIFY 112 /* 'stringify' */
  1466. #define DUK_STRIDX_TAN 113 /* 'tan' */
  1467. #define DUK_STRIDX_SQRT 114 /* 'sqrt' */
  1468. #define DUK_STRIDX_SIN 115 /* 'sin' */
  1469. #define DUK_STRIDX_ROUND 116 /* 'round' */
  1470. #define DUK_STRIDX_RANDOM 117 /* 'random' */
  1471. #define DUK_STRIDX_POW 118 /* 'pow' */
  1472. #define DUK_STRIDX_MIN 119 /* 'min' */
  1473. #define DUK_STRIDX_MAX 120 /* 'max' */
  1474. #define DUK_STRIDX_LOG 121 /* 'log' */
  1475. #define DUK_STRIDX_FLOOR 122 /* 'floor' */
  1476. #define DUK_STRIDX_EXP 123 /* 'exp' */
  1477. #define DUK_STRIDX_COS 124 /* 'cos' */
  1478. #define DUK_STRIDX_CEIL 125 /* 'ceil' */
  1479. #define DUK_STRIDX_ATAN2 126 /* 'atan2' */
  1480. #define DUK_STRIDX_ATAN 127 /* 'atan' */
  1481. #define DUK_STRIDX_ASIN 128 /* 'asin' */
  1482. #define DUK_STRIDX_ACOS 129 /* 'acos' */
  1483. #define DUK_STRIDX_ABS 130 /* 'abs' */
  1484. #define DUK_STRIDX_SQRT2 131 /* 'SQRT2' */
  1485. #define DUK_STRIDX_SQRT1_2 132 /* 'SQRT1_2' */
  1486. #define DUK_STRIDX_PI 133 /* 'PI' */
  1487. #define DUK_STRIDX_LOG10E 134 /* 'LOG10E' */
  1488. #define DUK_STRIDX_LOG2E 135 /* 'LOG2E' */
  1489. #define DUK_STRIDX_LN2 136 /* 'LN2' */
  1490. #define DUK_STRIDX_LN10 137 /* 'LN10' */
  1491. #define DUK_STRIDX_E 138 /* 'E' */
  1492. #define DUK_STRIDX_MESSAGE 139 /* 'message' */
  1493. #define DUK_STRIDX_NAME 140 /* 'name' */
  1494. #define DUK_STRIDX_INPUT 141 /* 'input' */
  1495. #define DUK_STRIDX_INDEX 142 /* 'index' */
  1496. #define DUK_STRIDX_ESCAPED_EMPTY_REGEXP 143 /* '(?:)' */
  1497. #define DUK_STRIDX_LAST_INDEX 144 /* 'lastIndex' */
  1498. #define DUK_STRIDX_MULTILINE 145 /* 'multiline' */
  1499. #define DUK_STRIDX_IGNORE_CASE 146 /* 'ignoreCase' */
  1500. #define DUK_STRIDX_SOURCE 147 /* 'source' */
  1501. #define DUK_STRIDX_TEST 148 /* 'test' */
  1502. #define DUK_STRIDX_EXEC 149 /* 'exec' */
  1503. #define DUK_STRIDX_TO_GMT_STRING 150 /* 'toGMTString' */
  1504. #define DUK_STRIDX_SET_YEAR 151 /* 'setYear' */
  1505. #define DUK_STRIDX_GET_YEAR 152 /* 'getYear' */
  1506. #define DUK_STRIDX_TO_JSON 153 /* 'toJSON' */
  1507. #define DUK_STRIDX_TO_ISO_STRING 154 /* 'toISOString' */
  1508. #define DUK_STRIDX_TO_UTC_STRING 155 /* 'toUTCString' */
  1509. #define DUK_STRIDX_SET_UTC_FULL_YEAR 156 /* 'setUTCFullYear' */
  1510. #define DUK_STRIDX_SET_FULL_YEAR 157 /* 'setFullYear' */
  1511. #define DUK_STRIDX_SET_UTC_MONTH 158 /* 'setUTCMonth' */
  1512. #define DUK_STRIDX_SET_MONTH 159 /* 'setMonth' */
  1513. #define DUK_STRIDX_SET_UTC_DATE 160 /* 'setUTCDate' */
  1514. #define DUK_STRIDX_SET_DATE 161 /* 'setDate' */
  1515. #define DUK_STRIDX_SET_UTC_HOURS 162 /* 'setUTCHours' */
  1516. #define DUK_STRIDX_SET_HOURS 163 /* 'setHours' */
  1517. #define DUK_STRIDX_SET_UTC_MINUTES 164 /* 'setUTCMinutes' */
  1518. #define DUK_STRIDX_SET_MINUTES 165 /* 'setMinutes' */
  1519. #define DUK_STRIDX_SET_UTC_SECONDS 166 /* 'setUTCSeconds' */
  1520. #define DUK_STRIDX_SET_SECONDS 167 /* 'setSeconds' */
  1521. #define DUK_STRIDX_SET_UTC_MILLISECONDS 168 /* 'setUTCMilliseconds' */
  1522. #define DUK_STRIDX_SET_MILLISECONDS 169 /* 'setMilliseconds' */
  1523. #define DUK_STRIDX_SET_TIME 170 /* 'setTime' */
  1524. #define DUK_STRIDX_GET_TIMEZONE_OFFSET 171 /* 'getTimezoneOffset' */
  1525. #define DUK_STRIDX_GET_UTC_MILLISECONDS 172 /* 'getUTCMilliseconds' */
  1526. #define DUK_STRIDX_GET_MILLISECONDS 173 /* 'getMilliseconds' */
  1527. #define DUK_STRIDX_GET_UTC_SECONDS 174 /* 'getUTCSeconds' */
  1528. #define DUK_STRIDX_GET_SECONDS 175 /* 'getSeconds' */
  1529. #define DUK_STRIDX_GET_UTC_MINUTES 176 /* 'getUTCMinutes' */
  1530. #define DUK_STRIDX_GET_MINUTES 177 /* 'getMinutes' */
  1531. #define DUK_STRIDX_GET_UTC_HOURS 178 /* 'getUTCHours' */
  1532. #define DUK_STRIDX_GET_HOURS 179 /* 'getHours' */
  1533. #define DUK_STRIDX_GET_UTC_DAY 180 /* 'getUTCDay' */
  1534. #define DUK_STRIDX_GET_DAY 181 /* 'getDay' */
  1535. #define DUK_STRIDX_GET_UTC_DATE 182 /* 'getUTCDate' */
  1536. #define DUK_STRIDX_GET_DATE 183 /* 'getDate' */
  1537. #define DUK_STRIDX_GET_UTC_MONTH 184 /* 'getUTCMonth' */
  1538. #define DUK_STRIDX_GET_MONTH 185 /* 'getMonth' */
  1539. #define DUK_STRIDX_GET_UTC_FULL_YEAR 186 /* 'getUTCFullYear' */
  1540. #define DUK_STRIDX_GET_FULL_YEAR 187 /* 'getFullYear' */
  1541. #define DUK_STRIDX_GET_TIME 188 /* 'getTime' */
  1542. #define DUK_STRIDX_TO_LOCALE_TIME_STRING 189 /* 'toLocaleTimeString' */
  1543. #define DUK_STRIDX_TO_LOCALE_DATE_STRING 190 /* 'toLocaleDateString' */
  1544. #define DUK_STRIDX_TO_TIME_STRING 191 /* 'toTimeString' */
  1545. #define DUK_STRIDX_TO_DATE_STRING 192 /* 'toDateString' */
  1546. #define DUK_STRIDX_NOW 193 /* 'now' */
  1547. #define DUK_STRIDX_UTC 194 /* 'UTC' */
  1548. #define DUK_STRIDX_PARSE 195 /* 'parse' */
  1549. #define DUK_STRIDX_TO_PRECISION 196 /* 'toPrecision' */
  1550. #define DUK_STRIDX_TO_EXPONENTIAL 197 /* 'toExponential' */
  1551. #define DUK_STRIDX_TO_FIXED 198 /* 'toFixed' */
  1552. #define DUK_STRIDX_POSITIVE_INFINITY 199 /* 'POSITIVE_INFINITY' */
  1553. #define DUK_STRIDX_NEGATIVE_INFINITY 200 /* 'NEGATIVE_INFINITY' */
  1554. #define DUK_STRIDX_NAN 201 /* 'NaN' */
  1555. #define DUK_STRIDX_MIN_VALUE 202 /* 'MIN_VALUE' */
  1556. #define DUK_STRIDX_MAX_VALUE 203 /* 'MAX_VALUE' */
  1557. #define DUK_STRIDX_SUBSTR 204 /* 'substr' */
  1558. #define DUK_STRIDX_TRIM 205 /* 'trim' */
  1559. #define DUK_STRIDX_TO_LOCALE_UPPER_CASE 206 /* 'toLocaleUpperCase' */
  1560. #define DUK_STRIDX_TO_UPPER_CASE 207 /* 'toUpperCase' */
  1561. #define DUK_STRIDX_TO_LOCALE_LOWER_CASE 208 /* 'toLocaleLowerCase' */
  1562. #define DUK_STRIDX_TO_LOWER_CASE 209 /* 'toLowerCase' */
  1563. #define DUK_STRIDX_SUBSTRING 210 /* 'substring' */
  1564. #define DUK_STRIDX_SPLIT 211 /* 'split' */
  1565. #define DUK_STRIDX_SEARCH 212 /* 'search' */
  1566. #define DUK_STRIDX_REPLACE 213 /* 'replace' */
  1567. #define DUK_STRIDX_MATCH 214 /* 'match' */
  1568. #define DUK_STRIDX_LOCALE_COMPARE 215 /* 'localeCompare' */
  1569. #define DUK_STRIDX_CHAR_CODE_AT 216 /* 'charCodeAt' */
  1570. #define DUK_STRIDX_CHAR_AT 217 /* 'charAt' */
  1571. #define DUK_STRIDX_FROM_CHAR_CODE 218 /* 'fromCharCode' */
  1572. #define DUK_STRIDX_REDUCE_RIGHT 219 /* 'reduceRight' */
  1573. #define DUK_STRIDX_REDUCE 220 /* 'reduce' */
  1574. #define DUK_STRIDX_FILTER 221 /* 'filter' */
  1575. #define DUK_STRIDX_MAP 222 /* 'map' */
  1576. #define DUK_STRIDX_FOR_EACH 223 /* 'forEach' */
  1577. #define DUK_STRIDX_SOME 224 /* 'some' */
  1578. #define DUK_STRIDX_EVERY 225 /* 'every' */
  1579. #define DUK_STRIDX_LAST_INDEX_OF 226 /* 'lastIndexOf' */
  1580. #define DUK_STRIDX_INDEX_OF 227 /* 'indexOf' */
  1581. #define DUK_STRIDX_UNSHIFT 228 /* 'unshift' */
  1582. #define DUK_STRIDX_SPLICE 229 /* 'splice' */
  1583. #define DUK_STRIDX_SORT 230 /* 'sort' */
  1584. #define DUK_STRIDX_SLICE 231 /* 'slice' */
  1585. #define DUK_STRIDX_SHIFT 232 /* 'shift' */
  1586. #define DUK_STRIDX_REVERSE 233 /* 'reverse' */
  1587. #define DUK_STRIDX_PUSH 234 /* 'push' */
  1588. #define DUK_STRIDX_POP 235 /* 'pop' */
  1589. #define DUK_STRIDX_JOIN 236 /* 'join' */
  1590. #define DUK_STRIDX_CONCAT 237 /* 'concat' */
  1591. #define DUK_STRIDX_IS_ARRAY 238 /* 'isArray' */
  1592. #define DUK_STRIDX_LC_ARGUMENTS 239 /* 'arguments' */
  1593. #define DUK_STRIDX_CALLER 240 /* 'caller' */
  1594. #define DUK_STRIDX_BIND 241 /* 'bind' */
  1595. #define DUK_STRIDX_CALL 242 /* 'call' */
  1596. #define DUK_STRIDX_APPLY 243 /* 'apply' */
  1597. #define DUK_STRIDX_PROPERTY_IS_ENUMERABLE 244 /* 'propertyIsEnumerable' */
  1598. #define DUK_STRIDX_IS_PROTOTYPE_OF 245 /* 'isPrototypeOf' */
  1599. #define DUK_STRIDX_HAS_OWN_PROPERTY 246 /* 'hasOwnProperty' */
  1600. #define DUK_STRIDX_VALUE_OF 247 /* 'valueOf' */
  1601. #define DUK_STRIDX_TO_LOCALE_STRING 248 /* 'toLocaleString' */
  1602. #define DUK_STRIDX_TO_STRING 249 /* 'toString' */
  1603. #define DUK_STRIDX_CONSTRUCTOR 250 /* 'constructor' */
  1604. #define DUK_STRIDX_SET 251 /* 'set' */
  1605. #define DUK_STRIDX_GET 252 /* 'get' */
  1606. #define DUK_STRIDX_ENUMERABLE 253 /* 'enumerable' */
  1607. #define DUK_STRIDX_CONFIGURABLE 254 /* 'configurable' */
  1608. #define DUK_STRIDX_WRITABLE 255 /* 'writable' */
  1609. #define DUK_STRIDX_VALUE 256 /* 'value' */
  1610. #define DUK_STRIDX_KEYS 257 /* 'keys' */
  1611. #define DUK_STRIDX_IS_EXTENSIBLE 258 /* 'isExtensible' */
  1612. #define DUK_STRIDX_IS_FROZEN 259 /* 'isFrozen' */
  1613. #define DUK_STRIDX_IS_SEALED 260 /* 'isSealed' */
  1614. #define DUK_STRIDX_PREVENT_EXTENSIONS 261 /* 'preventExtensions' */
  1615. #define DUK_STRIDX_FREEZE 262 /* 'freeze' */
  1616. #define DUK_STRIDX_SEAL 263 /* 'seal' */
  1617. #define DUK_STRIDX_DEFINE_PROPERTIES 264 /* 'defineProperties' */
  1618. #define DUK_STRIDX_DEFINE_PROPERTY 265 /* 'defineProperty' */
  1619. #define DUK_STRIDX_CREATE 266 /* 'create' */
  1620. #define DUK_STRIDX_GET_OWN_PROPERTY_NAMES 267 /* 'getOwnPropertyNames' */
  1621. #define DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR 268 /* 'getOwnPropertyDescriptor' */
  1622. #define DUK_STRIDX_GET_PROTOTYPE_OF 269 /* 'getPrototypeOf' */
  1623. #define DUK_STRIDX_PROTOTYPE 270 /* 'prototype' */
  1624. #define DUK_STRIDX_LENGTH 271 /* 'length' */
  1625. #define DUK_STRIDX_ALERT 272 /* 'alert' */
  1626. #define DUK_STRIDX_PRINT 273 /* 'print' */
  1627. #define DUK_STRIDX_UNESCAPE 274 /* 'unescape' */
  1628. #define DUK_STRIDX_ESCAPE 275 /* 'escape' */
  1629. #define DUK_STRIDX_ENCODE_URI_COMPONENT 276 /* 'encodeURIComponent' */
  1630. #define DUK_STRIDX_ENCODE_URI 277 /* 'encodeURI' */
  1631. #define DUK_STRIDX_DECODE_URI_COMPONENT 278 /* 'decodeURIComponent' */
  1632. #define DUK_STRIDX_DECODE_URI 279 /* 'decodeURI' */
  1633. #define DUK_STRIDX_IS_FINITE 280 /* 'isFinite' */
  1634. #define DUK_STRIDX_IS_NAN 281 /* 'isNaN' */
  1635. #define DUK_STRIDX_PARSE_FLOAT 282 /* 'parseFloat' */
  1636. #define DUK_STRIDX_PARSE_INT 283 /* 'parseInt' */
  1637. #define DUK_STRIDX_EVAL 284 /* 'eval' */
  1638. #define DUK_STRIDX_URI_ERROR 285 /* 'URIError' */
  1639. #define DUK_STRIDX_TYPE_ERROR 286 /* 'TypeError' */
  1640. #define DUK_STRIDX_SYNTAX_ERROR 287 /* 'SyntaxError' */
  1641. #define DUK_STRIDX_REFERENCE_ERROR 288 /* 'ReferenceError' */
  1642. #define DUK_STRIDX_RANGE_ERROR 289 /* 'RangeError' */
  1643. #define DUK_STRIDX_EVAL_ERROR 290 /* 'EvalError' */
  1644. #define DUK_STRIDX_BREAK 291 /* 'break' */
  1645. #define DUK_STRIDX_CASE 292 /* 'case' */
  1646. #define DUK_STRIDX_CATCH 293 /* 'catch' */
  1647. #define DUK_STRIDX_CONTINUE 294 /* 'continue' */
  1648. #define DUK_STRIDX_DEBUGGER 295 /* 'debugger' */
  1649. #define DUK_STRIDX_DEFAULT 296 /* 'default' */
  1650. #define DUK_STRIDX_DELETE 297 /* 'delete' */
  1651. #define DUK_STRIDX_DO 298 /* 'do' */
  1652. #define DUK_STRIDX_ELSE 299 /* 'else' */
  1653. #define DUK_STRIDX_FINALLY 300 /* 'finally' */
  1654. #define DUK_STRIDX_FOR 301 /* 'for' */
  1655. #define DUK_STRIDX_LC_FUNCTION 302 /* 'function' */
  1656. #define DUK_STRIDX_IF 303 /* 'if' */
  1657. #define DUK_STRIDX_IN 304 /* 'in' */
  1658. #define DUK_STRIDX_INSTANCEOF 305 /* 'instanceof' */
  1659. #define DUK_STRIDX_NEW 306 /* 'new' */
  1660. #define DUK_STRIDX_RETURN 307 /* 'return' */
  1661. #define DUK_STRIDX_SWITCH 308 /* 'switch' */
  1662. #define DUK_STRIDX_THIS 309 /* 'this' */
  1663. #define DUK_STRIDX_THROW 310 /* 'throw' */
  1664. #define DUK_STRIDX_TRY 311 /* 'try' */
  1665. #define DUK_STRIDX_TYPEOF 312 /* 'typeof' */
  1666. #define DUK_STRIDX_VAR 313 /* 'var' */
  1667. #define DUK_STRIDX_VOID 314 /* 'void' */
  1668. #define DUK_STRIDX_WHILE 315 /* 'while' */
  1669. #define DUK_STRIDX_WITH 316 /* 'with' */
  1670. #define DUK_STRIDX_CLASS 317 /* 'class' */
  1671. #define DUK_STRIDX_CONST 318 /* 'const' */
  1672. #define DUK_STRIDX_ENUM 319 /* 'enum' */
  1673. #define DUK_STRIDX_EXPORT 320 /* 'export' */
  1674. #define DUK_STRIDX_EXTENDS 321 /* 'extends' */
  1675. #define DUK_STRIDX_IMPORT 322 /* 'import' */
  1676. #define DUK_STRIDX_SUPER 323 /* 'super' */
  1677. #define DUK_STRIDX_LC_NULL 324 /* 'null' */
  1678. #define DUK_STRIDX_TRUE 325 /* 'true' */
  1679. #define DUK_STRIDX_FALSE 326 /* 'false' */
  1680. #define DUK_STRIDX_IMPLEMENTS 327 /* 'implements' */
  1681. #define DUK_STRIDX_INTERFACE 328 /* 'interface' */
  1682. #define DUK_STRIDX_LET 329 /* 'let' */
  1683. #define DUK_STRIDX_PACKAGE 330 /* 'package' */
  1684. #define DUK_STRIDX_PRIVATE 331 /* 'private' */
  1685. #define DUK_STRIDX_PROTECTED 332 /* 'protected' */
  1686. #define DUK_STRIDX_PUBLIC 333 /* 'public' */
  1687. #define DUK_STRIDX_STATIC 334 /* 'static' */
  1688. #define DUK_STRIDX_YIELD 335 /* 'yield' */
  1689. #define DUK_HEAP_STRING_UC_LOGGER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_LOGGER)
  1690. #define DUK_HTHREAD_STRING_UC_LOGGER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_LOGGER)
  1691. #define DUK_HEAP_STRING_UC_THREAD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_THREAD)
  1692. #define DUK_HTHREAD_STRING_UC_THREAD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_THREAD)
  1693. #define DUK_HEAP_STRING_UC_POINTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_POINTER)
  1694. #define DUK_HTHREAD_STRING_UC_POINTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_POINTER)
  1695. #define DUK_HEAP_STRING_UC_BUFFER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_BUFFER)
  1696. #define DUK_HTHREAD_STRING_UC_BUFFER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_BUFFER)
  1697. #define DUK_HEAP_STRING_DEC_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEC_ENV)
  1698. #define DUK_HTHREAD_STRING_DEC_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEC_ENV)
  1699. #define DUK_HEAP_STRING_OBJ_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_OBJ_ENV)
  1700. #define DUK_HTHREAD_STRING_OBJ_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_OBJ_ENV)
  1701. #define DUK_HEAP_STRING_EMPTY_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EMPTY_STRING)
  1702. #define DUK_HTHREAD_STRING_EMPTY_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EMPTY_STRING)
  1703. #define DUK_HEAP_STRING_GLOBAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GLOBAL)
  1704. #define DUK_HTHREAD_STRING_GLOBAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GLOBAL)
  1705. #define DUK_HEAP_STRING_UC_ARGUMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_ARGUMENTS)
  1706. #define DUK_HTHREAD_STRING_UC_ARGUMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_ARGUMENTS)
  1707. #define DUK_HEAP_STRING_JSON(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON)
  1708. #define DUK_HTHREAD_STRING_JSON(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON)
  1709. #define DUK_HEAP_STRING_MATH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MATH)
  1710. #define DUK_HTHREAD_STRING_MATH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MATH)
  1711. #define DUK_HEAP_STRING_UC_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_ERROR)
  1712. #define DUK_HTHREAD_STRING_UC_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_ERROR)
  1713. #define DUK_HEAP_STRING_REG_EXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REG_EXP)
  1714. #define DUK_HTHREAD_STRING_REG_EXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REG_EXP)
  1715. #define DUK_HEAP_STRING_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DATE)
  1716. #define DUK_HTHREAD_STRING_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DATE)
  1717. #define DUK_HEAP_STRING_UC_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_NUMBER)
  1718. #define DUK_HTHREAD_STRING_UC_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_NUMBER)
  1719. #define DUK_HEAP_STRING_UC_BOOLEAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_BOOLEAN)
  1720. #define DUK_HTHREAD_STRING_UC_BOOLEAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_BOOLEAN)
  1721. #define DUK_HEAP_STRING_UC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_STRING)
  1722. #define DUK_HTHREAD_STRING_UC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_STRING)
  1723. #define DUK_HEAP_STRING_ARRAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ARRAY)
  1724. #define DUK_HTHREAD_STRING_ARRAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ARRAY)
  1725. #define DUK_HEAP_STRING_UC_FUNCTION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_FUNCTION)
  1726. #define DUK_HTHREAD_STRING_UC_FUNCTION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_FUNCTION)
  1727. #define DUK_HEAP_STRING_UC_OBJECT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_OBJECT)
  1728. #define DUK_HTHREAD_STRING_UC_OBJECT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_OBJECT)
  1729. #define DUK_HEAP_STRING_UC_NULL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_NULL)
  1730. #define DUK_HTHREAD_STRING_UC_NULL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_NULL)
  1731. #define DUK_HEAP_STRING_UC_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_UNDEFINED)
  1732. #define DUK_HTHREAD_STRING_UC_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_UNDEFINED)
  1733. #define DUK_HEAP_STRING_JSON_EXT_FUNCTION2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_FUNCTION2)
  1734. #define DUK_HTHREAD_STRING_JSON_EXT_FUNCTION2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_FUNCTION2)
  1735. #define DUK_HEAP_STRING_JSON_EXT_FUNCTION1(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_FUNCTION1)
  1736. #define DUK_HTHREAD_STRING_JSON_EXT_FUNCTION1(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_FUNCTION1)
  1737. #define DUK_HEAP_STRING_JSON_EXT_NEGINF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_NEGINF)
  1738. #define DUK_HTHREAD_STRING_JSON_EXT_NEGINF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_NEGINF)
  1739. #define DUK_HEAP_STRING_JSON_EXT_POSINF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_POSINF)
  1740. #define DUK_HTHREAD_STRING_JSON_EXT_POSINF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_POSINF)
  1741. #define DUK_HEAP_STRING_JSON_EXT_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_NAN)
  1742. #define DUK_HTHREAD_STRING_JSON_EXT_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_NAN)
  1743. #define DUK_HEAP_STRING_JSON_EXT_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_UNDEFINED)
  1744. #define DUK_HTHREAD_STRING_JSON_EXT_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_UNDEFINED)
  1745. #define DUK_HEAP_STRING_TO_LOG_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOG_STRING)
  1746. #define DUK_HTHREAD_STRING_TO_LOG_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOG_STRING)
  1747. #define DUK_HEAP_STRING_CLOG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CLOG)
  1748. #define DUK_HTHREAD_STRING_CLOG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CLOG)
  1749. #define DUK_HEAP_STRING_LC_L(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_L)
  1750. #define DUK_HTHREAD_STRING_LC_L(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_L)
  1751. #define DUK_HEAP_STRING_LC_N(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_N)
  1752. #define DUK_HTHREAD_STRING_LC_N(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_N)
  1753. #define DUK_HEAP_STRING_LC_FATAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_FATAL)
  1754. #define DUK_HTHREAD_STRING_LC_FATAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_FATAL)
  1755. #define DUK_HEAP_STRING_LC_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_ERROR)
  1756. #define DUK_HTHREAD_STRING_LC_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_ERROR)
  1757. #define DUK_HEAP_STRING_LC_WARN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_WARN)
  1758. #define DUK_HTHREAD_STRING_LC_WARN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_WARN)
  1759. #define DUK_HEAP_STRING_LC_DEBUG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_DEBUG)
  1760. #define DUK_HTHREAD_STRING_LC_DEBUG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_DEBUG)
  1761. #define DUK_HEAP_STRING_LC_TRACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_TRACE)
  1762. #define DUK_HTHREAD_STRING_LC_TRACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_TRACE)
  1763. #define DUK_HEAP_STRING_RAW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RAW)
  1764. #define DUK_HTHREAD_STRING_RAW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RAW)
  1765. #define DUK_HEAP_STRING_FMT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FMT)
  1766. #define DUK_HTHREAD_STRING_FMT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FMT)
  1767. #define DUK_HEAP_STRING_CURRENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CURRENT)
  1768. #define DUK_HTHREAD_STRING_CURRENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CURRENT)
  1769. #define DUK_HEAP_STRING_RESUME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RESUME)
  1770. #define DUK_HTHREAD_STRING_RESUME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RESUME)
  1771. #define DUK_HEAP_STRING_COMPACT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMPACT)
  1772. #define DUK_HTHREAD_STRING_COMPACT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMPACT)
  1773. #define DUK_HEAP_STRING_JC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JC)
  1774. #define DUK_HTHREAD_STRING_JC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JC)
  1775. #define DUK_HEAP_STRING_JX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JX)
  1776. #define DUK_HTHREAD_STRING_JX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JX)
  1777. #define DUK_HEAP_STRING_BASE64(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BASE64)
  1778. #define DUK_HTHREAD_STRING_BASE64(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BASE64)
  1779. #define DUK_HEAP_STRING_HEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HEX)
  1780. #define DUK_HTHREAD_STRING_HEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HEX)
  1781. #define DUK_HEAP_STRING_DEC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEC)
  1782. #define DUK_HTHREAD_STRING_DEC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEC)
  1783. #define DUK_HEAP_STRING_ENC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENC)
  1784. #define DUK_HTHREAD_STRING_ENC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENC)
  1785. #define DUK_HEAP_STRING_FIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FIN)
  1786. #define DUK_HTHREAD_STRING_FIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FIN)
  1787. #define DUK_HEAP_STRING_GC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GC)
  1788. #define DUK_HTHREAD_STRING_GC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GC)
  1789. #define DUK_HEAP_STRING_ACT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ACT)
  1790. #define DUK_HTHREAD_STRING_ACT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ACT)
  1791. #define DUK_HEAP_STRING_LC_INFO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_INFO)
  1792. #define DUK_HTHREAD_STRING_LC_INFO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_INFO)
  1793. #define DUK_HEAP_STRING_VERSION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VERSION)
  1794. #define DUK_HTHREAD_STRING_VERSION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VERSION)
  1795. #define DUK_HEAP_STRING_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENV)
  1796. #define DUK_HTHREAD_STRING_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENV)
  1797. #define DUK_HEAP_STRING_MOD_LOADED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MOD_LOADED)
  1798. #define DUK_HTHREAD_STRING_MOD_LOADED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MOD_LOADED)
  1799. #define DUK_HEAP_STRING_MOD_SEARCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MOD_SEARCH)
  1800. #define DUK_HTHREAD_STRING_MOD_SEARCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MOD_SEARCH)
  1801. #define DUK_HEAP_STRING_ERR_THROW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ERR_THROW)
  1802. #define DUK_HTHREAD_STRING_ERR_THROW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ERR_THROW)
  1803. #define DUK_HEAP_STRING_ERR_CREATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ERR_CREATE)
  1804. #define DUK_HTHREAD_STRING_ERR_CREATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ERR_CREATE)
  1805. #define DUK_HEAP_STRING_COMPILE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMPILE)
  1806. #define DUK_HTHREAD_STRING_COMPILE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMPILE)
  1807. #define DUK_HEAP_STRING_INT_REGBASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_REGBASE)
  1808. #define DUK_HTHREAD_STRING_INT_REGBASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_REGBASE)
  1809. #define DUK_HEAP_STRING_INT_THREAD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_THREAD)
  1810. #define DUK_HTHREAD_STRING_INT_THREAD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_THREAD)
  1811. #define DUK_HEAP_STRING_INT_HANDLER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_HANDLER)
  1812. #define DUK_HTHREAD_STRING_INT_HANDLER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_HANDLER)
  1813. #define DUK_HEAP_STRING_INT_FINALIZER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_FINALIZER)
  1814. #define DUK_HTHREAD_STRING_INT_FINALIZER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_FINALIZER)
  1815. #define DUK_HEAP_STRING_INT_CALLEE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_CALLEE)
  1816. #define DUK_HTHREAD_STRING_INT_CALLEE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_CALLEE)
  1817. #define DUK_HEAP_STRING_INT_MAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_MAP)
  1818. #define DUK_HTHREAD_STRING_INT_MAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_MAP)
  1819. #define DUK_HEAP_STRING_INT_ARGS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_ARGS)
  1820. #define DUK_HTHREAD_STRING_INT_ARGS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_ARGS)
  1821. #define DUK_HEAP_STRING_INT_THIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_THIS)
  1822. #define DUK_HTHREAD_STRING_INT_THIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_THIS)
  1823. #define DUK_HEAP_STRING_INT_PC2LINE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_PC2LINE)
  1824. #define DUK_HTHREAD_STRING_INT_PC2LINE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_PC2LINE)
  1825. #define DUK_HEAP_STRING_INT_SOURCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_SOURCE)
  1826. #define DUK_HTHREAD_STRING_INT_SOURCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_SOURCE)
  1827. #define DUK_HEAP_STRING_INT_VARENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VARENV)
  1828. #define DUK_HTHREAD_STRING_INT_VARENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VARENV)
  1829. #define DUK_HEAP_STRING_INT_LEXENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_LEXENV)
  1830. #define DUK_HTHREAD_STRING_INT_LEXENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_LEXENV)
  1831. #define DUK_HEAP_STRING_INT_VARMAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VARMAP)
  1832. #define DUK_HTHREAD_STRING_INT_VARMAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VARMAP)
  1833. #define DUK_HEAP_STRING_INT_FORMALS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_FORMALS)
  1834. #define DUK_HTHREAD_STRING_INT_FORMALS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_FORMALS)
  1835. #define DUK_HEAP_STRING_INT_BYTECODE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_BYTECODE)
  1836. #define DUK_HTHREAD_STRING_INT_BYTECODE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_BYTECODE)
  1837. #define DUK_HEAP_STRING_INT_NEXT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_NEXT)
  1838. #define DUK_HTHREAD_STRING_INT_NEXT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_NEXT)
  1839. #define DUK_HEAP_STRING_INT_TARGET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_TARGET)
  1840. #define DUK_HTHREAD_STRING_INT_TARGET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_TARGET)
  1841. #define DUK_HEAP_STRING_INT_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VALUE)
  1842. #define DUK_HTHREAD_STRING_INT_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VALUE)
  1843. #define DUK_HEAP_STRING_LC_POINTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_POINTER)
  1844. #define DUK_HTHREAD_STRING_LC_POINTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_POINTER)
  1845. #define DUK_HEAP_STRING_LC_BUFFER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_BUFFER)
  1846. #define DUK_HTHREAD_STRING_LC_BUFFER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_BUFFER)
  1847. #define DUK_HEAP_STRING_INT_TRACEDATA(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_TRACEDATA)
  1848. #define DUK_HTHREAD_STRING_INT_TRACEDATA(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_TRACEDATA)
  1849. #define DUK_HEAP_STRING_LINE_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LINE_NUMBER)
  1850. #define DUK_HTHREAD_STRING_LINE_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LINE_NUMBER)
  1851. #define DUK_HEAP_STRING_FILE_NAME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FILE_NAME)
  1852. #define DUK_HTHREAD_STRING_FILE_NAME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FILE_NAME)
  1853. #define DUK_HEAP_STRING_PC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PC)
  1854. #define DUK_HTHREAD_STRING_PC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PC)
  1855. #define DUK_HEAP_STRING_STACK(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STACK)
  1856. #define DUK_HTHREAD_STRING_STACK(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STACK)
  1857. #define DUK_HEAP_STRING_THROW_TYPE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THROW_TYPE_ERROR)
  1858. #define DUK_HTHREAD_STRING_THROW_TYPE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THROW_TYPE_ERROR)
  1859. #define DUK_HEAP_STRING_DUKTAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DUKTAPE)
  1860. #define DUK_HTHREAD_STRING_DUKTAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DUKTAPE)
  1861. #define DUK_HEAP_STRING_ID(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ID)
  1862. #define DUK_HTHREAD_STRING_ID(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ID)
  1863. #define DUK_HEAP_STRING_REQUIRE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REQUIRE)
  1864. #define DUK_HTHREAD_STRING_REQUIRE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REQUIRE)
  1865. #define DUK_HEAP_STRING___PROTO__(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX___PROTO__)
  1866. #define DUK_HTHREAD_STRING___PROTO__(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX___PROTO__)
  1867. #define DUK_HEAP_STRING_SET_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_PROTOTYPE_OF)
  1868. #define DUK_HTHREAD_STRING_SET_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_PROTOTYPE_OF)
  1869. #define DUK_HEAP_STRING_OWN_KEYS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_OWN_KEYS)
  1870. #define DUK_HTHREAD_STRING_OWN_KEYS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_OWN_KEYS)
  1871. #define DUK_HEAP_STRING_ENUMERATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUMERATE)
  1872. #define DUK_HTHREAD_STRING_ENUMERATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUMERATE)
  1873. #define DUK_HEAP_STRING_DELETE_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DELETE_PROPERTY)
  1874. #define DUK_HTHREAD_STRING_DELETE_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DELETE_PROPERTY)
  1875. #define DUK_HEAP_STRING_HAS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HAS)
  1876. #define DUK_HTHREAD_STRING_HAS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HAS)
  1877. #define DUK_HEAP_STRING_PROXY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROXY)
  1878. #define DUK_HTHREAD_STRING_PROXY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROXY)
  1879. #define DUK_HEAP_STRING_CALLEE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALLEE)
  1880. #define DUK_HTHREAD_STRING_CALLEE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALLEE)
  1881. #define DUK_HEAP_STRING_INVALID_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INVALID_DATE)
  1882. #define DUK_HTHREAD_STRING_INVALID_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INVALID_DATE)
  1883. #define DUK_HEAP_STRING_BRACKETED_ELLIPSIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BRACKETED_ELLIPSIS)
  1884. #define DUK_HTHREAD_STRING_BRACKETED_ELLIPSIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BRACKETED_ELLIPSIS)
  1885. #define DUK_HEAP_STRING_NEWLINE_TAB(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEWLINE_TAB)
  1886. #define DUK_HTHREAD_STRING_NEWLINE_TAB(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEWLINE_TAB)
  1887. #define DUK_HEAP_STRING_SPACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPACE)
  1888. #define DUK_HTHREAD_STRING_SPACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPACE)
  1889. #define DUK_HEAP_STRING_COMMA(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMMA)
  1890. #define DUK_HTHREAD_STRING_COMMA(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMMA)
  1891. #define DUK_HEAP_STRING_MINUS_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MINUS_ZERO)
  1892. #define DUK_HTHREAD_STRING_MINUS_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MINUS_ZERO)
  1893. #define DUK_HEAP_STRING_PLUS_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PLUS_ZERO)
  1894. #define DUK_HTHREAD_STRING_PLUS_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PLUS_ZERO)
  1895. #define DUK_HEAP_STRING_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ZERO)
  1896. #define DUK_HTHREAD_STRING_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ZERO)
  1897. #define DUK_HEAP_STRING_MINUS_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MINUS_INFINITY)
  1898. #define DUK_HTHREAD_STRING_MINUS_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MINUS_INFINITY)
  1899. #define DUK_HEAP_STRING_PLUS_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PLUS_INFINITY)
  1900. #define DUK_HTHREAD_STRING_PLUS_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PLUS_INFINITY)
  1901. #define DUK_HEAP_STRING_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INFINITY)
  1902. #define DUK_HTHREAD_STRING_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INFINITY)
  1903. #define DUK_HEAP_STRING_LC_OBJECT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_OBJECT)
  1904. #define DUK_HTHREAD_STRING_LC_OBJECT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_OBJECT)
  1905. #define DUK_HEAP_STRING_LC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_STRING)
  1906. #define DUK_HTHREAD_STRING_LC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_STRING)
  1907. #define DUK_HEAP_STRING_LC_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_NUMBER)
  1908. #define DUK_HTHREAD_STRING_LC_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_NUMBER)
  1909. #define DUK_HEAP_STRING_LC_BOOLEAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_BOOLEAN)
  1910. #define DUK_HTHREAD_STRING_LC_BOOLEAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_BOOLEAN)
  1911. #define DUK_HEAP_STRING_LC_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_UNDEFINED)
  1912. #define DUK_HTHREAD_STRING_LC_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_UNDEFINED)
  1913. #define DUK_HEAP_STRING_STRINGIFY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STRINGIFY)
  1914. #define DUK_HTHREAD_STRING_STRINGIFY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STRINGIFY)
  1915. #define DUK_HEAP_STRING_TAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TAN)
  1916. #define DUK_HTHREAD_STRING_TAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TAN)
  1917. #define DUK_HEAP_STRING_SQRT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT)
  1918. #define DUK_HTHREAD_STRING_SQRT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT)
  1919. #define DUK_HEAP_STRING_SIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SIN)
  1920. #define DUK_HTHREAD_STRING_SIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SIN)
  1921. #define DUK_HEAP_STRING_ROUND(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ROUND)
  1922. #define DUK_HTHREAD_STRING_ROUND(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ROUND)
  1923. #define DUK_HEAP_STRING_RANDOM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RANDOM)
  1924. #define DUK_HTHREAD_STRING_RANDOM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RANDOM)
  1925. #define DUK_HEAP_STRING_POW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POW)
  1926. #define DUK_HTHREAD_STRING_POW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POW)
  1927. #define DUK_HEAP_STRING_MIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MIN)
  1928. #define DUK_HTHREAD_STRING_MIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MIN)
  1929. #define DUK_HEAP_STRING_MAX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAX)
  1930. #define DUK_HTHREAD_STRING_MAX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAX)
  1931. #define DUK_HEAP_STRING_LOG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG)
  1932. #define DUK_HTHREAD_STRING_LOG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG)
  1933. #define DUK_HEAP_STRING_FLOOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FLOOR)
  1934. #define DUK_HTHREAD_STRING_FLOOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FLOOR)
  1935. #define DUK_HEAP_STRING_EXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXP)
  1936. #define DUK_HTHREAD_STRING_EXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXP)
  1937. #define DUK_HEAP_STRING_COS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COS)
  1938. #define DUK_HTHREAD_STRING_COS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COS)
  1939. #define DUK_HEAP_STRING_CEIL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CEIL)
  1940. #define DUK_HTHREAD_STRING_CEIL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CEIL)
  1941. #define DUK_HEAP_STRING_ATAN2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ATAN2)
  1942. #define DUK_HTHREAD_STRING_ATAN2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ATAN2)
  1943. #define DUK_HEAP_STRING_ATAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ATAN)
  1944. #define DUK_HTHREAD_STRING_ATAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ATAN)
  1945. #define DUK_HEAP_STRING_ASIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ASIN)
  1946. #define DUK_HTHREAD_STRING_ASIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ASIN)
  1947. #define DUK_HEAP_STRING_ACOS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ACOS)
  1948. #define DUK_HTHREAD_STRING_ACOS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ACOS)
  1949. #define DUK_HEAP_STRING_ABS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ABS)
  1950. #define DUK_HTHREAD_STRING_ABS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ABS)
  1951. #define DUK_HEAP_STRING_SQRT2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT2)
  1952. #define DUK_HTHREAD_STRING_SQRT2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT2)
  1953. #define DUK_HEAP_STRING_SQRT1_2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT1_2)
  1954. #define DUK_HTHREAD_STRING_SQRT1_2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT1_2)
  1955. #define DUK_HEAP_STRING_PI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PI)
  1956. #define DUK_HTHREAD_STRING_PI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PI)
  1957. #define DUK_HEAP_STRING_LOG10E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG10E)
  1958. #define DUK_HTHREAD_STRING_LOG10E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG10E)
  1959. #define DUK_HEAP_STRING_LOG2E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG2E)
  1960. #define DUK_HTHREAD_STRING_LOG2E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG2E)
  1961. #define DUK_HEAP_STRING_LN2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LN2)
  1962. #define DUK_HTHREAD_STRING_LN2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LN2)
  1963. #define DUK_HEAP_STRING_LN10(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LN10)
  1964. #define DUK_HTHREAD_STRING_LN10(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LN10)
  1965. #define DUK_HEAP_STRING_E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_E)
  1966. #define DUK_HTHREAD_STRING_E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_E)
  1967. #define DUK_HEAP_STRING_MESSAGE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MESSAGE)
  1968. #define DUK_HTHREAD_STRING_MESSAGE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MESSAGE)
  1969. #define DUK_HEAP_STRING_NAME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NAME)
  1970. #define DUK_HTHREAD_STRING_NAME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NAME)
  1971. #define DUK_HEAP_STRING_INPUT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INPUT)
  1972. #define DUK_HTHREAD_STRING_INPUT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INPUT)
  1973. #define DUK_HEAP_STRING_INDEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INDEX)
  1974. #define DUK_HTHREAD_STRING_INDEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INDEX)
  1975. #define DUK_HEAP_STRING_ESCAPED_EMPTY_REGEXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ESCAPED_EMPTY_REGEXP)
  1976. #define DUK_HTHREAD_STRING_ESCAPED_EMPTY_REGEXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ESCAPED_EMPTY_REGEXP)
  1977. #define DUK_HEAP_STRING_LAST_INDEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LAST_INDEX)
  1978. #define DUK_HTHREAD_STRING_LAST_INDEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LAST_INDEX)
  1979. #define DUK_HEAP_STRING_MULTILINE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MULTILINE)
  1980. #define DUK_HTHREAD_STRING_MULTILINE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MULTILINE)
  1981. #define DUK_HEAP_STRING_IGNORE_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IGNORE_CASE)
  1982. #define DUK_HTHREAD_STRING_IGNORE_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IGNORE_CASE)
  1983. #define DUK_HEAP_STRING_SOURCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SOURCE)
  1984. #define DUK_HTHREAD_STRING_SOURCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SOURCE)
  1985. #define DUK_HEAP_STRING_TEST(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TEST)
  1986. #define DUK_HTHREAD_STRING_TEST(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TEST)
  1987. #define DUK_HEAP_STRING_EXEC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXEC)
  1988. #define DUK_HTHREAD_STRING_EXEC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXEC)
  1989. #define DUK_HEAP_STRING_TO_GMT_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_GMT_STRING)
  1990. #define DUK_HTHREAD_STRING_TO_GMT_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_GMT_STRING)
  1991. #define DUK_HEAP_STRING_SET_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_YEAR)
  1992. #define DUK_HTHREAD_STRING_SET_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_YEAR)
  1993. #define DUK_HEAP_STRING_GET_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_YEAR)
  1994. #define DUK_HTHREAD_STRING_GET_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_YEAR)
  1995. #define DUK_HEAP_STRING_TO_JSON(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_JSON)
  1996. #define DUK_HTHREAD_STRING_TO_JSON(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_JSON)
  1997. #define DUK_HEAP_STRING_TO_ISO_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_ISO_STRING)
  1998. #define DUK_HTHREAD_STRING_TO_ISO_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_ISO_STRING)
  1999. #define DUK_HEAP_STRING_TO_UTC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_UTC_STRING)
  2000. #define DUK_HTHREAD_STRING_TO_UTC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_UTC_STRING)
  2001. #define DUK_HEAP_STRING_SET_UTC_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_FULL_YEAR)
  2002. #define DUK_HTHREAD_STRING_SET_UTC_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_FULL_YEAR)
  2003. #define DUK_HEAP_STRING_SET_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_FULL_YEAR)
  2004. #define DUK_HTHREAD_STRING_SET_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_FULL_YEAR)
  2005. #define DUK_HEAP_STRING_SET_UTC_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MONTH)
  2006. #define DUK_HTHREAD_STRING_SET_UTC_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MONTH)
  2007. #define DUK_HEAP_STRING_SET_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MONTH)
  2008. #define DUK_HTHREAD_STRING_SET_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MONTH)
  2009. #define DUK_HEAP_STRING_SET_UTC_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_DATE)
  2010. #define DUK_HTHREAD_STRING_SET_UTC_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_DATE)
  2011. #define DUK_HEAP_STRING_SET_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_DATE)
  2012. #define DUK_HTHREAD_STRING_SET_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_DATE)
  2013. #define DUK_HEAP_STRING_SET_UTC_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_HOURS)
  2014. #define DUK_HTHREAD_STRING_SET_UTC_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_HOURS)
  2015. #define DUK_HEAP_STRING_SET_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_HOURS)
  2016. #define DUK_HTHREAD_STRING_SET_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_HOURS)
  2017. #define DUK_HEAP_STRING_SET_UTC_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MINUTES)
  2018. #define DUK_HTHREAD_STRING_SET_UTC_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MINUTES)
  2019. #define DUK_HEAP_STRING_SET_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MINUTES)
  2020. #define DUK_HTHREAD_STRING_SET_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MINUTES)
  2021. #define DUK_HEAP_STRING_SET_UTC_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_SECONDS)
  2022. #define DUK_HTHREAD_STRING_SET_UTC_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_SECONDS)
  2023. #define DUK_HEAP_STRING_SET_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_SECONDS)
  2024. #define DUK_HTHREAD_STRING_SET_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_SECONDS)
  2025. #define DUK_HEAP_STRING_SET_UTC_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MILLISECONDS)
  2026. #define DUK_HTHREAD_STRING_SET_UTC_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MILLISECONDS)
  2027. #define DUK_HEAP_STRING_SET_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MILLISECONDS)
  2028. #define DUK_HTHREAD_STRING_SET_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MILLISECONDS)
  2029. #define DUK_HEAP_STRING_SET_TIME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_TIME)
  2030. #define DUK_HTHREAD_STRING_SET_TIME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_TIME)
  2031. #define DUK_HEAP_STRING_GET_TIMEZONE_OFFSET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_TIMEZONE_OFFSET)
  2032. #define DUK_HTHREAD_STRING_GET_TIMEZONE_OFFSET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_TIMEZONE_OFFSET)
  2033. #define DUK_HEAP_STRING_GET_UTC_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MILLISECONDS)
  2034. #define DUK_HTHREAD_STRING_GET_UTC_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MILLISECONDS)
  2035. #define DUK_HEAP_STRING_GET_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MILLISECONDS)
  2036. #define DUK_HTHREAD_STRING_GET_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MILLISECONDS)
  2037. #define DUK_HEAP_STRING_GET_UTC_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_SECONDS)
  2038. #define DUK_HTHREAD_STRING_GET_UTC_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_SECONDS)
  2039. #define DUK_HEAP_STRING_GET_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_SECONDS)
  2040. #define DUK_HTHREAD_STRING_GET_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_SECONDS)
  2041. #define DUK_HEAP_STRING_GET_UTC_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MINUTES)
  2042. #define DUK_HTHREAD_STRING_GET_UTC_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MINUTES)
  2043. #define DUK_HEAP_STRING_GET_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MINUTES)
  2044. #define DUK_HTHREAD_STRING_GET_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MINUTES)
  2045. #define DUK_HEAP_STRING_GET_UTC_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_HOURS)
  2046. #define DUK_HTHREAD_STRING_GET_UTC_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_HOURS)
  2047. #define DUK_HEAP_STRING_GET_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_HOURS)
  2048. #define DUK_HTHREAD_STRING_GET_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_HOURS)
  2049. #define DUK_HEAP_STRING_GET_UTC_DAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_DAY)
  2050. #define DUK_HTHREAD_STRING_GET_UTC_DAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_DAY)
  2051. #define DUK_HEAP_STRING_GET_DAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_DAY)
  2052. #define DUK_HTHREAD_STRING_GET_DAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_DAY)
  2053. #define DUK_HEAP_STRING_GET_UTC_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_DATE)
  2054. #define DUK_HTHREAD_STRING_GET_UTC_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_DATE)
  2055. #define DUK_HEAP_STRING_GET_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_DATE)
  2056. #define DUK_HTHREAD_STRING_GET_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_DATE)
  2057. #define DUK_HEAP_STRING_GET_UTC_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MONTH)
  2058. #define DUK_HTHREAD_STRING_GET_UTC_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MONTH)
  2059. #define DUK_HEAP_STRING_GET_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MONTH)
  2060. #define DUK_HTHREAD_STRING_GET_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MONTH)
  2061. #define DUK_HEAP_STRING_GET_UTC_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_FULL_YEAR)
  2062. #define DUK_HTHREAD_STRING_GET_UTC_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_FULL_YEAR)
  2063. #define DUK_HEAP_STRING_GET_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_FULL_YEAR)
  2064. #define DUK_HTHREAD_STRING_GET_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_FULL_YEAR)
  2065. #define DUK_HEAP_STRING_GET_TIME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_TIME)
  2066. #define DUK_HTHREAD_STRING_GET_TIME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_TIME)
  2067. #define DUK_HEAP_STRING_TO_LOCALE_TIME_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_TIME_STRING)
  2068. #define DUK_HTHREAD_STRING_TO_LOCALE_TIME_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_TIME_STRING)
  2069. #define DUK_HEAP_STRING_TO_LOCALE_DATE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_DATE_STRING)
  2070. #define DUK_HTHREAD_STRING_TO_LOCALE_DATE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_DATE_STRING)
  2071. #define DUK_HEAP_STRING_TO_TIME_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_TIME_STRING)
  2072. #define DUK_HTHREAD_STRING_TO_TIME_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_TIME_STRING)
  2073. #define DUK_HEAP_STRING_TO_DATE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_DATE_STRING)
  2074. #define DUK_HTHREAD_STRING_TO_DATE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_DATE_STRING)
  2075. #define DUK_HEAP_STRING_NOW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NOW)
  2076. #define DUK_HTHREAD_STRING_NOW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NOW)
  2077. #define DUK_HEAP_STRING_UTC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UTC)
  2078. #define DUK_HTHREAD_STRING_UTC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UTC)
  2079. #define DUK_HEAP_STRING_PARSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE)
  2080. #define DUK_HTHREAD_STRING_PARSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE)
  2081. #define DUK_HEAP_STRING_TO_PRECISION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_PRECISION)
  2082. #define DUK_HTHREAD_STRING_TO_PRECISION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_PRECISION)
  2083. #define DUK_HEAP_STRING_TO_EXPONENTIAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_EXPONENTIAL)
  2084. #define DUK_HTHREAD_STRING_TO_EXPONENTIAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_EXPONENTIAL)
  2085. #define DUK_HEAP_STRING_TO_FIXED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_FIXED)
  2086. #define DUK_HTHREAD_STRING_TO_FIXED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_FIXED)
  2087. #define DUK_HEAP_STRING_POSITIVE_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POSITIVE_INFINITY)
  2088. #define DUK_HTHREAD_STRING_POSITIVE_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POSITIVE_INFINITY)
  2089. #define DUK_HEAP_STRING_NEGATIVE_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEGATIVE_INFINITY)
  2090. #define DUK_HTHREAD_STRING_NEGATIVE_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEGATIVE_INFINITY)
  2091. #define DUK_HEAP_STRING_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NAN)
  2092. #define DUK_HTHREAD_STRING_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NAN)
  2093. #define DUK_HEAP_STRING_MIN_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MIN_VALUE)
  2094. #define DUK_HTHREAD_STRING_MIN_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MIN_VALUE)
  2095. #define DUK_HEAP_STRING_MAX_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAX_VALUE)
  2096. #define DUK_HTHREAD_STRING_MAX_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAX_VALUE)
  2097. #define DUK_HEAP_STRING_SUBSTR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUBSTR)
  2098. #define DUK_HTHREAD_STRING_SUBSTR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUBSTR)
  2099. #define DUK_HEAP_STRING_TRIM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRIM)
  2100. #define DUK_HTHREAD_STRING_TRIM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRIM)
  2101. #define DUK_HEAP_STRING_TO_LOCALE_UPPER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_UPPER_CASE)
  2102. #define DUK_HTHREAD_STRING_TO_LOCALE_UPPER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_UPPER_CASE)
  2103. #define DUK_HEAP_STRING_TO_UPPER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_UPPER_CASE)
  2104. #define DUK_HTHREAD_STRING_TO_UPPER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_UPPER_CASE)
  2105. #define DUK_HEAP_STRING_TO_LOCALE_LOWER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_LOWER_CASE)
  2106. #define DUK_HTHREAD_STRING_TO_LOCALE_LOWER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_LOWER_CASE)
  2107. #define DUK_HEAP_STRING_TO_LOWER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOWER_CASE)
  2108. #define DUK_HTHREAD_STRING_TO_LOWER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOWER_CASE)
  2109. #define DUK_HEAP_STRING_SUBSTRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUBSTRING)
  2110. #define DUK_HTHREAD_STRING_SUBSTRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUBSTRING)
  2111. #define DUK_HEAP_STRING_SPLIT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPLIT)
  2112. #define DUK_HTHREAD_STRING_SPLIT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPLIT)
  2113. #define DUK_HEAP_STRING_SEARCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SEARCH)
  2114. #define DUK_HTHREAD_STRING_SEARCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SEARCH)
  2115. #define DUK_HEAP_STRING_REPLACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REPLACE)
  2116. #define DUK_HTHREAD_STRING_REPLACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REPLACE)
  2117. #define DUK_HEAP_STRING_MATCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MATCH)
  2118. #define DUK_HTHREAD_STRING_MATCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MATCH)
  2119. #define DUK_HEAP_STRING_LOCALE_COMPARE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOCALE_COMPARE)
  2120. #define DUK_HTHREAD_STRING_LOCALE_COMPARE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOCALE_COMPARE)
  2121. #define DUK_HEAP_STRING_CHAR_CODE_AT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CHAR_CODE_AT)
  2122. #define DUK_HTHREAD_STRING_CHAR_CODE_AT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CHAR_CODE_AT)
  2123. #define DUK_HEAP_STRING_CHAR_AT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CHAR_AT)
  2124. #define DUK_HTHREAD_STRING_CHAR_AT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CHAR_AT)
  2125. #define DUK_HEAP_STRING_FROM_CHAR_CODE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FROM_CHAR_CODE)
  2126. #define DUK_HTHREAD_STRING_FROM_CHAR_CODE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FROM_CHAR_CODE)
  2127. #define DUK_HEAP_STRING_REDUCE_RIGHT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REDUCE_RIGHT)
  2128. #define DUK_HTHREAD_STRING_REDUCE_RIGHT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REDUCE_RIGHT)
  2129. #define DUK_HEAP_STRING_REDUCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REDUCE)
  2130. #define DUK_HTHREAD_STRING_REDUCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REDUCE)
  2131. #define DUK_HEAP_STRING_FILTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FILTER)
  2132. #define DUK_HTHREAD_STRING_FILTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FILTER)
  2133. #define DUK_HEAP_STRING_MAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAP)
  2134. #define DUK_HTHREAD_STRING_MAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAP)
  2135. #define DUK_HEAP_STRING_FOR_EACH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FOR_EACH)
  2136. #define DUK_HTHREAD_STRING_FOR_EACH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FOR_EACH)
  2137. #define DUK_HEAP_STRING_SOME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SOME)
  2138. #define DUK_HTHREAD_STRING_SOME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SOME)
  2139. #define DUK_HEAP_STRING_EVERY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVERY)
  2140. #define DUK_HTHREAD_STRING_EVERY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVERY)
  2141. #define DUK_HEAP_STRING_LAST_INDEX_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LAST_INDEX_OF)
  2142. #define DUK_HTHREAD_STRING_LAST_INDEX_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LAST_INDEX_OF)
  2143. #define DUK_HEAP_STRING_INDEX_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INDEX_OF)
  2144. #define DUK_HTHREAD_STRING_INDEX_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INDEX_OF)
  2145. #define DUK_HEAP_STRING_UNSHIFT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UNSHIFT)
  2146. #define DUK_HTHREAD_STRING_UNSHIFT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UNSHIFT)
  2147. #define DUK_HEAP_STRING_SPLICE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPLICE)
  2148. #define DUK_HTHREAD_STRING_SPLICE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPLICE)
  2149. #define DUK_HEAP_STRING_SORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SORT)
  2150. #define DUK_HTHREAD_STRING_SORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SORT)
  2151. #define DUK_HEAP_STRING_SLICE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SLICE)
  2152. #define DUK_HTHREAD_STRING_SLICE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SLICE)
  2153. #define DUK_HEAP_STRING_SHIFT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SHIFT)
  2154. #define DUK_HTHREAD_STRING_SHIFT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SHIFT)
  2155. #define DUK_HEAP_STRING_REVERSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REVERSE)
  2156. #define DUK_HTHREAD_STRING_REVERSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REVERSE)
  2157. #define DUK_HEAP_STRING_PUSH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PUSH)
  2158. #define DUK_HTHREAD_STRING_PUSH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PUSH)
  2159. #define DUK_HEAP_STRING_POP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POP)
  2160. #define DUK_HTHREAD_STRING_POP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POP)
  2161. #define DUK_HEAP_STRING_JOIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JOIN)
  2162. #define DUK_HTHREAD_STRING_JOIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JOIN)
  2163. #define DUK_HEAP_STRING_CONCAT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONCAT)
  2164. #define DUK_HTHREAD_STRING_CONCAT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONCAT)
  2165. #define DUK_HEAP_STRING_IS_ARRAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_ARRAY)
  2166. #define DUK_HTHREAD_STRING_IS_ARRAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_ARRAY)
  2167. #define DUK_HEAP_STRING_LC_ARGUMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_ARGUMENTS)
  2168. #define DUK_HTHREAD_STRING_LC_ARGUMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_ARGUMENTS)
  2169. #define DUK_HEAP_STRING_CALLER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALLER)
  2170. #define DUK_HTHREAD_STRING_CALLER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALLER)
  2171. #define DUK_HEAP_STRING_BIND(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BIND)
  2172. #define DUK_HTHREAD_STRING_BIND(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BIND)
  2173. #define DUK_HEAP_STRING_CALL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALL)
  2174. #define DUK_HTHREAD_STRING_CALL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALL)
  2175. #define DUK_HEAP_STRING_APPLY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_APPLY)
  2176. #define DUK_HTHREAD_STRING_APPLY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_APPLY)
  2177. #define DUK_HEAP_STRING_PROPERTY_IS_ENUMERABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROPERTY_IS_ENUMERABLE)
  2178. #define DUK_HTHREAD_STRING_PROPERTY_IS_ENUMERABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROPERTY_IS_ENUMERABLE)
  2179. #define DUK_HEAP_STRING_IS_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_PROTOTYPE_OF)
  2180. #define DUK_HTHREAD_STRING_IS_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_PROTOTYPE_OF)
  2181. #define DUK_HEAP_STRING_HAS_OWN_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HAS_OWN_PROPERTY)
  2182. #define DUK_HTHREAD_STRING_HAS_OWN_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HAS_OWN_PROPERTY)
  2183. #define DUK_HEAP_STRING_VALUE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VALUE_OF)
  2184. #define DUK_HTHREAD_STRING_VALUE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VALUE_OF)
  2185. #define DUK_HEAP_STRING_TO_LOCALE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_STRING)
  2186. #define DUK_HTHREAD_STRING_TO_LOCALE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_STRING)
  2187. #define DUK_HEAP_STRING_TO_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_STRING)
  2188. #define DUK_HTHREAD_STRING_TO_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_STRING)
  2189. #define DUK_HEAP_STRING_CONSTRUCTOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONSTRUCTOR)
  2190. #define DUK_HTHREAD_STRING_CONSTRUCTOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONSTRUCTOR)
  2191. #define DUK_HEAP_STRING_SET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET)
  2192. #define DUK_HTHREAD_STRING_SET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET)
  2193. #define DUK_HEAP_STRING_GET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET)
  2194. #define DUK_HTHREAD_STRING_GET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET)
  2195. #define DUK_HEAP_STRING_ENUMERABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUMERABLE)
  2196. #define DUK_HTHREAD_STRING_ENUMERABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUMERABLE)
  2197. #define DUK_HEAP_STRING_CONFIGURABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONFIGURABLE)
  2198. #define DUK_HTHREAD_STRING_CONFIGURABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONFIGURABLE)
  2199. #define DUK_HEAP_STRING_WRITABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WRITABLE)
  2200. #define DUK_HTHREAD_STRING_WRITABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WRITABLE)
  2201. #define DUK_HEAP_STRING_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VALUE)
  2202. #define DUK_HTHREAD_STRING_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VALUE)
  2203. #define DUK_HEAP_STRING_KEYS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_KEYS)
  2204. #define DUK_HTHREAD_STRING_KEYS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_KEYS)
  2205. #define DUK_HEAP_STRING_IS_EXTENSIBLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_EXTENSIBLE)
  2206. #define DUK_HTHREAD_STRING_IS_EXTENSIBLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_EXTENSIBLE)
  2207. #define DUK_HEAP_STRING_IS_FROZEN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_FROZEN)
  2208. #define DUK_HTHREAD_STRING_IS_FROZEN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_FROZEN)
  2209. #define DUK_HEAP_STRING_IS_SEALED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_SEALED)
  2210. #define DUK_HTHREAD_STRING_IS_SEALED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_SEALED)
  2211. #define DUK_HEAP_STRING_PREVENT_EXTENSIONS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PREVENT_EXTENSIONS)
  2212. #define DUK_HTHREAD_STRING_PREVENT_EXTENSIONS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PREVENT_EXTENSIONS)
  2213. #define DUK_HEAP_STRING_FREEZE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FREEZE)
  2214. #define DUK_HTHREAD_STRING_FREEZE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FREEZE)
  2215. #define DUK_HEAP_STRING_SEAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SEAL)
  2216. #define DUK_HTHREAD_STRING_SEAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SEAL)
  2217. #define DUK_HEAP_STRING_DEFINE_PROPERTIES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFINE_PROPERTIES)
  2218. #define DUK_HTHREAD_STRING_DEFINE_PROPERTIES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFINE_PROPERTIES)
  2219. #define DUK_HEAP_STRING_DEFINE_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFINE_PROPERTY)
  2220. #define DUK_HTHREAD_STRING_DEFINE_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFINE_PROPERTY)
  2221. #define DUK_HEAP_STRING_CREATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CREATE)
  2222. #define DUK_HTHREAD_STRING_CREATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CREATE)
  2223. #define DUK_HEAP_STRING_GET_OWN_PROPERTY_NAMES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_OWN_PROPERTY_NAMES)
  2224. #define DUK_HTHREAD_STRING_GET_OWN_PROPERTY_NAMES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_OWN_PROPERTY_NAMES)
  2225. #define DUK_HEAP_STRING_GET_OWN_PROPERTY_DESCRIPTOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR)
  2226. #define DUK_HTHREAD_STRING_GET_OWN_PROPERTY_DESCRIPTOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR)
  2227. #define DUK_HEAP_STRING_GET_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_PROTOTYPE_OF)
  2228. #define DUK_HTHREAD_STRING_GET_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_PROTOTYPE_OF)
  2229. #define DUK_HEAP_STRING_PROTOTYPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROTOTYPE)
  2230. #define DUK_HTHREAD_STRING_PROTOTYPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROTOTYPE)
  2231. #define DUK_HEAP_STRING_LENGTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LENGTH)
  2232. #define DUK_HTHREAD_STRING_LENGTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LENGTH)
  2233. #define DUK_HEAP_STRING_ALERT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ALERT)
  2234. #define DUK_HTHREAD_STRING_ALERT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ALERT)
  2235. #define DUK_HEAP_STRING_PRINT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PRINT)
  2236. #define DUK_HTHREAD_STRING_PRINT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PRINT)
  2237. #define DUK_HEAP_STRING_UNESCAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UNESCAPE)
  2238. #define DUK_HTHREAD_STRING_UNESCAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UNESCAPE)
  2239. #define DUK_HEAP_STRING_ESCAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ESCAPE)
  2240. #define DUK_HTHREAD_STRING_ESCAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ESCAPE)
  2241. #define DUK_HEAP_STRING_ENCODE_URI_COMPONENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENCODE_URI_COMPONENT)
  2242. #define DUK_HTHREAD_STRING_ENCODE_URI_COMPONENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENCODE_URI_COMPONENT)
  2243. #define DUK_HEAP_STRING_ENCODE_URI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENCODE_URI)
  2244. #define DUK_HTHREAD_STRING_ENCODE_URI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENCODE_URI)
  2245. #define DUK_HEAP_STRING_DECODE_URI_COMPONENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DECODE_URI_COMPONENT)
  2246. #define DUK_HTHREAD_STRING_DECODE_URI_COMPONENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DECODE_URI_COMPONENT)
  2247. #define DUK_HEAP_STRING_DECODE_URI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DECODE_URI)
  2248. #define DUK_HTHREAD_STRING_DECODE_URI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DECODE_URI)
  2249. #define DUK_HEAP_STRING_IS_FINITE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_FINITE)
  2250. #define DUK_HTHREAD_STRING_IS_FINITE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_FINITE)
  2251. #define DUK_HEAP_STRING_IS_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_NAN)
  2252. #define DUK_HTHREAD_STRING_IS_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_NAN)
  2253. #define DUK_HEAP_STRING_PARSE_FLOAT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE_FLOAT)
  2254. #define DUK_HTHREAD_STRING_PARSE_FLOAT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE_FLOAT)
  2255. #define DUK_HEAP_STRING_PARSE_INT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE_INT)
  2256. #define DUK_HTHREAD_STRING_PARSE_INT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE_INT)
  2257. #define DUK_HEAP_STRING_EVAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVAL)
  2258. #define DUK_HTHREAD_STRING_EVAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVAL)
  2259. #define DUK_HEAP_STRING_URI_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_URI_ERROR)
  2260. #define DUK_HTHREAD_STRING_URI_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_URI_ERROR)
  2261. #define DUK_HEAP_STRING_TYPE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TYPE_ERROR)
  2262. #define DUK_HTHREAD_STRING_TYPE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TYPE_ERROR)
  2263. #define DUK_HEAP_STRING_SYNTAX_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SYNTAX_ERROR)
  2264. #define DUK_HTHREAD_STRING_SYNTAX_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SYNTAX_ERROR)
  2265. #define DUK_HEAP_STRING_REFERENCE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REFERENCE_ERROR)
  2266. #define DUK_HTHREAD_STRING_REFERENCE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REFERENCE_ERROR)
  2267. #define DUK_HEAP_STRING_RANGE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RANGE_ERROR)
  2268. #define DUK_HTHREAD_STRING_RANGE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RANGE_ERROR)
  2269. #define DUK_HEAP_STRING_EVAL_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVAL_ERROR)
  2270. #define DUK_HTHREAD_STRING_EVAL_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVAL_ERROR)
  2271. #define DUK_HEAP_STRING_BREAK(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BREAK)
  2272. #define DUK_HTHREAD_STRING_BREAK(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BREAK)
  2273. #define DUK_HEAP_STRING_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CASE)
  2274. #define DUK_HTHREAD_STRING_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CASE)
  2275. #define DUK_HEAP_STRING_CATCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CATCH)
  2276. #define DUK_HTHREAD_STRING_CATCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CATCH)
  2277. #define DUK_HEAP_STRING_CONTINUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONTINUE)
  2278. #define DUK_HTHREAD_STRING_CONTINUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONTINUE)
  2279. #define DUK_HEAP_STRING_DEBUGGER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEBUGGER)
  2280. #define DUK_HTHREAD_STRING_DEBUGGER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEBUGGER)
  2281. #define DUK_HEAP_STRING_DEFAULT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFAULT)
  2282. #define DUK_HTHREAD_STRING_DEFAULT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFAULT)
  2283. #define DUK_HEAP_STRING_DELETE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DELETE)
  2284. #define DUK_HTHREAD_STRING_DELETE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DELETE)
  2285. #define DUK_HEAP_STRING_DO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DO)
  2286. #define DUK_HTHREAD_STRING_DO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DO)
  2287. #define DUK_HEAP_STRING_ELSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ELSE)
  2288. #define DUK_HTHREAD_STRING_ELSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ELSE)
  2289. #define DUK_HEAP_STRING_FINALLY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FINALLY)
  2290. #define DUK_HTHREAD_STRING_FINALLY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FINALLY)
  2291. #define DUK_HEAP_STRING_FOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FOR)
  2292. #define DUK_HTHREAD_STRING_FOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FOR)
  2293. #define DUK_HEAP_STRING_LC_FUNCTION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_FUNCTION)
  2294. #define DUK_HTHREAD_STRING_LC_FUNCTION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_FUNCTION)
  2295. #define DUK_HEAP_STRING_IF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IF)
  2296. #define DUK_HTHREAD_STRING_IF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IF)
  2297. #define DUK_HEAP_STRING_IN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IN)
  2298. #define DUK_HTHREAD_STRING_IN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IN)
  2299. #define DUK_HEAP_STRING_INSTANCEOF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INSTANCEOF)
  2300. #define DUK_HTHREAD_STRING_INSTANCEOF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INSTANCEOF)
  2301. #define DUK_HEAP_STRING_NEW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEW)
  2302. #define DUK_HTHREAD_STRING_NEW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEW)
  2303. #define DUK_HEAP_STRING_RETURN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RETURN)
  2304. #define DUK_HTHREAD_STRING_RETURN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RETURN)
  2305. #define DUK_HEAP_STRING_SWITCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SWITCH)
  2306. #define DUK_HTHREAD_STRING_SWITCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SWITCH)
  2307. #define DUK_HEAP_STRING_THIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THIS)
  2308. #define DUK_HTHREAD_STRING_THIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THIS)
  2309. #define DUK_HEAP_STRING_THROW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THROW)
  2310. #define DUK_HTHREAD_STRING_THROW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THROW)
  2311. #define DUK_HEAP_STRING_TRY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRY)
  2312. #define DUK_HTHREAD_STRING_TRY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRY)
  2313. #define DUK_HEAP_STRING_TYPEOF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TYPEOF)
  2314. #define DUK_HTHREAD_STRING_TYPEOF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TYPEOF)
  2315. #define DUK_HEAP_STRING_VAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VAR)
  2316. #define DUK_HTHREAD_STRING_VAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VAR)
  2317. #define DUK_HEAP_STRING_VOID(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VOID)
  2318. #define DUK_HTHREAD_STRING_VOID(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VOID)
  2319. #define DUK_HEAP_STRING_WHILE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WHILE)
  2320. #define DUK_HTHREAD_STRING_WHILE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WHILE)
  2321. #define DUK_HEAP_STRING_WITH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WITH)
  2322. #define DUK_HTHREAD_STRING_WITH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WITH)
  2323. #define DUK_HEAP_STRING_CLASS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CLASS)
  2324. #define DUK_HTHREAD_STRING_CLASS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CLASS)
  2325. #define DUK_HEAP_STRING_CONST(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONST)
  2326. #define DUK_HTHREAD_STRING_CONST(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONST)
  2327. #define DUK_HEAP_STRING_ENUM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUM)
  2328. #define DUK_HTHREAD_STRING_ENUM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUM)
  2329. #define DUK_HEAP_STRING_EXPORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXPORT)
  2330. #define DUK_HTHREAD_STRING_EXPORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXPORT)
  2331. #define DUK_HEAP_STRING_EXTENDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXTENDS)
  2332. #define DUK_HTHREAD_STRING_EXTENDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXTENDS)
  2333. #define DUK_HEAP_STRING_IMPORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IMPORT)
  2334. #define DUK_HTHREAD_STRING_IMPORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IMPORT)
  2335. #define DUK_HEAP_STRING_SUPER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUPER)
  2336. #define DUK_HTHREAD_STRING_SUPER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUPER)
  2337. #define DUK_HEAP_STRING_LC_NULL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_NULL)
  2338. #define DUK_HTHREAD_STRING_LC_NULL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_NULL)
  2339. #define DUK_HEAP_STRING_TRUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRUE)
  2340. #define DUK_HTHREAD_STRING_TRUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRUE)
  2341. #define DUK_HEAP_STRING_FALSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FALSE)
  2342. #define DUK_HTHREAD_STRING_FALSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FALSE)
  2343. #define DUK_HEAP_STRING_IMPLEMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IMPLEMENTS)
  2344. #define DUK_HTHREAD_STRING_IMPLEMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IMPLEMENTS)
  2345. #define DUK_HEAP_STRING_INTERFACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INTERFACE)
  2346. #define DUK_HTHREAD_STRING_INTERFACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INTERFACE)
  2347. #define DUK_HEAP_STRING_LET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LET)
  2348. #define DUK_HTHREAD_STRING_LET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LET)
  2349. #define DUK_HEAP_STRING_PACKAGE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PACKAGE)
  2350. #define DUK_HTHREAD_STRING_PACKAGE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PACKAGE)
  2351. #define DUK_HEAP_STRING_PRIVATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PRIVATE)
  2352. #define DUK_HTHREAD_STRING_PRIVATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PRIVATE)
  2353. #define DUK_HEAP_STRING_PROTECTED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROTECTED)
  2354. #define DUK_HTHREAD_STRING_PROTECTED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROTECTED)
  2355. #define DUK_HEAP_STRING_PUBLIC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PUBLIC)
  2356. #define DUK_HTHREAD_STRING_PUBLIC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PUBLIC)
  2357. #define DUK_HEAP_STRING_STATIC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STATIC)
  2358. #define DUK_HTHREAD_STRING_STATIC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STATIC)
  2359. #define DUK_HEAP_STRING_YIELD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_YIELD)
  2360. #define DUK_HTHREAD_STRING_YIELD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_YIELD)
  2361. #define DUK_HEAP_NUM_STRINGS 336
  2362. #define DUK_STRIDX_START_RESERVED 291
  2363. #define DUK_STRIDX_START_STRICT_RESERVED 327
  2364. #define DUK_STRIDX_END_RESERVED 336 /* exclusive endpoint */
  2365. #if !defined(DUK_SINGLE_FILE)
  2366. DUK_INTERNAL_DECL const duk_c_function duk_bi_native_functions[128];
  2367. DUK_INTERNAL_DECL const duk_uint8_t duk_builtins_data[1341];
  2368. #ifdef DUK_USE_BUILTIN_INITJS
  2369. DUK_INTERNAL_DECL const duk_uint8_t duk_initjs_data[187];
  2370. #endif /* DUK_USE_BUILTIN_INITJS */
  2371. #endif /* !DUK_SINGLE_FILE */
  2372. #define DUK_BUILTINS_DATA_LENGTH 1341
  2373. #ifdef DUK_USE_BUILTIN_INITJS
  2374. #define DUK_BUILTIN_INITJS_DATA_LENGTH 187
  2375. #endif /* DUK_USE_BUILTIN_INITJS */
  2376. #define DUK_BIDX_GLOBAL 0
  2377. #define DUK_BIDX_GLOBAL_ENV 1
  2378. #define DUK_BIDX_OBJECT_CONSTRUCTOR 2
  2379. #define DUK_BIDX_OBJECT_PROTOTYPE 3
  2380. #define DUK_BIDX_FUNCTION_CONSTRUCTOR 4
  2381. #define DUK_BIDX_FUNCTION_PROTOTYPE 5
  2382. #define DUK_BIDX_ARRAY_CONSTRUCTOR 6
  2383. #define DUK_BIDX_ARRAY_PROTOTYPE 7
  2384. #define DUK_BIDX_STRING_CONSTRUCTOR 8
  2385. #define DUK_BIDX_STRING_PROTOTYPE 9
  2386. #define DUK_BIDX_BOOLEAN_CONSTRUCTOR 10
  2387. #define DUK_BIDX_BOOLEAN_PROTOTYPE 11
  2388. #define DUK_BIDX_NUMBER_CONSTRUCTOR 12
  2389. #define DUK_BIDX_NUMBER_PROTOTYPE 13
  2390. #define DUK_BIDX_DATE_CONSTRUCTOR 14
  2391. #define DUK_BIDX_DATE_PROTOTYPE 15
  2392. #define DUK_BIDX_REGEXP_CONSTRUCTOR 16
  2393. #define DUK_BIDX_REGEXP_PROTOTYPE 17
  2394. #define DUK_BIDX_ERROR_CONSTRUCTOR 18
  2395. #define DUK_BIDX_ERROR_PROTOTYPE 19
  2396. #define DUK_BIDX_EVAL_ERROR_CONSTRUCTOR 20
  2397. #define DUK_BIDX_EVAL_ERROR_PROTOTYPE 21
  2398. #define DUK_BIDX_RANGE_ERROR_CONSTRUCTOR 22
  2399. #define DUK_BIDX_RANGE_ERROR_PROTOTYPE 23
  2400. #define DUK_BIDX_REFERENCE_ERROR_CONSTRUCTOR 24
  2401. #define DUK_BIDX_REFERENCE_ERROR_PROTOTYPE 25
  2402. #define DUK_BIDX_SYNTAX_ERROR_CONSTRUCTOR 26
  2403. #define DUK_BIDX_SYNTAX_ERROR_PROTOTYPE 27
  2404. #define DUK_BIDX_TYPE_ERROR_CONSTRUCTOR 28
  2405. #define DUK_BIDX_TYPE_ERROR_PROTOTYPE 29
  2406. #define DUK_BIDX_URI_ERROR_CONSTRUCTOR 30
  2407. #define DUK_BIDX_URI_ERROR_PROTOTYPE 31
  2408. #define DUK_BIDX_MATH 32
  2409. #define DUK_BIDX_JSON 33
  2410. #define DUK_BIDX_TYPE_ERROR_THROWER 34
  2411. #define DUK_BIDX_PROXY_CONSTRUCTOR 35
  2412. #define DUK_BIDX_DUKTAPE 36
  2413. #define DUK_BIDX_THREAD_CONSTRUCTOR 37
  2414. #define DUK_BIDX_THREAD_PROTOTYPE 38
  2415. #define DUK_BIDX_BUFFER_CONSTRUCTOR 39
  2416. #define DUK_BIDX_BUFFER_PROTOTYPE 40
  2417. #define DUK_BIDX_POINTER_CONSTRUCTOR 41
  2418. #define DUK_BIDX_POINTER_PROTOTYPE 42
  2419. #define DUK_BIDX_LOGGER_CONSTRUCTOR 43
  2420. #define DUK_BIDX_LOGGER_PROTOTYPE 44
  2421. #define DUK_BIDX_DOUBLE_ERROR 45
  2422. #define DUK_NUM_BUILTINS 46
  2423. #elif defined(DUK_USE_DOUBLE_ME)
  2424. #if !defined(DUK_SINGLE_FILE)
  2425. DUK_INTERNAL_DECL const duk_uint8_t duk_strings_data[1943];
  2426. #endif /* !DUK_SINGLE_FILE */
  2427. #define DUK_STRDATA_DATA_LENGTH 1943
  2428. #define DUK_STRDATA_MAX_STRLEN 24
  2429. #define DUK_STRIDX_UC_LOGGER 0 /* 'Logger' */
  2430. #define DUK_STRIDX_UC_THREAD 1 /* 'Thread' */
  2431. #define DUK_STRIDX_UC_POINTER 2 /* 'Pointer' */
  2432. #define DUK_STRIDX_UC_BUFFER 3 /* 'Buffer' */
  2433. #define DUK_STRIDX_DEC_ENV 4 /* 'DecEnv' */
  2434. #define DUK_STRIDX_OBJ_ENV 5 /* 'ObjEnv' */
  2435. #define DUK_STRIDX_EMPTY_STRING 6 /* '' */
  2436. #define DUK_STRIDX_GLOBAL 7 /* 'global' */
  2437. #define DUK_STRIDX_UC_ARGUMENTS 8 /* 'Arguments' */
  2438. #define DUK_STRIDX_JSON 9 /* 'JSON' */
  2439. #define DUK_STRIDX_MATH 10 /* 'Math' */
  2440. #define DUK_STRIDX_UC_ERROR 11 /* 'Error' */
  2441. #define DUK_STRIDX_REG_EXP 12 /* 'RegExp' */
  2442. #define DUK_STRIDX_DATE 13 /* 'Date' */
  2443. #define DUK_STRIDX_UC_NUMBER 14 /* 'Number' */
  2444. #define DUK_STRIDX_UC_BOOLEAN 15 /* 'Boolean' */
  2445. #define DUK_STRIDX_UC_STRING 16 /* 'String' */
  2446. #define DUK_STRIDX_ARRAY 17 /* 'Array' */
  2447. #define DUK_STRIDX_UC_FUNCTION 18 /* 'Function' */
  2448. #define DUK_STRIDX_UC_OBJECT 19 /* 'Object' */
  2449. #define DUK_STRIDX_UC_NULL 20 /* 'Null' */
  2450. #define DUK_STRIDX_UC_UNDEFINED 21 /* 'Undefined' */
  2451. #define DUK_STRIDX_JSON_EXT_FUNCTION2 22 /* '{_func:true}' */
  2452. #define DUK_STRIDX_JSON_EXT_FUNCTION1 23 /* '{"_func":true}' */
  2453. #define DUK_STRIDX_JSON_EXT_NEGINF 24 /* '{"_ninf":true}' */
  2454. #define DUK_STRIDX_JSON_EXT_POSINF 25 /* '{"_inf":true}' */
  2455. #define DUK_STRIDX_JSON_EXT_NAN 26 /* '{"_nan":true}' */
  2456. #define DUK_STRIDX_JSON_EXT_UNDEFINED 27 /* '{"_undef":true}' */
  2457. #define DUK_STRIDX_TO_LOG_STRING 28 /* 'toLogString' */
  2458. #define DUK_STRIDX_CLOG 29 /* 'clog' */
  2459. #define DUK_STRIDX_LC_L 30 /* 'l' */
  2460. #define DUK_STRIDX_LC_N 31 /* 'n' */
  2461. #define DUK_STRIDX_LC_FATAL 32 /* 'fatal' */
  2462. #define DUK_STRIDX_LC_ERROR 33 /* 'error' */
  2463. #define DUK_STRIDX_LC_WARN 34 /* 'warn' */
  2464. #define DUK_STRIDX_LC_DEBUG 35 /* 'debug' */
  2465. #define DUK_STRIDX_LC_TRACE 36 /* 'trace' */
  2466. #define DUK_STRIDX_RAW 37 /* 'raw' */
  2467. #define DUK_STRIDX_FMT 38 /* 'fmt' */
  2468. #define DUK_STRIDX_CURRENT 39 /* 'current' */
  2469. #define DUK_STRIDX_RESUME 40 /* 'resume' */
  2470. #define DUK_STRIDX_COMPACT 41 /* 'compact' */
  2471. #define DUK_STRIDX_JC 42 /* 'jc' */
  2472. #define DUK_STRIDX_JX 43 /* 'jx' */
  2473. #define DUK_STRIDX_BASE64 44 /* 'base64' */
  2474. #define DUK_STRIDX_HEX 45 /* 'hex' */
  2475. #define DUK_STRIDX_DEC 46 /* 'dec' */
  2476. #define DUK_STRIDX_ENC 47 /* 'enc' */
  2477. #define DUK_STRIDX_FIN 48 /* 'fin' */
  2478. #define DUK_STRIDX_GC 49 /* 'gc' */
  2479. #define DUK_STRIDX_ACT 50 /* 'act' */
  2480. #define DUK_STRIDX_LC_INFO 51 /* 'info' */
  2481. #define DUK_STRIDX_VERSION 52 /* 'version' */
  2482. #define DUK_STRIDX_ENV 53 /* 'env' */
  2483. #define DUK_STRIDX_MOD_LOADED 54 /* 'modLoaded' */
  2484. #define DUK_STRIDX_MOD_SEARCH 55 /* 'modSearch' */
  2485. #define DUK_STRIDX_ERR_THROW 56 /* 'errThrow' */
  2486. #define DUK_STRIDX_ERR_CREATE 57 /* 'errCreate' */
  2487. #define DUK_STRIDX_COMPILE 58 /* 'compile' */
  2488. #define DUK_STRIDX_INT_REGBASE 59 /* '\x00Regbase' */
  2489. #define DUK_STRIDX_INT_THREAD 60 /* '\x00Thread' */
  2490. #define DUK_STRIDX_INT_HANDLER 61 /* '\x00Handler' */
  2491. #define DUK_STRIDX_INT_FINALIZER 62 /* '\x00Finalizer' */
  2492. #define DUK_STRIDX_INT_CALLEE 63 /* '\x00Callee' */
  2493. #define DUK_STRIDX_INT_MAP 64 /* '\x00Map' */
  2494. #define DUK_STRIDX_INT_ARGS 65 /* '\x00Args' */
  2495. #define DUK_STRIDX_INT_THIS 66 /* '\x00This' */
  2496. #define DUK_STRIDX_INT_PC2LINE 67 /* '\x00Pc2line' */
  2497. #define DUK_STRIDX_INT_SOURCE 68 /* '\x00Source' */
  2498. #define DUK_STRIDX_INT_VARENV 69 /* '\x00Varenv' */
  2499. #define DUK_STRIDX_INT_LEXENV 70 /* '\x00Lexenv' */
  2500. #define DUK_STRIDX_INT_VARMAP 71 /* '\x00Varmap' */
  2501. #define DUK_STRIDX_INT_FORMALS 72 /* '\x00Formals' */
  2502. #define DUK_STRIDX_INT_BYTECODE 73 /* '\x00Bytecode' */
  2503. #define DUK_STRIDX_INT_NEXT 74 /* '\x00Next' */
  2504. #define DUK_STRIDX_INT_TARGET 75 /* '\x00Target' */
  2505. #define DUK_STRIDX_INT_VALUE 76 /* '\x00Value' */
  2506. #define DUK_STRIDX_LC_POINTER 77 /* 'pointer' */
  2507. #define DUK_STRIDX_LC_BUFFER 78 /* 'buffer' */
  2508. #define DUK_STRIDX_INT_TRACEDATA 79 /* '\x00Tracedata' */
  2509. #define DUK_STRIDX_LINE_NUMBER 80 /* 'lineNumber' */
  2510. #define DUK_STRIDX_FILE_NAME 81 /* 'fileName' */
  2511. #define DUK_STRIDX_PC 82 /* 'pc' */
  2512. #define DUK_STRIDX_STACK 83 /* 'stack' */
  2513. #define DUK_STRIDX_THROW_TYPE_ERROR 84 /* 'ThrowTypeError' */
  2514. #define DUK_STRIDX_DUKTAPE 85 /* 'Duktape' */
  2515. #define DUK_STRIDX_ID 86 /* 'id' */
  2516. #define DUK_STRIDX_REQUIRE 87 /* 'require' */
  2517. #define DUK_STRIDX___PROTO__ 88 /* '__proto__' */
  2518. #define DUK_STRIDX_SET_PROTOTYPE_OF 89 /* 'setPrototypeOf' */
  2519. #define DUK_STRIDX_OWN_KEYS 90 /* 'ownKeys' */
  2520. #define DUK_STRIDX_ENUMERATE 91 /* 'enumerate' */
  2521. #define DUK_STRIDX_DELETE_PROPERTY 92 /* 'deleteProperty' */
  2522. #define DUK_STRIDX_HAS 93 /* 'has' */
  2523. #define DUK_STRIDX_PROXY 94 /* 'Proxy' */
  2524. #define DUK_STRIDX_CALLEE 95 /* 'callee' */
  2525. #define DUK_STRIDX_INVALID_DATE 96 /* 'Invalid Date' */
  2526. #define DUK_STRIDX_BRACKETED_ELLIPSIS 97 /* '[...]' */
  2527. #define DUK_STRIDX_NEWLINE_TAB 98 /* '\n\t' */
  2528. #define DUK_STRIDX_SPACE 99 /* ' ' */
  2529. #define DUK_STRIDX_COMMA 100 /* ',' */
  2530. #define DUK_STRIDX_MINUS_ZERO 101 /* '-0' */
  2531. #define DUK_STRIDX_PLUS_ZERO 102 /* '+0' */
  2532. #define DUK_STRIDX_ZERO 103 /* '0' */
  2533. #define DUK_STRIDX_MINUS_INFINITY 104 /* '-Infinity' */
  2534. #define DUK_STRIDX_PLUS_INFINITY 105 /* '+Infinity' */
  2535. #define DUK_STRIDX_INFINITY 106 /* 'Infinity' */
  2536. #define DUK_STRIDX_LC_OBJECT 107 /* 'object' */
  2537. #define DUK_STRIDX_LC_STRING 108 /* 'string' */
  2538. #define DUK_STRIDX_LC_NUMBER 109 /* 'number' */
  2539. #define DUK_STRIDX_LC_BOOLEAN 110 /* 'boolean' */
  2540. #define DUK_STRIDX_LC_UNDEFINED 111 /* 'undefined' */
  2541. #define DUK_STRIDX_STRINGIFY 112 /* 'stringify' */
  2542. #define DUK_STRIDX_TAN 113 /* 'tan' */
  2543. #define DUK_STRIDX_SQRT 114 /* 'sqrt' */
  2544. #define DUK_STRIDX_SIN 115 /* 'sin' */
  2545. #define DUK_STRIDX_ROUND 116 /* 'round' */
  2546. #define DUK_STRIDX_RANDOM 117 /* 'random' */
  2547. #define DUK_STRIDX_POW 118 /* 'pow' */
  2548. #define DUK_STRIDX_MIN 119 /* 'min' */
  2549. #define DUK_STRIDX_MAX 120 /* 'max' */
  2550. #define DUK_STRIDX_LOG 121 /* 'log' */
  2551. #define DUK_STRIDX_FLOOR 122 /* 'floor' */
  2552. #define DUK_STRIDX_EXP 123 /* 'exp' */
  2553. #define DUK_STRIDX_COS 124 /* 'cos' */
  2554. #define DUK_STRIDX_CEIL 125 /* 'ceil' */
  2555. #define DUK_STRIDX_ATAN2 126 /* 'atan2' */
  2556. #define DUK_STRIDX_ATAN 127 /* 'atan' */
  2557. #define DUK_STRIDX_ASIN 128 /* 'asin' */
  2558. #define DUK_STRIDX_ACOS 129 /* 'acos' */
  2559. #define DUK_STRIDX_ABS 130 /* 'abs' */
  2560. #define DUK_STRIDX_SQRT2 131 /* 'SQRT2' */
  2561. #define DUK_STRIDX_SQRT1_2 132 /* 'SQRT1_2' */
  2562. #define DUK_STRIDX_PI 133 /* 'PI' */
  2563. #define DUK_STRIDX_LOG10E 134 /* 'LOG10E' */
  2564. #define DUK_STRIDX_LOG2E 135 /* 'LOG2E' */
  2565. #define DUK_STRIDX_LN2 136 /* 'LN2' */
  2566. #define DUK_STRIDX_LN10 137 /* 'LN10' */
  2567. #define DUK_STRIDX_E 138 /* 'E' */
  2568. #define DUK_STRIDX_MESSAGE 139 /* 'message' */
  2569. #define DUK_STRIDX_NAME 140 /* 'name' */
  2570. #define DUK_STRIDX_INPUT 141 /* 'input' */
  2571. #define DUK_STRIDX_INDEX 142 /* 'index' */
  2572. #define DUK_STRIDX_ESCAPED_EMPTY_REGEXP 143 /* '(?:)' */
  2573. #define DUK_STRIDX_LAST_INDEX 144 /* 'lastIndex' */
  2574. #define DUK_STRIDX_MULTILINE 145 /* 'multiline' */
  2575. #define DUK_STRIDX_IGNORE_CASE 146 /* 'ignoreCase' */
  2576. #define DUK_STRIDX_SOURCE 147 /* 'source' */
  2577. #define DUK_STRIDX_TEST 148 /* 'test' */
  2578. #define DUK_STRIDX_EXEC 149 /* 'exec' */
  2579. #define DUK_STRIDX_TO_GMT_STRING 150 /* 'toGMTString' */
  2580. #define DUK_STRIDX_SET_YEAR 151 /* 'setYear' */
  2581. #define DUK_STRIDX_GET_YEAR 152 /* 'getYear' */
  2582. #define DUK_STRIDX_TO_JSON 153 /* 'toJSON' */
  2583. #define DUK_STRIDX_TO_ISO_STRING 154 /* 'toISOString' */
  2584. #define DUK_STRIDX_TO_UTC_STRING 155 /* 'toUTCString' */
  2585. #define DUK_STRIDX_SET_UTC_FULL_YEAR 156 /* 'setUTCFullYear' */
  2586. #define DUK_STRIDX_SET_FULL_YEAR 157 /* 'setFullYear' */
  2587. #define DUK_STRIDX_SET_UTC_MONTH 158 /* 'setUTCMonth' */
  2588. #define DUK_STRIDX_SET_MONTH 159 /* 'setMonth' */
  2589. #define DUK_STRIDX_SET_UTC_DATE 160 /* 'setUTCDate' */
  2590. #define DUK_STRIDX_SET_DATE 161 /* 'setDate' */
  2591. #define DUK_STRIDX_SET_UTC_HOURS 162 /* 'setUTCHours' */
  2592. #define DUK_STRIDX_SET_HOURS 163 /* 'setHours' */
  2593. #define DUK_STRIDX_SET_UTC_MINUTES 164 /* 'setUTCMinutes' */
  2594. #define DUK_STRIDX_SET_MINUTES 165 /* 'setMinutes' */
  2595. #define DUK_STRIDX_SET_UTC_SECONDS 166 /* 'setUTCSeconds' */
  2596. #define DUK_STRIDX_SET_SECONDS 167 /* 'setSeconds' */
  2597. #define DUK_STRIDX_SET_UTC_MILLISECONDS 168 /* 'setUTCMilliseconds' */
  2598. #define DUK_STRIDX_SET_MILLISECONDS 169 /* 'setMilliseconds' */
  2599. #define DUK_STRIDX_SET_TIME 170 /* 'setTime' */
  2600. #define DUK_STRIDX_GET_TIMEZONE_OFFSET 171 /* 'getTimezoneOffset' */
  2601. #define DUK_STRIDX_GET_UTC_MILLISECONDS 172 /* 'getUTCMilliseconds' */
  2602. #define DUK_STRIDX_GET_MILLISECONDS 173 /* 'getMilliseconds' */
  2603. #define DUK_STRIDX_GET_UTC_SECONDS 174 /* 'getUTCSeconds' */
  2604. #define DUK_STRIDX_GET_SECONDS 175 /* 'getSeconds' */
  2605. #define DUK_STRIDX_GET_UTC_MINUTES 176 /* 'getUTCMinutes' */
  2606. #define DUK_STRIDX_GET_MINUTES 177 /* 'getMinutes' */
  2607. #define DUK_STRIDX_GET_UTC_HOURS 178 /* 'getUTCHours' */
  2608. #define DUK_STRIDX_GET_HOURS 179 /* 'getHours' */
  2609. #define DUK_STRIDX_GET_UTC_DAY 180 /* 'getUTCDay' */
  2610. #define DUK_STRIDX_GET_DAY 181 /* 'getDay' */
  2611. #define DUK_STRIDX_GET_UTC_DATE 182 /* 'getUTCDate' */
  2612. #define DUK_STRIDX_GET_DATE 183 /* 'getDate' */
  2613. #define DUK_STRIDX_GET_UTC_MONTH 184 /* 'getUTCMonth' */
  2614. #define DUK_STRIDX_GET_MONTH 185 /* 'getMonth' */
  2615. #define DUK_STRIDX_GET_UTC_FULL_YEAR 186 /* 'getUTCFullYear' */
  2616. #define DUK_STRIDX_GET_FULL_YEAR 187 /* 'getFullYear' */
  2617. #define DUK_STRIDX_GET_TIME 188 /* 'getTime' */
  2618. #define DUK_STRIDX_TO_LOCALE_TIME_STRING 189 /* 'toLocaleTimeString' */
  2619. #define DUK_STRIDX_TO_LOCALE_DATE_STRING 190 /* 'toLocaleDateString' */
  2620. #define DUK_STRIDX_TO_TIME_STRING 191 /* 'toTimeString' */
  2621. #define DUK_STRIDX_TO_DATE_STRING 192 /* 'toDateString' */
  2622. #define DUK_STRIDX_NOW 193 /* 'now' */
  2623. #define DUK_STRIDX_UTC 194 /* 'UTC' */
  2624. #define DUK_STRIDX_PARSE 195 /* 'parse' */
  2625. #define DUK_STRIDX_TO_PRECISION 196 /* 'toPrecision' */
  2626. #define DUK_STRIDX_TO_EXPONENTIAL 197 /* 'toExponential' */
  2627. #define DUK_STRIDX_TO_FIXED 198 /* 'toFixed' */
  2628. #define DUK_STRIDX_POSITIVE_INFINITY 199 /* 'POSITIVE_INFINITY' */
  2629. #define DUK_STRIDX_NEGATIVE_INFINITY 200 /* 'NEGATIVE_INFINITY' */
  2630. #define DUK_STRIDX_NAN 201 /* 'NaN' */
  2631. #define DUK_STRIDX_MIN_VALUE 202 /* 'MIN_VALUE' */
  2632. #define DUK_STRIDX_MAX_VALUE 203 /* 'MAX_VALUE' */
  2633. #define DUK_STRIDX_SUBSTR 204 /* 'substr' */
  2634. #define DUK_STRIDX_TRIM 205 /* 'trim' */
  2635. #define DUK_STRIDX_TO_LOCALE_UPPER_CASE 206 /* 'toLocaleUpperCase' */
  2636. #define DUK_STRIDX_TO_UPPER_CASE 207 /* 'toUpperCase' */
  2637. #define DUK_STRIDX_TO_LOCALE_LOWER_CASE 208 /* 'toLocaleLowerCase' */
  2638. #define DUK_STRIDX_TO_LOWER_CASE 209 /* 'toLowerCase' */
  2639. #define DUK_STRIDX_SUBSTRING 210 /* 'substring' */
  2640. #define DUK_STRIDX_SPLIT 211 /* 'split' */
  2641. #define DUK_STRIDX_SEARCH 212 /* 'search' */
  2642. #define DUK_STRIDX_REPLACE 213 /* 'replace' */
  2643. #define DUK_STRIDX_MATCH 214 /* 'match' */
  2644. #define DUK_STRIDX_LOCALE_COMPARE 215 /* 'localeCompare' */
  2645. #define DUK_STRIDX_CHAR_CODE_AT 216 /* 'charCodeAt' */
  2646. #define DUK_STRIDX_CHAR_AT 217 /* 'charAt' */
  2647. #define DUK_STRIDX_FROM_CHAR_CODE 218 /* 'fromCharCode' */
  2648. #define DUK_STRIDX_REDUCE_RIGHT 219 /* 'reduceRight' */
  2649. #define DUK_STRIDX_REDUCE 220 /* 'reduce' */
  2650. #define DUK_STRIDX_FILTER 221 /* 'filter' */
  2651. #define DUK_STRIDX_MAP 222 /* 'map' */
  2652. #define DUK_STRIDX_FOR_EACH 223 /* 'forEach' */
  2653. #define DUK_STRIDX_SOME 224 /* 'some' */
  2654. #define DUK_STRIDX_EVERY 225 /* 'every' */
  2655. #define DUK_STRIDX_LAST_INDEX_OF 226 /* 'lastIndexOf' */
  2656. #define DUK_STRIDX_INDEX_OF 227 /* 'indexOf' */
  2657. #define DUK_STRIDX_UNSHIFT 228 /* 'unshift' */
  2658. #define DUK_STRIDX_SPLICE 229 /* 'splice' */
  2659. #define DUK_STRIDX_SORT 230 /* 'sort' */
  2660. #define DUK_STRIDX_SLICE 231 /* 'slice' */
  2661. #define DUK_STRIDX_SHIFT 232 /* 'shift' */
  2662. #define DUK_STRIDX_REVERSE 233 /* 'reverse' */
  2663. #define DUK_STRIDX_PUSH 234 /* 'push' */
  2664. #define DUK_STRIDX_POP 235 /* 'pop' */
  2665. #define DUK_STRIDX_JOIN 236 /* 'join' */
  2666. #define DUK_STRIDX_CONCAT 237 /* 'concat' */
  2667. #define DUK_STRIDX_IS_ARRAY 238 /* 'isArray' */
  2668. #define DUK_STRIDX_LC_ARGUMENTS 239 /* 'arguments' */
  2669. #define DUK_STRIDX_CALLER 240 /* 'caller' */
  2670. #define DUK_STRIDX_BIND 241 /* 'bind' */
  2671. #define DUK_STRIDX_CALL 242 /* 'call' */
  2672. #define DUK_STRIDX_APPLY 243 /* 'apply' */
  2673. #define DUK_STRIDX_PROPERTY_IS_ENUMERABLE 244 /* 'propertyIsEnumerable' */
  2674. #define DUK_STRIDX_IS_PROTOTYPE_OF 245 /* 'isPrototypeOf' */
  2675. #define DUK_STRIDX_HAS_OWN_PROPERTY 246 /* 'hasOwnProperty' */
  2676. #define DUK_STRIDX_VALUE_OF 247 /* 'valueOf' */
  2677. #define DUK_STRIDX_TO_LOCALE_STRING 248 /* 'toLocaleString' */
  2678. #define DUK_STRIDX_TO_STRING 249 /* 'toString' */
  2679. #define DUK_STRIDX_CONSTRUCTOR 250 /* 'constructor' */
  2680. #define DUK_STRIDX_SET 251 /* 'set' */
  2681. #define DUK_STRIDX_GET 252 /* 'get' */
  2682. #define DUK_STRIDX_ENUMERABLE 253 /* 'enumerable' */
  2683. #define DUK_STRIDX_CONFIGURABLE 254 /* 'configurable' */
  2684. #define DUK_STRIDX_WRITABLE 255 /* 'writable' */
  2685. #define DUK_STRIDX_VALUE 256 /* 'value' */
  2686. #define DUK_STRIDX_KEYS 257 /* 'keys' */
  2687. #define DUK_STRIDX_IS_EXTENSIBLE 258 /* 'isExtensible' */
  2688. #define DUK_STRIDX_IS_FROZEN 259 /* 'isFrozen' */
  2689. #define DUK_STRIDX_IS_SEALED 260 /* 'isSealed' */
  2690. #define DUK_STRIDX_PREVENT_EXTENSIONS 261 /* 'preventExtensions' */
  2691. #define DUK_STRIDX_FREEZE 262 /* 'freeze' */
  2692. #define DUK_STRIDX_SEAL 263 /* 'seal' */
  2693. #define DUK_STRIDX_DEFINE_PROPERTIES 264 /* 'defineProperties' */
  2694. #define DUK_STRIDX_DEFINE_PROPERTY 265 /* 'defineProperty' */
  2695. #define DUK_STRIDX_CREATE 266 /* 'create' */
  2696. #define DUK_STRIDX_GET_OWN_PROPERTY_NAMES 267 /* 'getOwnPropertyNames' */
  2697. #define DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR 268 /* 'getOwnPropertyDescriptor' */
  2698. #define DUK_STRIDX_GET_PROTOTYPE_OF 269 /* 'getPrototypeOf' */
  2699. #define DUK_STRIDX_PROTOTYPE 270 /* 'prototype' */
  2700. #define DUK_STRIDX_LENGTH 271 /* 'length' */
  2701. #define DUK_STRIDX_ALERT 272 /* 'alert' */
  2702. #define DUK_STRIDX_PRINT 273 /* 'print' */
  2703. #define DUK_STRIDX_UNESCAPE 274 /* 'unescape' */
  2704. #define DUK_STRIDX_ESCAPE 275 /* 'escape' */
  2705. #define DUK_STRIDX_ENCODE_URI_COMPONENT 276 /* 'encodeURIComponent' */
  2706. #define DUK_STRIDX_ENCODE_URI 277 /* 'encodeURI' */
  2707. #define DUK_STRIDX_DECODE_URI_COMPONENT 278 /* 'decodeURIComponent' */
  2708. #define DUK_STRIDX_DECODE_URI 279 /* 'decodeURI' */
  2709. #define DUK_STRIDX_IS_FINITE 280 /* 'isFinite' */
  2710. #define DUK_STRIDX_IS_NAN 281 /* 'isNaN' */
  2711. #define DUK_STRIDX_PARSE_FLOAT 282 /* 'parseFloat' */
  2712. #define DUK_STRIDX_PARSE_INT 283 /* 'parseInt' */
  2713. #define DUK_STRIDX_EVAL 284 /* 'eval' */
  2714. #define DUK_STRIDX_URI_ERROR 285 /* 'URIError' */
  2715. #define DUK_STRIDX_TYPE_ERROR 286 /* 'TypeError' */
  2716. #define DUK_STRIDX_SYNTAX_ERROR 287 /* 'SyntaxError' */
  2717. #define DUK_STRIDX_REFERENCE_ERROR 288 /* 'ReferenceError' */
  2718. #define DUK_STRIDX_RANGE_ERROR 289 /* 'RangeError' */
  2719. #define DUK_STRIDX_EVAL_ERROR 290 /* 'EvalError' */
  2720. #define DUK_STRIDX_BREAK 291 /* 'break' */
  2721. #define DUK_STRIDX_CASE 292 /* 'case' */
  2722. #define DUK_STRIDX_CATCH 293 /* 'catch' */
  2723. #define DUK_STRIDX_CONTINUE 294 /* 'continue' */
  2724. #define DUK_STRIDX_DEBUGGER 295 /* 'debugger' */
  2725. #define DUK_STRIDX_DEFAULT 296 /* 'default' */
  2726. #define DUK_STRIDX_DELETE 297 /* 'delete' */
  2727. #define DUK_STRIDX_DO 298 /* 'do' */
  2728. #define DUK_STRIDX_ELSE 299 /* 'else' */
  2729. #define DUK_STRIDX_FINALLY 300 /* 'finally' */
  2730. #define DUK_STRIDX_FOR 301 /* 'for' */
  2731. #define DUK_STRIDX_LC_FUNCTION 302 /* 'function' */
  2732. #define DUK_STRIDX_IF 303 /* 'if' */
  2733. #define DUK_STRIDX_IN 304 /* 'in' */
  2734. #define DUK_STRIDX_INSTANCEOF 305 /* 'instanceof' */
  2735. #define DUK_STRIDX_NEW 306 /* 'new' */
  2736. #define DUK_STRIDX_RETURN 307 /* 'return' */
  2737. #define DUK_STRIDX_SWITCH 308 /* 'switch' */
  2738. #define DUK_STRIDX_THIS 309 /* 'this' */
  2739. #define DUK_STRIDX_THROW 310 /* 'throw' */
  2740. #define DUK_STRIDX_TRY 311 /* 'try' */
  2741. #define DUK_STRIDX_TYPEOF 312 /* 'typeof' */
  2742. #define DUK_STRIDX_VAR 313 /* 'var' */
  2743. #define DUK_STRIDX_VOID 314 /* 'void' */
  2744. #define DUK_STRIDX_WHILE 315 /* 'while' */
  2745. #define DUK_STRIDX_WITH 316 /* 'with' */
  2746. #define DUK_STRIDX_CLASS 317 /* 'class' */
  2747. #define DUK_STRIDX_CONST 318 /* 'const' */
  2748. #define DUK_STRIDX_ENUM 319 /* 'enum' */
  2749. #define DUK_STRIDX_EXPORT 320 /* 'export' */
  2750. #define DUK_STRIDX_EXTENDS 321 /* 'extends' */
  2751. #define DUK_STRIDX_IMPORT 322 /* 'import' */
  2752. #define DUK_STRIDX_SUPER 323 /* 'super' */
  2753. #define DUK_STRIDX_LC_NULL 324 /* 'null' */
  2754. #define DUK_STRIDX_TRUE 325 /* 'true' */
  2755. #define DUK_STRIDX_FALSE 326 /* 'false' */
  2756. #define DUK_STRIDX_IMPLEMENTS 327 /* 'implements' */
  2757. #define DUK_STRIDX_INTERFACE 328 /* 'interface' */
  2758. #define DUK_STRIDX_LET 329 /* 'let' */
  2759. #define DUK_STRIDX_PACKAGE 330 /* 'package' */
  2760. #define DUK_STRIDX_PRIVATE 331 /* 'private' */
  2761. #define DUK_STRIDX_PROTECTED 332 /* 'protected' */
  2762. #define DUK_STRIDX_PUBLIC 333 /* 'public' */
  2763. #define DUK_STRIDX_STATIC 334 /* 'static' */
  2764. #define DUK_STRIDX_YIELD 335 /* 'yield' */
  2765. #define DUK_HEAP_STRING_UC_LOGGER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_LOGGER)
  2766. #define DUK_HTHREAD_STRING_UC_LOGGER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_LOGGER)
  2767. #define DUK_HEAP_STRING_UC_THREAD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_THREAD)
  2768. #define DUK_HTHREAD_STRING_UC_THREAD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_THREAD)
  2769. #define DUK_HEAP_STRING_UC_POINTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_POINTER)
  2770. #define DUK_HTHREAD_STRING_UC_POINTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_POINTER)
  2771. #define DUK_HEAP_STRING_UC_BUFFER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_BUFFER)
  2772. #define DUK_HTHREAD_STRING_UC_BUFFER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_BUFFER)
  2773. #define DUK_HEAP_STRING_DEC_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEC_ENV)
  2774. #define DUK_HTHREAD_STRING_DEC_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEC_ENV)
  2775. #define DUK_HEAP_STRING_OBJ_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_OBJ_ENV)
  2776. #define DUK_HTHREAD_STRING_OBJ_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_OBJ_ENV)
  2777. #define DUK_HEAP_STRING_EMPTY_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EMPTY_STRING)
  2778. #define DUK_HTHREAD_STRING_EMPTY_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EMPTY_STRING)
  2779. #define DUK_HEAP_STRING_GLOBAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GLOBAL)
  2780. #define DUK_HTHREAD_STRING_GLOBAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GLOBAL)
  2781. #define DUK_HEAP_STRING_UC_ARGUMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_ARGUMENTS)
  2782. #define DUK_HTHREAD_STRING_UC_ARGUMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_ARGUMENTS)
  2783. #define DUK_HEAP_STRING_JSON(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON)
  2784. #define DUK_HTHREAD_STRING_JSON(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON)
  2785. #define DUK_HEAP_STRING_MATH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MATH)
  2786. #define DUK_HTHREAD_STRING_MATH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MATH)
  2787. #define DUK_HEAP_STRING_UC_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_ERROR)
  2788. #define DUK_HTHREAD_STRING_UC_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_ERROR)
  2789. #define DUK_HEAP_STRING_REG_EXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REG_EXP)
  2790. #define DUK_HTHREAD_STRING_REG_EXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REG_EXP)
  2791. #define DUK_HEAP_STRING_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DATE)
  2792. #define DUK_HTHREAD_STRING_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DATE)
  2793. #define DUK_HEAP_STRING_UC_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_NUMBER)
  2794. #define DUK_HTHREAD_STRING_UC_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_NUMBER)
  2795. #define DUK_HEAP_STRING_UC_BOOLEAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_BOOLEAN)
  2796. #define DUK_HTHREAD_STRING_UC_BOOLEAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_BOOLEAN)
  2797. #define DUK_HEAP_STRING_UC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_STRING)
  2798. #define DUK_HTHREAD_STRING_UC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_STRING)
  2799. #define DUK_HEAP_STRING_ARRAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ARRAY)
  2800. #define DUK_HTHREAD_STRING_ARRAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ARRAY)
  2801. #define DUK_HEAP_STRING_UC_FUNCTION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_FUNCTION)
  2802. #define DUK_HTHREAD_STRING_UC_FUNCTION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_FUNCTION)
  2803. #define DUK_HEAP_STRING_UC_OBJECT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_OBJECT)
  2804. #define DUK_HTHREAD_STRING_UC_OBJECT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_OBJECT)
  2805. #define DUK_HEAP_STRING_UC_NULL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_NULL)
  2806. #define DUK_HTHREAD_STRING_UC_NULL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_NULL)
  2807. #define DUK_HEAP_STRING_UC_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UC_UNDEFINED)
  2808. #define DUK_HTHREAD_STRING_UC_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UC_UNDEFINED)
  2809. #define DUK_HEAP_STRING_JSON_EXT_FUNCTION2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_FUNCTION2)
  2810. #define DUK_HTHREAD_STRING_JSON_EXT_FUNCTION2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_FUNCTION2)
  2811. #define DUK_HEAP_STRING_JSON_EXT_FUNCTION1(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_FUNCTION1)
  2812. #define DUK_HTHREAD_STRING_JSON_EXT_FUNCTION1(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_FUNCTION1)
  2813. #define DUK_HEAP_STRING_JSON_EXT_NEGINF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_NEGINF)
  2814. #define DUK_HTHREAD_STRING_JSON_EXT_NEGINF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_NEGINF)
  2815. #define DUK_HEAP_STRING_JSON_EXT_POSINF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_POSINF)
  2816. #define DUK_HTHREAD_STRING_JSON_EXT_POSINF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_POSINF)
  2817. #define DUK_HEAP_STRING_JSON_EXT_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_NAN)
  2818. #define DUK_HTHREAD_STRING_JSON_EXT_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_NAN)
  2819. #define DUK_HEAP_STRING_JSON_EXT_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JSON_EXT_UNDEFINED)
  2820. #define DUK_HTHREAD_STRING_JSON_EXT_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JSON_EXT_UNDEFINED)
  2821. #define DUK_HEAP_STRING_TO_LOG_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOG_STRING)
  2822. #define DUK_HTHREAD_STRING_TO_LOG_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOG_STRING)
  2823. #define DUK_HEAP_STRING_CLOG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CLOG)
  2824. #define DUK_HTHREAD_STRING_CLOG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CLOG)
  2825. #define DUK_HEAP_STRING_LC_L(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_L)
  2826. #define DUK_HTHREAD_STRING_LC_L(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_L)
  2827. #define DUK_HEAP_STRING_LC_N(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_N)
  2828. #define DUK_HTHREAD_STRING_LC_N(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_N)
  2829. #define DUK_HEAP_STRING_LC_FATAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_FATAL)
  2830. #define DUK_HTHREAD_STRING_LC_FATAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_FATAL)
  2831. #define DUK_HEAP_STRING_LC_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_ERROR)
  2832. #define DUK_HTHREAD_STRING_LC_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_ERROR)
  2833. #define DUK_HEAP_STRING_LC_WARN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_WARN)
  2834. #define DUK_HTHREAD_STRING_LC_WARN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_WARN)
  2835. #define DUK_HEAP_STRING_LC_DEBUG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_DEBUG)
  2836. #define DUK_HTHREAD_STRING_LC_DEBUG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_DEBUG)
  2837. #define DUK_HEAP_STRING_LC_TRACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_TRACE)
  2838. #define DUK_HTHREAD_STRING_LC_TRACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_TRACE)
  2839. #define DUK_HEAP_STRING_RAW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RAW)
  2840. #define DUK_HTHREAD_STRING_RAW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RAW)
  2841. #define DUK_HEAP_STRING_FMT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FMT)
  2842. #define DUK_HTHREAD_STRING_FMT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FMT)
  2843. #define DUK_HEAP_STRING_CURRENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CURRENT)
  2844. #define DUK_HTHREAD_STRING_CURRENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CURRENT)
  2845. #define DUK_HEAP_STRING_RESUME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RESUME)
  2846. #define DUK_HTHREAD_STRING_RESUME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RESUME)
  2847. #define DUK_HEAP_STRING_COMPACT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMPACT)
  2848. #define DUK_HTHREAD_STRING_COMPACT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMPACT)
  2849. #define DUK_HEAP_STRING_JC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JC)
  2850. #define DUK_HTHREAD_STRING_JC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JC)
  2851. #define DUK_HEAP_STRING_JX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JX)
  2852. #define DUK_HTHREAD_STRING_JX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JX)
  2853. #define DUK_HEAP_STRING_BASE64(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BASE64)
  2854. #define DUK_HTHREAD_STRING_BASE64(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BASE64)
  2855. #define DUK_HEAP_STRING_HEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HEX)
  2856. #define DUK_HTHREAD_STRING_HEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HEX)
  2857. #define DUK_HEAP_STRING_DEC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEC)
  2858. #define DUK_HTHREAD_STRING_DEC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEC)
  2859. #define DUK_HEAP_STRING_ENC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENC)
  2860. #define DUK_HTHREAD_STRING_ENC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENC)
  2861. #define DUK_HEAP_STRING_FIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FIN)
  2862. #define DUK_HTHREAD_STRING_FIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FIN)
  2863. #define DUK_HEAP_STRING_GC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GC)
  2864. #define DUK_HTHREAD_STRING_GC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GC)
  2865. #define DUK_HEAP_STRING_ACT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ACT)
  2866. #define DUK_HTHREAD_STRING_ACT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ACT)
  2867. #define DUK_HEAP_STRING_LC_INFO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_INFO)
  2868. #define DUK_HTHREAD_STRING_LC_INFO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_INFO)
  2869. #define DUK_HEAP_STRING_VERSION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VERSION)
  2870. #define DUK_HTHREAD_STRING_VERSION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VERSION)
  2871. #define DUK_HEAP_STRING_ENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENV)
  2872. #define DUK_HTHREAD_STRING_ENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENV)
  2873. #define DUK_HEAP_STRING_MOD_LOADED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MOD_LOADED)
  2874. #define DUK_HTHREAD_STRING_MOD_LOADED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MOD_LOADED)
  2875. #define DUK_HEAP_STRING_MOD_SEARCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MOD_SEARCH)
  2876. #define DUK_HTHREAD_STRING_MOD_SEARCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MOD_SEARCH)
  2877. #define DUK_HEAP_STRING_ERR_THROW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ERR_THROW)
  2878. #define DUK_HTHREAD_STRING_ERR_THROW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ERR_THROW)
  2879. #define DUK_HEAP_STRING_ERR_CREATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ERR_CREATE)
  2880. #define DUK_HTHREAD_STRING_ERR_CREATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ERR_CREATE)
  2881. #define DUK_HEAP_STRING_COMPILE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMPILE)
  2882. #define DUK_HTHREAD_STRING_COMPILE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMPILE)
  2883. #define DUK_HEAP_STRING_INT_REGBASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_REGBASE)
  2884. #define DUK_HTHREAD_STRING_INT_REGBASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_REGBASE)
  2885. #define DUK_HEAP_STRING_INT_THREAD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_THREAD)
  2886. #define DUK_HTHREAD_STRING_INT_THREAD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_THREAD)
  2887. #define DUK_HEAP_STRING_INT_HANDLER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_HANDLER)
  2888. #define DUK_HTHREAD_STRING_INT_HANDLER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_HANDLER)
  2889. #define DUK_HEAP_STRING_INT_FINALIZER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_FINALIZER)
  2890. #define DUK_HTHREAD_STRING_INT_FINALIZER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_FINALIZER)
  2891. #define DUK_HEAP_STRING_INT_CALLEE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_CALLEE)
  2892. #define DUK_HTHREAD_STRING_INT_CALLEE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_CALLEE)
  2893. #define DUK_HEAP_STRING_INT_MAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_MAP)
  2894. #define DUK_HTHREAD_STRING_INT_MAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_MAP)
  2895. #define DUK_HEAP_STRING_INT_ARGS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_ARGS)
  2896. #define DUK_HTHREAD_STRING_INT_ARGS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_ARGS)
  2897. #define DUK_HEAP_STRING_INT_THIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_THIS)
  2898. #define DUK_HTHREAD_STRING_INT_THIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_THIS)
  2899. #define DUK_HEAP_STRING_INT_PC2LINE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_PC2LINE)
  2900. #define DUK_HTHREAD_STRING_INT_PC2LINE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_PC2LINE)
  2901. #define DUK_HEAP_STRING_INT_SOURCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_SOURCE)
  2902. #define DUK_HTHREAD_STRING_INT_SOURCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_SOURCE)
  2903. #define DUK_HEAP_STRING_INT_VARENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VARENV)
  2904. #define DUK_HTHREAD_STRING_INT_VARENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VARENV)
  2905. #define DUK_HEAP_STRING_INT_LEXENV(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_LEXENV)
  2906. #define DUK_HTHREAD_STRING_INT_LEXENV(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_LEXENV)
  2907. #define DUK_HEAP_STRING_INT_VARMAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VARMAP)
  2908. #define DUK_HTHREAD_STRING_INT_VARMAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VARMAP)
  2909. #define DUK_HEAP_STRING_INT_FORMALS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_FORMALS)
  2910. #define DUK_HTHREAD_STRING_INT_FORMALS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_FORMALS)
  2911. #define DUK_HEAP_STRING_INT_BYTECODE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_BYTECODE)
  2912. #define DUK_HTHREAD_STRING_INT_BYTECODE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_BYTECODE)
  2913. #define DUK_HEAP_STRING_INT_NEXT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_NEXT)
  2914. #define DUK_HTHREAD_STRING_INT_NEXT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_NEXT)
  2915. #define DUK_HEAP_STRING_INT_TARGET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_TARGET)
  2916. #define DUK_HTHREAD_STRING_INT_TARGET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_TARGET)
  2917. #define DUK_HEAP_STRING_INT_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_VALUE)
  2918. #define DUK_HTHREAD_STRING_INT_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_VALUE)
  2919. #define DUK_HEAP_STRING_LC_POINTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_POINTER)
  2920. #define DUK_HTHREAD_STRING_LC_POINTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_POINTER)
  2921. #define DUK_HEAP_STRING_LC_BUFFER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_BUFFER)
  2922. #define DUK_HTHREAD_STRING_LC_BUFFER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_BUFFER)
  2923. #define DUK_HEAP_STRING_INT_TRACEDATA(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INT_TRACEDATA)
  2924. #define DUK_HTHREAD_STRING_INT_TRACEDATA(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INT_TRACEDATA)
  2925. #define DUK_HEAP_STRING_LINE_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LINE_NUMBER)
  2926. #define DUK_HTHREAD_STRING_LINE_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LINE_NUMBER)
  2927. #define DUK_HEAP_STRING_FILE_NAME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FILE_NAME)
  2928. #define DUK_HTHREAD_STRING_FILE_NAME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FILE_NAME)
  2929. #define DUK_HEAP_STRING_PC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PC)
  2930. #define DUK_HTHREAD_STRING_PC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PC)
  2931. #define DUK_HEAP_STRING_STACK(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STACK)
  2932. #define DUK_HTHREAD_STRING_STACK(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STACK)
  2933. #define DUK_HEAP_STRING_THROW_TYPE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THROW_TYPE_ERROR)
  2934. #define DUK_HTHREAD_STRING_THROW_TYPE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THROW_TYPE_ERROR)
  2935. #define DUK_HEAP_STRING_DUKTAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DUKTAPE)
  2936. #define DUK_HTHREAD_STRING_DUKTAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DUKTAPE)
  2937. #define DUK_HEAP_STRING_ID(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ID)
  2938. #define DUK_HTHREAD_STRING_ID(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ID)
  2939. #define DUK_HEAP_STRING_REQUIRE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REQUIRE)
  2940. #define DUK_HTHREAD_STRING_REQUIRE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REQUIRE)
  2941. #define DUK_HEAP_STRING___PROTO__(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX___PROTO__)
  2942. #define DUK_HTHREAD_STRING___PROTO__(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX___PROTO__)
  2943. #define DUK_HEAP_STRING_SET_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_PROTOTYPE_OF)
  2944. #define DUK_HTHREAD_STRING_SET_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_PROTOTYPE_OF)
  2945. #define DUK_HEAP_STRING_OWN_KEYS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_OWN_KEYS)
  2946. #define DUK_HTHREAD_STRING_OWN_KEYS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_OWN_KEYS)
  2947. #define DUK_HEAP_STRING_ENUMERATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUMERATE)
  2948. #define DUK_HTHREAD_STRING_ENUMERATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUMERATE)
  2949. #define DUK_HEAP_STRING_DELETE_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DELETE_PROPERTY)
  2950. #define DUK_HTHREAD_STRING_DELETE_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DELETE_PROPERTY)
  2951. #define DUK_HEAP_STRING_HAS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HAS)
  2952. #define DUK_HTHREAD_STRING_HAS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HAS)
  2953. #define DUK_HEAP_STRING_PROXY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROXY)
  2954. #define DUK_HTHREAD_STRING_PROXY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROXY)
  2955. #define DUK_HEAP_STRING_CALLEE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALLEE)
  2956. #define DUK_HTHREAD_STRING_CALLEE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALLEE)
  2957. #define DUK_HEAP_STRING_INVALID_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INVALID_DATE)
  2958. #define DUK_HTHREAD_STRING_INVALID_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INVALID_DATE)
  2959. #define DUK_HEAP_STRING_BRACKETED_ELLIPSIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BRACKETED_ELLIPSIS)
  2960. #define DUK_HTHREAD_STRING_BRACKETED_ELLIPSIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BRACKETED_ELLIPSIS)
  2961. #define DUK_HEAP_STRING_NEWLINE_TAB(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEWLINE_TAB)
  2962. #define DUK_HTHREAD_STRING_NEWLINE_TAB(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEWLINE_TAB)
  2963. #define DUK_HEAP_STRING_SPACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPACE)
  2964. #define DUK_HTHREAD_STRING_SPACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPACE)
  2965. #define DUK_HEAP_STRING_COMMA(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COMMA)
  2966. #define DUK_HTHREAD_STRING_COMMA(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COMMA)
  2967. #define DUK_HEAP_STRING_MINUS_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MINUS_ZERO)
  2968. #define DUK_HTHREAD_STRING_MINUS_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MINUS_ZERO)
  2969. #define DUK_HEAP_STRING_PLUS_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PLUS_ZERO)
  2970. #define DUK_HTHREAD_STRING_PLUS_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PLUS_ZERO)
  2971. #define DUK_HEAP_STRING_ZERO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ZERO)
  2972. #define DUK_HTHREAD_STRING_ZERO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ZERO)
  2973. #define DUK_HEAP_STRING_MINUS_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MINUS_INFINITY)
  2974. #define DUK_HTHREAD_STRING_MINUS_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MINUS_INFINITY)
  2975. #define DUK_HEAP_STRING_PLUS_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PLUS_INFINITY)
  2976. #define DUK_HTHREAD_STRING_PLUS_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PLUS_INFINITY)
  2977. #define DUK_HEAP_STRING_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INFINITY)
  2978. #define DUK_HTHREAD_STRING_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INFINITY)
  2979. #define DUK_HEAP_STRING_LC_OBJECT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_OBJECT)
  2980. #define DUK_HTHREAD_STRING_LC_OBJECT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_OBJECT)
  2981. #define DUK_HEAP_STRING_LC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_STRING)
  2982. #define DUK_HTHREAD_STRING_LC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_STRING)
  2983. #define DUK_HEAP_STRING_LC_NUMBER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_NUMBER)
  2984. #define DUK_HTHREAD_STRING_LC_NUMBER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_NUMBER)
  2985. #define DUK_HEAP_STRING_LC_BOOLEAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_BOOLEAN)
  2986. #define DUK_HTHREAD_STRING_LC_BOOLEAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_BOOLEAN)
  2987. #define DUK_HEAP_STRING_LC_UNDEFINED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_UNDEFINED)
  2988. #define DUK_HTHREAD_STRING_LC_UNDEFINED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_UNDEFINED)
  2989. #define DUK_HEAP_STRING_STRINGIFY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STRINGIFY)
  2990. #define DUK_HTHREAD_STRING_STRINGIFY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STRINGIFY)
  2991. #define DUK_HEAP_STRING_TAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TAN)
  2992. #define DUK_HTHREAD_STRING_TAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TAN)
  2993. #define DUK_HEAP_STRING_SQRT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT)
  2994. #define DUK_HTHREAD_STRING_SQRT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT)
  2995. #define DUK_HEAP_STRING_SIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SIN)
  2996. #define DUK_HTHREAD_STRING_SIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SIN)
  2997. #define DUK_HEAP_STRING_ROUND(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ROUND)
  2998. #define DUK_HTHREAD_STRING_ROUND(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ROUND)
  2999. #define DUK_HEAP_STRING_RANDOM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RANDOM)
  3000. #define DUK_HTHREAD_STRING_RANDOM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RANDOM)
  3001. #define DUK_HEAP_STRING_POW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POW)
  3002. #define DUK_HTHREAD_STRING_POW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POW)
  3003. #define DUK_HEAP_STRING_MIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MIN)
  3004. #define DUK_HTHREAD_STRING_MIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MIN)
  3005. #define DUK_HEAP_STRING_MAX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAX)
  3006. #define DUK_HTHREAD_STRING_MAX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAX)
  3007. #define DUK_HEAP_STRING_LOG(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG)
  3008. #define DUK_HTHREAD_STRING_LOG(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG)
  3009. #define DUK_HEAP_STRING_FLOOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FLOOR)
  3010. #define DUK_HTHREAD_STRING_FLOOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FLOOR)
  3011. #define DUK_HEAP_STRING_EXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXP)
  3012. #define DUK_HTHREAD_STRING_EXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXP)
  3013. #define DUK_HEAP_STRING_COS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_COS)
  3014. #define DUK_HTHREAD_STRING_COS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_COS)
  3015. #define DUK_HEAP_STRING_CEIL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CEIL)
  3016. #define DUK_HTHREAD_STRING_CEIL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CEIL)
  3017. #define DUK_HEAP_STRING_ATAN2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ATAN2)
  3018. #define DUK_HTHREAD_STRING_ATAN2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ATAN2)
  3019. #define DUK_HEAP_STRING_ATAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ATAN)
  3020. #define DUK_HTHREAD_STRING_ATAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ATAN)
  3021. #define DUK_HEAP_STRING_ASIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ASIN)
  3022. #define DUK_HTHREAD_STRING_ASIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ASIN)
  3023. #define DUK_HEAP_STRING_ACOS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ACOS)
  3024. #define DUK_HTHREAD_STRING_ACOS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ACOS)
  3025. #define DUK_HEAP_STRING_ABS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ABS)
  3026. #define DUK_HTHREAD_STRING_ABS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ABS)
  3027. #define DUK_HEAP_STRING_SQRT2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT2)
  3028. #define DUK_HTHREAD_STRING_SQRT2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT2)
  3029. #define DUK_HEAP_STRING_SQRT1_2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SQRT1_2)
  3030. #define DUK_HTHREAD_STRING_SQRT1_2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SQRT1_2)
  3031. #define DUK_HEAP_STRING_PI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PI)
  3032. #define DUK_HTHREAD_STRING_PI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PI)
  3033. #define DUK_HEAP_STRING_LOG10E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG10E)
  3034. #define DUK_HTHREAD_STRING_LOG10E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG10E)
  3035. #define DUK_HEAP_STRING_LOG2E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOG2E)
  3036. #define DUK_HTHREAD_STRING_LOG2E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOG2E)
  3037. #define DUK_HEAP_STRING_LN2(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LN2)
  3038. #define DUK_HTHREAD_STRING_LN2(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LN2)
  3039. #define DUK_HEAP_STRING_LN10(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LN10)
  3040. #define DUK_HTHREAD_STRING_LN10(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LN10)
  3041. #define DUK_HEAP_STRING_E(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_E)
  3042. #define DUK_HTHREAD_STRING_E(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_E)
  3043. #define DUK_HEAP_STRING_MESSAGE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MESSAGE)
  3044. #define DUK_HTHREAD_STRING_MESSAGE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MESSAGE)
  3045. #define DUK_HEAP_STRING_NAME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NAME)
  3046. #define DUK_HTHREAD_STRING_NAME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NAME)
  3047. #define DUK_HEAP_STRING_INPUT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INPUT)
  3048. #define DUK_HTHREAD_STRING_INPUT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INPUT)
  3049. #define DUK_HEAP_STRING_INDEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INDEX)
  3050. #define DUK_HTHREAD_STRING_INDEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INDEX)
  3051. #define DUK_HEAP_STRING_ESCAPED_EMPTY_REGEXP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ESCAPED_EMPTY_REGEXP)
  3052. #define DUK_HTHREAD_STRING_ESCAPED_EMPTY_REGEXP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ESCAPED_EMPTY_REGEXP)
  3053. #define DUK_HEAP_STRING_LAST_INDEX(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LAST_INDEX)
  3054. #define DUK_HTHREAD_STRING_LAST_INDEX(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LAST_INDEX)
  3055. #define DUK_HEAP_STRING_MULTILINE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MULTILINE)
  3056. #define DUK_HTHREAD_STRING_MULTILINE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MULTILINE)
  3057. #define DUK_HEAP_STRING_IGNORE_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IGNORE_CASE)
  3058. #define DUK_HTHREAD_STRING_IGNORE_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IGNORE_CASE)
  3059. #define DUK_HEAP_STRING_SOURCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SOURCE)
  3060. #define DUK_HTHREAD_STRING_SOURCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SOURCE)
  3061. #define DUK_HEAP_STRING_TEST(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TEST)
  3062. #define DUK_HTHREAD_STRING_TEST(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TEST)
  3063. #define DUK_HEAP_STRING_EXEC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXEC)
  3064. #define DUK_HTHREAD_STRING_EXEC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXEC)
  3065. #define DUK_HEAP_STRING_TO_GMT_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_GMT_STRING)
  3066. #define DUK_HTHREAD_STRING_TO_GMT_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_GMT_STRING)
  3067. #define DUK_HEAP_STRING_SET_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_YEAR)
  3068. #define DUK_HTHREAD_STRING_SET_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_YEAR)
  3069. #define DUK_HEAP_STRING_GET_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_YEAR)
  3070. #define DUK_HTHREAD_STRING_GET_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_YEAR)
  3071. #define DUK_HEAP_STRING_TO_JSON(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_JSON)
  3072. #define DUK_HTHREAD_STRING_TO_JSON(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_JSON)
  3073. #define DUK_HEAP_STRING_TO_ISO_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_ISO_STRING)
  3074. #define DUK_HTHREAD_STRING_TO_ISO_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_ISO_STRING)
  3075. #define DUK_HEAP_STRING_TO_UTC_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_UTC_STRING)
  3076. #define DUK_HTHREAD_STRING_TO_UTC_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_UTC_STRING)
  3077. #define DUK_HEAP_STRING_SET_UTC_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_FULL_YEAR)
  3078. #define DUK_HTHREAD_STRING_SET_UTC_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_FULL_YEAR)
  3079. #define DUK_HEAP_STRING_SET_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_FULL_YEAR)
  3080. #define DUK_HTHREAD_STRING_SET_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_FULL_YEAR)
  3081. #define DUK_HEAP_STRING_SET_UTC_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MONTH)
  3082. #define DUK_HTHREAD_STRING_SET_UTC_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MONTH)
  3083. #define DUK_HEAP_STRING_SET_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MONTH)
  3084. #define DUK_HTHREAD_STRING_SET_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MONTH)
  3085. #define DUK_HEAP_STRING_SET_UTC_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_DATE)
  3086. #define DUK_HTHREAD_STRING_SET_UTC_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_DATE)
  3087. #define DUK_HEAP_STRING_SET_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_DATE)
  3088. #define DUK_HTHREAD_STRING_SET_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_DATE)
  3089. #define DUK_HEAP_STRING_SET_UTC_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_HOURS)
  3090. #define DUK_HTHREAD_STRING_SET_UTC_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_HOURS)
  3091. #define DUK_HEAP_STRING_SET_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_HOURS)
  3092. #define DUK_HTHREAD_STRING_SET_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_HOURS)
  3093. #define DUK_HEAP_STRING_SET_UTC_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MINUTES)
  3094. #define DUK_HTHREAD_STRING_SET_UTC_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MINUTES)
  3095. #define DUK_HEAP_STRING_SET_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MINUTES)
  3096. #define DUK_HTHREAD_STRING_SET_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MINUTES)
  3097. #define DUK_HEAP_STRING_SET_UTC_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_SECONDS)
  3098. #define DUK_HTHREAD_STRING_SET_UTC_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_SECONDS)
  3099. #define DUK_HEAP_STRING_SET_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_SECONDS)
  3100. #define DUK_HTHREAD_STRING_SET_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_SECONDS)
  3101. #define DUK_HEAP_STRING_SET_UTC_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_UTC_MILLISECONDS)
  3102. #define DUK_HTHREAD_STRING_SET_UTC_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_UTC_MILLISECONDS)
  3103. #define DUK_HEAP_STRING_SET_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_MILLISECONDS)
  3104. #define DUK_HTHREAD_STRING_SET_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_MILLISECONDS)
  3105. #define DUK_HEAP_STRING_SET_TIME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET_TIME)
  3106. #define DUK_HTHREAD_STRING_SET_TIME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET_TIME)
  3107. #define DUK_HEAP_STRING_GET_TIMEZONE_OFFSET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_TIMEZONE_OFFSET)
  3108. #define DUK_HTHREAD_STRING_GET_TIMEZONE_OFFSET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_TIMEZONE_OFFSET)
  3109. #define DUK_HEAP_STRING_GET_UTC_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MILLISECONDS)
  3110. #define DUK_HTHREAD_STRING_GET_UTC_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MILLISECONDS)
  3111. #define DUK_HEAP_STRING_GET_MILLISECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MILLISECONDS)
  3112. #define DUK_HTHREAD_STRING_GET_MILLISECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MILLISECONDS)
  3113. #define DUK_HEAP_STRING_GET_UTC_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_SECONDS)
  3114. #define DUK_HTHREAD_STRING_GET_UTC_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_SECONDS)
  3115. #define DUK_HEAP_STRING_GET_SECONDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_SECONDS)
  3116. #define DUK_HTHREAD_STRING_GET_SECONDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_SECONDS)
  3117. #define DUK_HEAP_STRING_GET_UTC_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MINUTES)
  3118. #define DUK_HTHREAD_STRING_GET_UTC_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MINUTES)
  3119. #define DUK_HEAP_STRING_GET_MINUTES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MINUTES)
  3120. #define DUK_HTHREAD_STRING_GET_MINUTES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MINUTES)
  3121. #define DUK_HEAP_STRING_GET_UTC_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_HOURS)
  3122. #define DUK_HTHREAD_STRING_GET_UTC_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_HOURS)
  3123. #define DUK_HEAP_STRING_GET_HOURS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_HOURS)
  3124. #define DUK_HTHREAD_STRING_GET_HOURS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_HOURS)
  3125. #define DUK_HEAP_STRING_GET_UTC_DAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_DAY)
  3126. #define DUK_HTHREAD_STRING_GET_UTC_DAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_DAY)
  3127. #define DUK_HEAP_STRING_GET_DAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_DAY)
  3128. #define DUK_HTHREAD_STRING_GET_DAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_DAY)
  3129. #define DUK_HEAP_STRING_GET_UTC_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_DATE)
  3130. #define DUK_HTHREAD_STRING_GET_UTC_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_DATE)
  3131. #define DUK_HEAP_STRING_GET_DATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_DATE)
  3132. #define DUK_HTHREAD_STRING_GET_DATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_DATE)
  3133. #define DUK_HEAP_STRING_GET_UTC_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_MONTH)
  3134. #define DUK_HTHREAD_STRING_GET_UTC_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_MONTH)
  3135. #define DUK_HEAP_STRING_GET_MONTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_MONTH)
  3136. #define DUK_HTHREAD_STRING_GET_MONTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_MONTH)
  3137. #define DUK_HEAP_STRING_GET_UTC_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_UTC_FULL_YEAR)
  3138. #define DUK_HTHREAD_STRING_GET_UTC_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_UTC_FULL_YEAR)
  3139. #define DUK_HEAP_STRING_GET_FULL_YEAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_FULL_YEAR)
  3140. #define DUK_HTHREAD_STRING_GET_FULL_YEAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_FULL_YEAR)
  3141. #define DUK_HEAP_STRING_GET_TIME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_TIME)
  3142. #define DUK_HTHREAD_STRING_GET_TIME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_TIME)
  3143. #define DUK_HEAP_STRING_TO_LOCALE_TIME_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_TIME_STRING)
  3144. #define DUK_HTHREAD_STRING_TO_LOCALE_TIME_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_TIME_STRING)
  3145. #define DUK_HEAP_STRING_TO_LOCALE_DATE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_DATE_STRING)
  3146. #define DUK_HTHREAD_STRING_TO_LOCALE_DATE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_DATE_STRING)
  3147. #define DUK_HEAP_STRING_TO_TIME_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_TIME_STRING)
  3148. #define DUK_HTHREAD_STRING_TO_TIME_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_TIME_STRING)
  3149. #define DUK_HEAP_STRING_TO_DATE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_DATE_STRING)
  3150. #define DUK_HTHREAD_STRING_TO_DATE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_DATE_STRING)
  3151. #define DUK_HEAP_STRING_NOW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NOW)
  3152. #define DUK_HTHREAD_STRING_NOW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NOW)
  3153. #define DUK_HEAP_STRING_UTC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UTC)
  3154. #define DUK_HTHREAD_STRING_UTC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UTC)
  3155. #define DUK_HEAP_STRING_PARSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE)
  3156. #define DUK_HTHREAD_STRING_PARSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE)
  3157. #define DUK_HEAP_STRING_TO_PRECISION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_PRECISION)
  3158. #define DUK_HTHREAD_STRING_TO_PRECISION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_PRECISION)
  3159. #define DUK_HEAP_STRING_TO_EXPONENTIAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_EXPONENTIAL)
  3160. #define DUK_HTHREAD_STRING_TO_EXPONENTIAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_EXPONENTIAL)
  3161. #define DUK_HEAP_STRING_TO_FIXED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_FIXED)
  3162. #define DUK_HTHREAD_STRING_TO_FIXED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_FIXED)
  3163. #define DUK_HEAP_STRING_POSITIVE_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POSITIVE_INFINITY)
  3164. #define DUK_HTHREAD_STRING_POSITIVE_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POSITIVE_INFINITY)
  3165. #define DUK_HEAP_STRING_NEGATIVE_INFINITY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEGATIVE_INFINITY)
  3166. #define DUK_HTHREAD_STRING_NEGATIVE_INFINITY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEGATIVE_INFINITY)
  3167. #define DUK_HEAP_STRING_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NAN)
  3168. #define DUK_HTHREAD_STRING_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NAN)
  3169. #define DUK_HEAP_STRING_MIN_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MIN_VALUE)
  3170. #define DUK_HTHREAD_STRING_MIN_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MIN_VALUE)
  3171. #define DUK_HEAP_STRING_MAX_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAX_VALUE)
  3172. #define DUK_HTHREAD_STRING_MAX_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAX_VALUE)
  3173. #define DUK_HEAP_STRING_SUBSTR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUBSTR)
  3174. #define DUK_HTHREAD_STRING_SUBSTR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUBSTR)
  3175. #define DUK_HEAP_STRING_TRIM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRIM)
  3176. #define DUK_HTHREAD_STRING_TRIM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRIM)
  3177. #define DUK_HEAP_STRING_TO_LOCALE_UPPER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_UPPER_CASE)
  3178. #define DUK_HTHREAD_STRING_TO_LOCALE_UPPER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_UPPER_CASE)
  3179. #define DUK_HEAP_STRING_TO_UPPER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_UPPER_CASE)
  3180. #define DUK_HTHREAD_STRING_TO_UPPER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_UPPER_CASE)
  3181. #define DUK_HEAP_STRING_TO_LOCALE_LOWER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_LOWER_CASE)
  3182. #define DUK_HTHREAD_STRING_TO_LOCALE_LOWER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_LOWER_CASE)
  3183. #define DUK_HEAP_STRING_TO_LOWER_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOWER_CASE)
  3184. #define DUK_HTHREAD_STRING_TO_LOWER_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOWER_CASE)
  3185. #define DUK_HEAP_STRING_SUBSTRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUBSTRING)
  3186. #define DUK_HTHREAD_STRING_SUBSTRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUBSTRING)
  3187. #define DUK_HEAP_STRING_SPLIT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPLIT)
  3188. #define DUK_HTHREAD_STRING_SPLIT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPLIT)
  3189. #define DUK_HEAP_STRING_SEARCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SEARCH)
  3190. #define DUK_HTHREAD_STRING_SEARCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SEARCH)
  3191. #define DUK_HEAP_STRING_REPLACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REPLACE)
  3192. #define DUK_HTHREAD_STRING_REPLACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REPLACE)
  3193. #define DUK_HEAP_STRING_MATCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MATCH)
  3194. #define DUK_HTHREAD_STRING_MATCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MATCH)
  3195. #define DUK_HEAP_STRING_LOCALE_COMPARE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LOCALE_COMPARE)
  3196. #define DUK_HTHREAD_STRING_LOCALE_COMPARE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LOCALE_COMPARE)
  3197. #define DUK_HEAP_STRING_CHAR_CODE_AT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CHAR_CODE_AT)
  3198. #define DUK_HTHREAD_STRING_CHAR_CODE_AT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CHAR_CODE_AT)
  3199. #define DUK_HEAP_STRING_CHAR_AT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CHAR_AT)
  3200. #define DUK_HTHREAD_STRING_CHAR_AT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CHAR_AT)
  3201. #define DUK_HEAP_STRING_FROM_CHAR_CODE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FROM_CHAR_CODE)
  3202. #define DUK_HTHREAD_STRING_FROM_CHAR_CODE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FROM_CHAR_CODE)
  3203. #define DUK_HEAP_STRING_REDUCE_RIGHT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REDUCE_RIGHT)
  3204. #define DUK_HTHREAD_STRING_REDUCE_RIGHT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REDUCE_RIGHT)
  3205. #define DUK_HEAP_STRING_REDUCE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REDUCE)
  3206. #define DUK_HTHREAD_STRING_REDUCE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REDUCE)
  3207. #define DUK_HEAP_STRING_FILTER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FILTER)
  3208. #define DUK_HTHREAD_STRING_FILTER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FILTER)
  3209. #define DUK_HEAP_STRING_MAP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_MAP)
  3210. #define DUK_HTHREAD_STRING_MAP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_MAP)
  3211. #define DUK_HEAP_STRING_FOR_EACH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FOR_EACH)
  3212. #define DUK_HTHREAD_STRING_FOR_EACH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FOR_EACH)
  3213. #define DUK_HEAP_STRING_SOME(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SOME)
  3214. #define DUK_HTHREAD_STRING_SOME(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SOME)
  3215. #define DUK_HEAP_STRING_EVERY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVERY)
  3216. #define DUK_HTHREAD_STRING_EVERY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVERY)
  3217. #define DUK_HEAP_STRING_LAST_INDEX_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LAST_INDEX_OF)
  3218. #define DUK_HTHREAD_STRING_LAST_INDEX_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LAST_INDEX_OF)
  3219. #define DUK_HEAP_STRING_INDEX_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INDEX_OF)
  3220. #define DUK_HTHREAD_STRING_INDEX_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INDEX_OF)
  3221. #define DUK_HEAP_STRING_UNSHIFT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UNSHIFT)
  3222. #define DUK_HTHREAD_STRING_UNSHIFT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UNSHIFT)
  3223. #define DUK_HEAP_STRING_SPLICE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SPLICE)
  3224. #define DUK_HTHREAD_STRING_SPLICE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SPLICE)
  3225. #define DUK_HEAP_STRING_SORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SORT)
  3226. #define DUK_HTHREAD_STRING_SORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SORT)
  3227. #define DUK_HEAP_STRING_SLICE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SLICE)
  3228. #define DUK_HTHREAD_STRING_SLICE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SLICE)
  3229. #define DUK_HEAP_STRING_SHIFT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SHIFT)
  3230. #define DUK_HTHREAD_STRING_SHIFT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SHIFT)
  3231. #define DUK_HEAP_STRING_REVERSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REVERSE)
  3232. #define DUK_HTHREAD_STRING_REVERSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REVERSE)
  3233. #define DUK_HEAP_STRING_PUSH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PUSH)
  3234. #define DUK_HTHREAD_STRING_PUSH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PUSH)
  3235. #define DUK_HEAP_STRING_POP(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_POP)
  3236. #define DUK_HTHREAD_STRING_POP(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_POP)
  3237. #define DUK_HEAP_STRING_JOIN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_JOIN)
  3238. #define DUK_HTHREAD_STRING_JOIN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_JOIN)
  3239. #define DUK_HEAP_STRING_CONCAT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONCAT)
  3240. #define DUK_HTHREAD_STRING_CONCAT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONCAT)
  3241. #define DUK_HEAP_STRING_IS_ARRAY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_ARRAY)
  3242. #define DUK_HTHREAD_STRING_IS_ARRAY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_ARRAY)
  3243. #define DUK_HEAP_STRING_LC_ARGUMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_ARGUMENTS)
  3244. #define DUK_HTHREAD_STRING_LC_ARGUMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_ARGUMENTS)
  3245. #define DUK_HEAP_STRING_CALLER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALLER)
  3246. #define DUK_HTHREAD_STRING_CALLER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALLER)
  3247. #define DUK_HEAP_STRING_BIND(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BIND)
  3248. #define DUK_HTHREAD_STRING_BIND(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BIND)
  3249. #define DUK_HEAP_STRING_CALL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CALL)
  3250. #define DUK_HTHREAD_STRING_CALL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CALL)
  3251. #define DUK_HEAP_STRING_APPLY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_APPLY)
  3252. #define DUK_HTHREAD_STRING_APPLY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_APPLY)
  3253. #define DUK_HEAP_STRING_PROPERTY_IS_ENUMERABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROPERTY_IS_ENUMERABLE)
  3254. #define DUK_HTHREAD_STRING_PROPERTY_IS_ENUMERABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROPERTY_IS_ENUMERABLE)
  3255. #define DUK_HEAP_STRING_IS_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_PROTOTYPE_OF)
  3256. #define DUK_HTHREAD_STRING_IS_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_PROTOTYPE_OF)
  3257. #define DUK_HEAP_STRING_HAS_OWN_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_HAS_OWN_PROPERTY)
  3258. #define DUK_HTHREAD_STRING_HAS_OWN_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_HAS_OWN_PROPERTY)
  3259. #define DUK_HEAP_STRING_VALUE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VALUE_OF)
  3260. #define DUK_HTHREAD_STRING_VALUE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VALUE_OF)
  3261. #define DUK_HEAP_STRING_TO_LOCALE_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_LOCALE_STRING)
  3262. #define DUK_HTHREAD_STRING_TO_LOCALE_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_LOCALE_STRING)
  3263. #define DUK_HEAP_STRING_TO_STRING(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TO_STRING)
  3264. #define DUK_HTHREAD_STRING_TO_STRING(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TO_STRING)
  3265. #define DUK_HEAP_STRING_CONSTRUCTOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONSTRUCTOR)
  3266. #define DUK_HTHREAD_STRING_CONSTRUCTOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONSTRUCTOR)
  3267. #define DUK_HEAP_STRING_SET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SET)
  3268. #define DUK_HTHREAD_STRING_SET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SET)
  3269. #define DUK_HEAP_STRING_GET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET)
  3270. #define DUK_HTHREAD_STRING_GET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET)
  3271. #define DUK_HEAP_STRING_ENUMERABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUMERABLE)
  3272. #define DUK_HTHREAD_STRING_ENUMERABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUMERABLE)
  3273. #define DUK_HEAP_STRING_CONFIGURABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONFIGURABLE)
  3274. #define DUK_HTHREAD_STRING_CONFIGURABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONFIGURABLE)
  3275. #define DUK_HEAP_STRING_WRITABLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WRITABLE)
  3276. #define DUK_HTHREAD_STRING_WRITABLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WRITABLE)
  3277. #define DUK_HEAP_STRING_VALUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VALUE)
  3278. #define DUK_HTHREAD_STRING_VALUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VALUE)
  3279. #define DUK_HEAP_STRING_KEYS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_KEYS)
  3280. #define DUK_HTHREAD_STRING_KEYS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_KEYS)
  3281. #define DUK_HEAP_STRING_IS_EXTENSIBLE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_EXTENSIBLE)
  3282. #define DUK_HTHREAD_STRING_IS_EXTENSIBLE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_EXTENSIBLE)
  3283. #define DUK_HEAP_STRING_IS_FROZEN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_FROZEN)
  3284. #define DUK_HTHREAD_STRING_IS_FROZEN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_FROZEN)
  3285. #define DUK_HEAP_STRING_IS_SEALED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_SEALED)
  3286. #define DUK_HTHREAD_STRING_IS_SEALED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_SEALED)
  3287. #define DUK_HEAP_STRING_PREVENT_EXTENSIONS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PREVENT_EXTENSIONS)
  3288. #define DUK_HTHREAD_STRING_PREVENT_EXTENSIONS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PREVENT_EXTENSIONS)
  3289. #define DUK_HEAP_STRING_FREEZE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FREEZE)
  3290. #define DUK_HTHREAD_STRING_FREEZE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FREEZE)
  3291. #define DUK_HEAP_STRING_SEAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SEAL)
  3292. #define DUK_HTHREAD_STRING_SEAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SEAL)
  3293. #define DUK_HEAP_STRING_DEFINE_PROPERTIES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFINE_PROPERTIES)
  3294. #define DUK_HTHREAD_STRING_DEFINE_PROPERTIES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFINE_PROPERTIES)
  3295. #define DUK_HEAP_STRING_DEFINE_PROPERTY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFINE_PROPERTY)
  3296. #define DUK_HTHREAD_STRING_DEFINE_PROPERTY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFINE_PROPERTY)
  3297. #define DUK_HEAP_STRING_CREATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CREATE)
  3298. #define DUK_HTHREAD_STRING_CREATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CREATE)
  3299. #define DUK_HEAP_STRING_GET_OWN_PROPERTY_NAMES(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_OWN_PROPERTY_NAMES)
  3300. #define DUK_HTHREAD_STRING_GET_OWN_PROPERTY_NAMES(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_OWN_PROPERTY_NAMES)
  3301. #define DUK_HEAP_STRING_GET_OWN_PROPERTY_DESCRIPTOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR)
  3302. #define DUK_HTHREAD_STRING_GET_OWN_PROPERTY_DESCRIPTOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_OWN_PROPERTY_DESCRIPTOR)
  3303. #define DUK_HEAP_STRING_GET_PROTOTYPE_OF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_GET_PROTOTYPE_OF)
  3304. #define DUK_HTHREAD_STRING_GET_PROTOTYPE_OF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_GET_PROTOTYPE_OF)
  3305. #define DUK_HEAP_STRING_PROTOTYPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROTOTYPE)
  3306. #define DUK_HTHREAD_STRING_PROTOTYPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROTOTYPE)
  3307. #define DUK_HEAP_STRING_LENGTH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LENGTH)
  3308. #define DUK_HTHREAD_STRING_LENGTH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LENGTH)
  3309. #define DUK_HEAP_STRING_ALERT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ALERT)
  3310. #define DUK_HTHREAD_STRING_ALERT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ALERT)
  3311. #define DUK_HEAP_STRING_PRINT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PRINT)
  3312. #define DUK_HTHREAD_STRING_PRINT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PRINT)
  3313. #define DUK_HEAP_STRING_UNESCAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_UNESCAPE)
  3314. #define DUK_HTHREAD_STRING_UNESCAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_UNESCAPE)
  3315. #define DUK_HEAP_STRING_ESCAPE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ESCAPE)
  3316. #define DUK_HTHREAD_STRING_ESCAPE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ESCAPE)
  3317. #define DUK_HEAP_STRING_ENCODE_URI_COMPONENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENCODE_URI_COMPONENT)
  3318. #define DUK_HTHREAD_STRING_ENCODE_URI_COMPONENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENCODE_URI_COMPONENT)
  3319. #define DUK_HEAP_STRING_ENCODE_URI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENCODE_URI)
  3320. #define DUK_HTHREAD_STRING_ENCODE_URI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENCODE_URI)
  3321. #define DUK_HEAP_STRING_DECODE_URI_COMPONENT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DECODE_URI_COMPONENT)
  3322. #define DUK_HTHREAD_STRING_DECODE_URI_COMPONENT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DECODE_URI_COMPONENT)
  3323. #define DUK_HEAP_STRING_DECODE_URI(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DECODE_URI)
  3324. #define DUK_HTHREAD_STRING_DECODE_URI(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DECODE_URI)
  3325. #define DUK_HEAP_STRING_IS_FINITE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_FINITE)
  3326. #define DUK_HTHREAD_STRING_IS_FINITE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_FINITE)
  3327. #define DUK_HEAP_STRING_IS_NAN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IS_NAN)
  3328. #define DUK_HTHREAD_STRING_IS_NAN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IS_NAN)
  3329. #define DUK_HEAP_STRING_PARSE_FLOAT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE_FLOAT)
  3330. #define DUK_HTHREAD_STRING_PARSE_FLOAT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE_FLOAT)
  3331. #define DUK_HEAP_STRING_PARSE_INT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PARSE_INT)
  3332. #define DUK_HTHREAD_STRING_PARSE_INT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PARSE_INT)
  3333. #define DUK_HEAP_STRING_EVAL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVAL)
  3334. #define DUK_HTHREAD_STRING_EVAL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVAL)
  3335. #define DUK_HEAP_STRING_URI_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_URI_ERROR)
  3336. #define DUK_HTHREAD_STRING_URI_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_URI_ERROR)
  3337. #define DUK_HEAP_STRING_TYPE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TYPE_ERROR)
  3338. #define DUK_HTHREAD_STRING_TYPE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TYPE_ERROR)
  3339. #define DUK_HEAP_STRING_SYNTAX_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SYNTAX_ERROR)
  3340. #define DUK_HTHREAD_STRING_SYNTAX_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SYNTAX_ERROR)
  3341. #define DUK_HEAP_STRING_REFERENCE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_REFERENCE_ERROR)
  3342. #define DUK_HTHREAD_STRING_REFERENCE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_REFERENCE_ERROR)
  3343. #define DUK_HEAP_STRING_RANGE_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RANGE_ERROR)
  3344. #define DUK_HTHREAD_STRING_RANGE_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RANGE_ERROR)
  3345. #define DUK_HEAP_STRING_EVAL_ERROR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EVAL_ERROR)
  3346. #define DUK_HTHREAD_STRING_EVAL_ERROR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EVAL_ERROR)
  3347. #define DUK_HEAP_STRING_BREAK(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_BREAK)
  3348. #define DUK_HTHREAD_STRING_BREAK(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_BREAK)
  3349. #define DUK_HEAP_STRING_CASE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CASE)
  3350. #define DUK_HTHREAD_STRING_CASE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CASE)
  3351. #define DUK_HEAP_STRING_CATCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CATCH)
  3352. #define DUK_HTHREAD_STRING_CATCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CATCH)
  3353. #define DUK_HEAP_STRING_CONTINUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONTINUE)
  3354. #define DUK_HTHREAD_STRING_CONTINUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONTINUE)
  3355. #define DUK_HEAP_STRING_DEBUGGER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEBUGGER)
  3356. #define DUK_HTHREAD_STRING_DEBUGGER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEBUGGER)
  3357. #define DUK_HEAP_STRING_DEFAULT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DEFAULT)
  3358. #define DUK_HTHREAD_STRING_DEFAULT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DEFAULT)
  3359. #define DUK_HEAP_STRING_DELETE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DELETE)
  3360. #define DUK_HTHREAD_STRING_DELETE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DELETE)
  3361. #define DUK_HEAP_STRING_DO(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_DO)
  3362. #define DUK_HTHREAD_STRING_DO(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_DO)
  3363. #define DUK_HEAP_STRING_ELSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ELSE)
  3364. #define DUK_HTHREAD_STRING_ELSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ELSE)
  3365. #define DUK_HEAP_STRING_FINALLY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FINALLY)
  3366. #define DUK_HTHREAD_STRING_FINALLY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FINALLY)
  3367. #define DUK_HEAP_STRING_FOR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FOR)
  3368. #define DUK_HTHREAD_STRING_FOR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FOR)
  3369. #define DUK_HEAP_STRING_LC_FUNCTION(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_FUNCTION)
  3370. #define DUK_HTHREAD_STRING_LC_FUNCTION(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_FUNCTION)
  3371. #define DUK_HEAP_STRING_IF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IF)
  3372. #define DUK_HTHREAD_STRING_IF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IF)
  3373. #define DUK_HEAP_STRING_IN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IN)
  3374. #define DUK_HTHREAD_STRING_IN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IN)
  3375. #define DUK_HEAP_STRING_INSTANCEOF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INSTANCEOF)
  3376. #define DUK_HTHREAD_STRING_INSTANCEOF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INSTANCEOF)
  3377. #define DUK_HEAP_STRING_NEW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_NEW)
  3378. #define DUK_HTHREAD_STRING_NEW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_NEW)
  3379. #define DUK_HEAP_STRING_RETURN(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_RETURN)
  3380. #define DUK_HTHREAD_STRING_RETURN(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_RETURN)
  3381. #define DUK_HEAP_STRING_SWITCH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SWITCH)
  3382. #define DUK_HTHREAD_STRING_SWITCH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SWITCH)
  3383. #define DUK_HEAP_STRING_THIS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THIS)
  3384. #define DUK_HTHREAD_STRING_THIS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THIS)
  3385. #define DUK_HEAP_STRING_THROW(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_THROW)
  3386. #define DUK_HTHREAD_STRING_THROW(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_THROW)
  3387. #define DUK_HEAP_STRING_TRY(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRY)
  3388. #define DUK_HTHREAD_STRING_TRY(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRY)
  3389. #define DUK_HEAP_STRING_TYPEOF(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TYPEOF)
  3390. #define DUK_HTHREAD_STRING_TYPEOF(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TYPEOF)
  3391. #define DUK_HEAP_STRING_VAR(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VAR)
  3392. #define DUK_HTHREAD_STRING_VAR(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VAR)
  3393. #define DUK_HEAP_STRING_VOID(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_VOID)
  3394. #define DUK_HTHREAD_STRING_VOID(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_VOID)
  3395. #define DUK_HEAP_STRING_WHILE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WHILE)
  3396. #define DUK_HTHREAD_STRING_WHILE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WHILE)
  3397. #define DUK_HEAP_STRING_WITH(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_WITH)
  3398. #define DUK_HTHREAD_STRING_WITH(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_WITH)
  3399. #define DUK_HEAP_STRING_CLASS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CLASS)
  3400. #define DUK_HTHREAD_STRING_CLASS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CLASS)
  3401. #define DUK_HEAP_STRING_CONST(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_CONST)
  3402. #define DUK_HTHREAD_STRING_CONST(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_CONST)
  3403. #define DUK_HEAP_STRING_ENUM(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_ENUM)
  3404. #define DUK_HTHREAD_STRING_ENUM(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_ENUM)
  3405. #define DUK_HEAP_STRING_EXPORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXPORT)
  3406. #define DUK_HTHREAD_STRING_EXPORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXPORT)
  3407. #define DUK_HEAP_STRING_EXTENDS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_EXTENDS)
  3408. #define DUK_HTHREAD_STRING_EXTENDS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_EXTENDS)
  3409. #define DUK_HEAP_STRING_IMPORT(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IMPORT)
  3410. #define DUK_HTHREAD_STRING_IMPORT(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IMPORT)
  3411. #define DUK_HEAP_STRING_SUPER(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_SUPER)
  3412. #define DUK_HTHREAD_STRING_SUPER(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_SUPER)
  3413. #define DUK_HEAP_STRING_LC_NULL(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LC_NULL)
  3414. #define DUK_HTHREAD_STRING_LC_NULL(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LC_NULL)
  3415. #define DUK_HEAP_STRING_TRUE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_TRUE)
  3416. #define DUK_HTHREAD_STRING_TRUE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_TRUE)
  3417. #define DUK_HEAP_STRING_FALSE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_FALSE)
  3418. #define DUK_HTHREAD_STRING_FALSE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_FALSE)
  3419. #define DUK_HEAP_STRING_IMPLEMENTS(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_IMPLEMENTS)
  3420. #define DUK_HTHREAD_STRING_IMPLEMENTS(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_IMPLEMENTS)
  3421. #define DUK_HEAP_STRING_INTERFACE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_INTERFACE)
  3422. #define DUK_HTHREAD_STRING_INTERFACE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_INTERFACE)
  3423. #define DUK_HEAP_STRING_LET(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_LET)
  3424. #define DUK_HTHREAD_STRING_LET(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_LET)
  3425. #define DUK_HEAP_STRING_PACKAGE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PACKAGE)
  3426. #define DUK_HTHREAD_STRING_PACKAGE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PACKAGE)
  3427. #define DUK_HEAP_STRING_PRIVATE(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PRIVATE)
  3428. #define DUK_HTHREAD_STRING_PRIVATE(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PRIVATE)
  3429. #define DUK_HEAP_STRING_PROTECTED(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PROTECTED)
  3430. #define DUK_HTHREAD_STRING_PROTECTED(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PROTECTED)
  3431. #define DUK_HEAP_STRING_PUBLIC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_PUBLIC)
  3432. #define DUK_HTHREAD_STRING_PUBLIC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_PUBLIC)
  3433. #define DUK_HEAP_STRING_STATIC(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_STATIC)
  3434. #define DUK_HTHREAD_STRING_STATIC(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_STATIC)
  3435. #define DUK_HEAP_STRING_YIELD(heap) DUK_HEAP_GET_STRING((heap),DUK_STRIDX_YIELD)
  3436. #define DUK_HTHREAD_STRING_YIELD(thr) DUK_HTHREAD_GET_STRING((thr),DUK_STRIDX_YIELD)
  3437. #define DUK_HEAP_NUM_STRINGS 336
  3438. #define DUK_STRIDX_START_RESERVED 291
  3439. #define DUK_STRIDX_START_STRICT_RESERVED 327
  3440. #define DUK_STRIDX_END_RESERVED 336 /* exclusive endpoint */
  3441. #if !defined(DUK_SINGLE_FILE)
  3442. DUK_INTERNAL_DECL const duk_c_function duk_bi_native_functions[128];
  3443. DUK_INTERNAL_DECL const duk_uint8_t duk_builtins_data[1341];
  3444. #ifdef DUK_USE_BUILTIN_INITJS
  3445. DUK_INTERNAL_DECL const duk_uint8_t duk_initjs_data[187];
  3446. #endif /* DUK_USE_BUILTIN_INITJS */
  3447. #endif /* !DUK_SINGLE_FILE */
  3448. #define DUK_BUILTINS_DATA_LENGTH 1341
  3449. #ifdef DUK_USE_BUILTIN_INITJS
  3450. #define DUK_BUILTIN_INITJS_DATA_LENGTH 187
  3451. #endif /* DUK_USE_BUILTIN_INITJS */
  3452. #define DUK_BIDX_GLOBAL 0
  3453. #define DUK_BIDX_GLOBAL_ENV 1
  3454. #define DUK_BIDX_OBJECT_CONSTRUCTOR 2
  3455. #define DUK_BIDX_OBJECT_PROTOTYPE 3
  3456. #define DUK_BIDX_FUNCTION_CONSTRUCTOR 4
  3457. #define DUK_BIDX_FUNCTION_PROTOTYPE 5
  3458. #define DUK_BIDX_ARRAY_CONSTRUCTOR 6
  3459. #define DUK_BIDX_ARRAY_PROTOTYPE 7
  3460. #define DUK_BIDX_STRING_CONSTRUCTOR 8
  3461. #define DUK_BIDX_STRING_PROTOTYPE 9
  3462. #define DUK_BIDX_BOOLEAN_CONSTRUCTOR 10
  3463. #define DUK_BIDX_BOOLEAN_PROTOTYPE 11
  3464. #define DUK_BIDX_NUMBER_CONSTRUCTOR 12
  3465. #define DUK_BIDX_NUMBER_PROTOTYPE 13
  3466. #define DUK_BIDX_DATE_CONSTRUCTOR 14
  3467. #define DUK_BIDX_DATE_PROTOTYPE 15
  3468. #define DUK_BIDX_REGEXP_CONSTRUCTOR 16
  3469. #define DUK_BIDX_REGEXP_PROTOTYPE 17
  3470. #define DUK_BIDX_ERROR_CONSTRUCTOR 18
  3471. #define DUK_BIDX_ERROR_PROTOTYPE 19
  3472. #define DUK_BIDX_EVAL_ERROR_CONSTRUCTOR 20
  3473. #define DUK_BIDX_EVAL_ERROR_PROTOTYPE 21
  3474. #define DUK_BIDX_RANGE_ERROR_CONSTRUCTOR 22
  3475. #define DUK_BIDX_RANGE_ERROR_PROTOTYPE 23
  3476. #define DUK_BIDX_REFERENCE_ERROR_CONSTRUCTOR 24
  3477. #define DUK_BIDX_REFERENCE_ERROR_PROTOTYPE 25
  3478. #define DUK_BIDX_SYNTAX_ERROR_CONSTRUCTOR 26
  3479. #define DUK_BIDX_SYNTAX_ERROR_PROTOTYPE 27
  3480. #define DUK_BIDX_TYPE_ERROR_CONSTRUCTOR 28
  3481. #define DUK_BIDX_TYPE_ERROR_PROTOTYPE 29
  3482. #define DUK_BIDX_URI_ERROR_CONSTRUCTOR 30
  3483. #define DUK_BIDX_URI_ERROR_PROTOTYPE 31
  3484. #define DUK_BIDX_MATH 32
  3485. #define DUK_BIDX_JSON 33
  3486. #define DUK_BIDX_TYPE_ERROR_THROWER 34
  3487. #define DUK_BIDX_PROXY_CONSTRUCTOR 35
  3488. #define DUK_BIDX_DUKTAPE 36
  3489. #define DUK_BIDX_THREAD_CONSTRUCTOR 37
  3490. #define DUK_BIDX_THREAD_PROTOTYPE 38
  3491. #define DUK_BIDX_BUFFER_CONSTRUCTOR 39
  3492. #define DUK_BIDX_BUFFER_PROTOTYPE 40
  3493. #define DUK_BIDX_POINTER_CONSTRUCTOR 41
  3494. #define DUK_BIDX_POINTER_PROTOTYPE 42
  3495. #define DUK_BIDX_LOGGER_CONSTRUCTOR 43
  3496. #define DUK_BIDX_LOGGER_PROTOTYPE 44
  3497. #define DUK_BIDX_DOUBLE_ERROR 45
  3498. #define DUK_NUM_BUILTINS 46
  3499. #else
  3500. #error invalid endianness defines
  3501. #endif
  3502. #endif /* DUK_BUILTINS_H_INCLUDED */
  3503. #line 50 "duk_internal.h"
  3504. #line 1 "duk_strings.h"
  3505. /*
  3506. * Shared error messages: declarations and macros
  3507. *
  3508. * Error messages are accessed through macros with fine-grained, explicit
  3509. * error message distinctions. Concrete error messages are selected by the
  3510. * macros and multiple macros can map to the same concrete string to save
  3511. * on code footprint. This allows flexible footprint/verbosity tuning with
  3512. * minimal code impact. There are a few limitations to this approach:
  3513. * (1) switching between plain messages and format strings doesn't work
  3514. * conveniently, and (2) conditional strings are a bit awkward to handle.
  3515. *
  3516. * Because format strings behave differently in the call site (they need to
  3517. * be followed by format arguments), they have a special prefix (DUK_STR_FMT_
  3518. * and duk_str_fmt_).
  3519. *
  3520. * On some compilers using explicit shared strings is preferable; on others
  3521. * it may be better to use straight literals because the compiler will combine
  3522. * them anyway, and such strings won't end up unnecessarily in a symbol table.
  3523. */
  3524. #ifndef DUK_ERRMSG_H_INCLUDED
  3525. #define DUK_ERRMSG_H_INCLUDED
  3526. #define DUK_STR_INTERNAL_ERROR duk_str_internal_error
  3527. #define DUK_STR_INVALID_COUNT duk_str_invalid_count
  3528. #define DUK_STR_INVALID_CALL_ARGS duk_str_invalid_call_args
  3529. #define DUK_STR_NOT_CONSTRUCTABLE duk_str_not_constructable
  3530. #define DUK_STR_NOT_CALLABLE duk_str_not_callable
  3531. #define DUK_STR_NOT_EXTENSIBLE duk_str_not_extensible
  3532. #define DUK_STR_NOT_WRITABLE duk_str_not_writable
  3533. #define DUK_STR_NOT_CONFIGURABLE duk_str_not_configurable
  3534. #if !defined(DUK_SINGLE_FILE)
  3535. DUK_INTERNAL_DECL const char *duk_str_internal_error;
  3536. DUK_INTERNAL_DECL const char *duk_str_invalid_count;
  3537. DUK_INTERNAL_DECL const char *duk_str_invalid_call_args;
  3538. DUK_INTERNAL_DECL const char *duk_str_not_constructable;
  3539. DUK_INTERNAL_DECL const char *duk_str_not_callable;
  3540. DUK_INTERNAL_DECL const char *duk_str_not_extensible;
  3541. DUK_INTERNAL_DECL const char *duk_str_not_writable;
  3542. DUK_INTERNAL_DECL const char *duk_str_not_configurable;
  3543. #endif /* !DUK_SINGLE_FILE */
  3544. #define DUK_STR_INVALID_CONTEXT duk_str_invalid_context
  3545. #define DUK_STR_INVALID_INDEX duk_str_invalid_index
  3546. #define DUK_STR_PUSH_BEYOND_ALLOC_STACK duk_str_push_beyond_alloc_stack
  3547. #define DUK_STR_NOT_UNDEFINED duk_str_not_undefined
  3548. #define DUK_STR_NOT_NULL duk_str_not_null
  3549. #define DUK_STR_NOT_BOOLEAN duk_str_not_boolean
  3550. #define DUK_STR_NOT_NUMBER duk_str_not_number
  3551. #define DUK_STR_NOT_STRING duk_str_not_string
  3552. #define DUK_STR_NOT_POINTER duk_str_not_pointer
  3553. #define DUK_STR_NOT_BUFFER duk_str_not_buffer
  3554. #define DUK_STR_UNEXPECTED_TYPE duk_str_unexpected_type
  3555. #define DUK_STR_NOT_THREAD duk_str_not_thread
  3556. #if 0 /*unused*/
  3557. #define DUK_STR_NOT_COMPILEDFUNCTION duk_str_not_compiledfunction
  3558. #endif
  3559. #define DUK_STR_NOT_NATIVEFUNCTION duk_str_not_nativefunction
  3560. #define DUK_STR_NOT_C_FUNCTION duk_str_not_c_function
  3561. #define DUK_STR_DEFAULTVALUE_COERCE_FAILED duk_str_defaultvalue_coerce_failed
  3562. #define DUK_STR_NUMBER_OUTSIDE_RANGE duk_str_number_outside_range
  3563. #define DUK_STR_NOT_OBJECT_COERCIBLE duk_str_not_object_coercible
  3564. #define DUK_STR_STRING_TOO_LONG duk_str_string_too_long
  3565. #define DUK_STR_BUFFER_TOO_LONG duk_str_buffer_too_long
  3566. #define DUK_STR_SPRINTF_TOO_LONG duk_str_sprintf_too_long
  3567. #define DUK_STR_OBJECT_ALLOC_FAILED duk_str_object_alloc_failed
  3568. #define DUK_STR_THREAD_ALLOC_FAILED duk_str_thread_alloc_failed
  3569. #define DUK_STR_FUNC_ALLOC_FAILED duk_str_func_alloc_failed
  3570. #define DUK_STR_BUFFER_ALLOC_FAILED duk_str_buffer_alloc_failed
  3571. #define DUK_STR_POP_TOO_MANY duk_str_pop_too_many
  3572. #define DUK_STR_BUFFER_NOT_DYNAMIC duk_str_buffer_not_dynamic
  3573. #define DUK_STR_FAILED_TO_EXTEND_VALSTACK duk_str_failed_to_extend_valstack
  3574. #define DUK_STR_BASE64_ENCODE_FAILED duk_str_base64_encode_failed
  3575. #define DUK_STR_BASE64_DECODE_FAILED duk_str_base64_decode_failed
  3576. #define DUK_STR_HEX_DECODE_FAILED duk_str_hex_decode_failed
  3577. #define DUK_STR_NO_SOURCECODE duk_str_no_sourcecode
  3578. #define DUK_STR_CONCAT_RESULT_TOO_LONG duk_str_concat_result_too_long
  3579. #define DUK_STR_UNIMPLEMENTED duk_str_unimplemented
  3580. #define DUK_STR_ARRAY_LENGTH_OVER_2G duk_str_array_length_over_2g
  3581. #if !defined(DUK_SINGLE_FILE)
  3582. DUK_INTERNAL_DECL const char *duk_str_invalid_context;
  3583. DUK_INTERNAL_DECL const char *duk_str_invalid_index;
  3584. DUK_INTERNAL_DECL const char *duk_str_push_beyond_alloc_stack;
  3585. DUK_INTERNAL_DECL const char *duk_str_not_undefined;
  3586. DUK_INTERNAL_DECL const char *duk_str_not_null;
  3587. DUK_INTERNAL_DECL const char *duk_str_not_boolean;
  3588. DUK_INTERNAL_DECL const char *duk_str_not_number;
  3589. DUK_INTERNAL_DECL const char *duk_str_not_string;
  3590. DUK_INTERNAL_DECL const char *duk_str_not_pointer;
  3591. DUK_INTERNAL_DECL const char *duk_str_not_buffer;
  3592. DUK_INTERNAL_DECL const char *duk_str_unexpected_type;
  3593. DUK_INTERNAL_DECL const char *duk_str_not_thread;
  3594. #if 0 /*unused*/
  3595. DUK_INTERNAL_DECL const char *duk_str_not_compiledfunction;
  3596. #endif
  3597. DUK_INTERNAL_DECL const char *duk_str_not_nativefunction;
  3598. DUK_INTERNAL_DECL const char *duk_str_not_c_function;
  3599. DUK_INTERNAL_DECL const char *duk_str_defaultvalue_coerce_failed;
  3600. DUK_INTERNAL_DECL const char *duk_str_number_outside_range;
  3601. DUK_INTERNAL_DECL const char *duk_str_not_object_coercible;
  3602. DUK_INTERNAL_DECL const char *duk_str_string_too_long;
  3603. DUK_INTERNAL_DECL const char *duk_str_buffer_too_long;
  3604. DUK_INTERNAL_DECL const char *duk_str_sprintf_too_long;
  3605. DUK_INTERNAL_DECL const char *duk_str_object_alloc_failed;
  3606. DUK_INTERNAL_DECL const char *duk_str_thread_alloc_failed;
  3607. DUK_INTERNAL_DECL const char *duk_str_func_alloc_failed;
  3608. DUK_INTERNAL_DECL const char *duk_str_buffer_alloc_failed;
  3609. DUK_INTERNAL_DECL const char *duk_str_pop_too_many;
  3610. DUK_INTERNAL_DECL const char *duk_str_buffer_not_dynamic;
  3611. DUK_INTERNAL_DECL const char *duk_str_failed_to_extend_valstack;
  3612. DUK_INTERNAL_DECL const char *duk_str_base64_encode_failed;
  3613. DUK_INTERNAL_DECL const char *duk_str_base64_decode_failed;
  3614. DUK_INTERNAL_DECL const char *duk_str_hex_decode_failed;
  3615. DUK_INTERNAL_DECL const char *duk_str_no_sourcecode;
  3616. DUK_INTERNAL_DECL const char *duk_str_concat_result_too_long;
  3617. DUK_INTERNAL_DECL const char *duk_str_unimplemented;
  3618. DUK_INTERNAL_DECL const char *duk_str_array_length_over_2g;
  3619. #endif /* !DUK_SINGLE_FILE */
  3620. #define DUK_STR_FMT_PTR duk_str_fmt_ptr
  3621. #define DUK_STR_FMT_INVALID_JSON duk_str_fmt_invalid_json
  3622. #define DUK_STR_JSONDEC_RECLIMIT duk_str_jsondec_reclimit
  3623. #define DUK_STR_JSONENC_RECLIMIT duk_str_jsonenc_reclimit
  3624. #define DUK_STR_CYCLIC_INPUT duk_str_cyclic_input
  3625. #if !defined(DUK_SINGLE_FILE)
  3626. DUK_INTERNAL_DECL const char *duk_str_fmt_ptr;
  3627. DUK_INTERNAL_DECL const char *duk_str_fmt_invalid_json;
  3628. DUK_INTERNAL_DECL const char *duk_str_jsondec_reclimit;
  3629. DUK_INTERNAL_DECL const char *duk_str_jsonenc_reclimit;
  3630. DUK_INTERNAL_DECL const char *duk_str_cyclic_input;
  3631. #endif /* !DUK_SINGLE_FILE */
  3632. #define DUK_STR_PROXY_REVOKED duk_str_proxy_revoked
  3633. #define DUK_STR_OBJECT_RESIZE_FAILED duk_str_object_resize_failed
  3634. #define DUK_STR_INVALID_BASE duk_str_invalid_base
  3635. #define DUK_STR_STRICT_CALLER_READ duk_str_strict_caller_read
  3636. #define DUK_STR_PROXY_REJECTED duk_str_proxy_rejected
  3637. #define DUK_STR_INVALID_ARRAY_LENGTH duk_str_invalid_array_length
  3638. #define DUK_STR_ARRAY_LENGTH_WRITE_FAILED duk_str_array_length_write_failed
  3639. #define DUK_STR_ARRAY_LENGTH_NOT_WRITABLE duk_str_array_length_not_writable
  3640. #define DUK_STR_SETTER_UNDEFINED duk_str_setter_undefined
  3641. #define DUK_STR_REDEFINE_VIRT_PROP duk_str_redefine_virt_prop
  3642. #define DUK_STR_INVALID_DESCRIPTOR duk_str_invalid_descriptor
  3643. #define DUK_STR_PROPERTY_IS_VIRTUAL duk_str_property_is_virtual
  3644. #if !defined(DUK_SINGLE_FILE)
  3645. DUK_INTERNAL_DECL const char *duk_str_proxy_revoked;
  3646. DUK_INTERNAL_DECL const char *duk_str_object_resize_failed;
  3647. DUK_INTERNAL_DECL const char *duk_str_invalid_base;
  3648. DUK_INTERNAL_DECL const char *duk_str_strict_caller_read;
  3649. DUK_INTERNAL_DECL const char *duk_str_proxy_rejected;
  3650. DUK_INTERNAL_DECL const char *duk_str_invalid_array_length;
  3651. DUK_INTERNAL_DECL const char *duk_str_array_length_write_failed;
  3652. DUK_INTERNAL_DECL const char *duk_str_array_length_not_writable;
  3653. DUK_INTERNAL_DECL const char *duk_str_setter_undefined;
  3654. DUK_INTERNAL_DECL const char *duk_str_redefine_virt_prop;
  3655. DUK_INTERNAL_DECL const char *duk_str_invalid_descriptor;
  3656. DUK_INTERNAL_DECL const char *duk_str_property_is_virtual;
  3657. #endif /* !DUK_SINGLE_FILE */
  3658. #define DUK_STR_PARSE_ERROR duk_str_parse_error
  3659. #define DUK_STR_DUPLICATE_LABEL duk_str_duplicate_label
  3660. #define DUK_STR_INVALID_LABEL duk_str_invalid_label
  3661. #define DUK_STR_INVALID_ARRAY_LITERAL duk_str_invalid_array_literal
  3662. #define DUK_STR_INVALID_OBJECT_LITERAL duk_str_invalid_object_literal
  3663. #define DUK_STR_INVALID_VAR_DECLARATION duk_str_invalid_var_declaration
  3664. #define DUK_STR_CANNOT_DELETE_IDENTIFIER duk_str_cannot_delete_identifier
  3665. #define DUK_STR_INVALID_EXPRESSION duk_str_invalid_expression
  3666. #define DUK_STR_INVALID_LVALUE duk_str_invalid_lvalue
  3667. #define DUK_STR_EXPECTED_IDENTIFIER duk_str_expected_identifier
  3668. #define DUK_STR_EMPTY_EXPR_NOT_ALLOWED duk_str_empty_expr_not_allowed
  3669. #define DUK_STR_INVALID_FOR duk_str_invalid_for
  3670. #define DUK_STR_INVALID_SWITCH duk_str_invalid_switch
  3671. #define DUK_STR_INVALID_BREAK_CONT_LABEL duk_str_invalid_break_cont_label
  3672. #define DUK_STR_INVALID_RETURN duk_str_invalid_return
  3673. #define DUK_STR_INVALID_TRY duk_str_invalid_try
  3674. #define DUK_STR_INVALID_THROW duk_str_invalid_throw
  3675. #define DUK_STR_WITH_IN_STRICT_MODE duk_str_with_in_strict_mode
  3676. #define DUK_STR_FUNC_STMT_NOT_ALLOWED duk_str_func_stmt_not_allowed
  3677. #define DUK_STR_UNTERMINATED_STMT duk_str_unterminated_stmt
  3678. #define DUK_STR_INVALID_ARG_NAME duk_str_invalid_arg_name
  3679. #define DUK_STR_INVALID_FUNC_NAME duk_str_invalid_func_name
  3680. #define DUK_STR_INVALID_GETSET_NAME duk_str_invalid_getset_name
  3681. #define DUK_STR_FUNC_NAME_REQUIRED duk_str_func_name_required
  3682. #if !defined(DUK_SINGLE_FILE)
  3683. DUK_INTERNAL_DECL const char *duk_str_parse_error;
  3684. DUK_INTERNAL_DECL const char *duk_str_duplicate_label;
  3685. DUK_INTERNAL_DECL const char *duk_str_invalid_label;
  3686. DUK_INTERNAL_DECL const char *duk_str_invalid_array_literal;
  3687. DUK_INTERNAL_DECL const char *duk_str_invalid_object_literal;
  3688. DUK_INTERNAL_DECL const char *duk_str_invalid_var_declaration;
  3689. DUK_INTERNAL_DECL const char *duk_str_cannot_delete_identifier;
  3690. DUK_INTERNAL_DECL const char *duk_str_invalid_expression;
  3691. DUK_INTERNAL_DECL const char *duk_str_invalid_lvalue;
  3692. DUK_INTERNAL_DECL const char *duk_str_expected_identifier;
  3693. DUK_INTERNAL_DECL const char *duk_str_empty_expr_not_allowed;
  3694. DUK_INTERNAL_DECL const char *duk_str_invalid_for;
  3695. DUK_INTERNAL_DECL const char *duk_str_invalid_switch;
  3696. DUK_INTERNAL_DECL const char *duk_str_invalid_break_cont_label;
  3697. DUK_INTERNAL_DECL const char *duk_str_invalid_return;
  3698. DUK_INTERNAL_DECL const char *duk_str_invalid_try;
  3699. DUK_INTERNAL_DECL const char *duk_str_invalid_throw;
  3700. DUK_INTERNAL_DECL const char *duk_str_with_in_strict_mode;
  3701. DUK_INTERNAL_DECL const char *duk_str_func_stmt_not_allowed;
  3702. DUK_INTERNAL_DECL const char *duk_str_unterminated_stmt;
  3703. DUK_INTERNAL_DECL const char *duk_str_invalid_arg_name;
  3704. DUK_INTERNAL_DECL const char *duk_str_invalid_func_name;
  3705. DUK_INTERNAL_DECL const char *duk_str_invalid_getset_name;
  3706. DUK_INTERNAL_DECL const char *duk_str_func_name_required;
  3707. #endif /* !DUK_SINGLE_FILE */
  3708. #define DUK_STR_INTERNAL_ERROR_EXEC_LONGJMP duk_str_internal_error_exec_longjmp
  3709. #if !defined(DUK_SINGLE_FILE)
  3710. DUK_INTERNAL_DECL const char *duk_str_internal_error_exec_longjmp;
  3711. #endif /* !DUK_SINGLE_FILE */
  3712. #define DUK_STR_INVALID_QUANTIFIER_NO_ATOM duk_str_invalid_quantifier_no_atom
  3713. #define DUK_STR_INVALID_QUANTIFIER_VALUES duk_str_invalid_quantifier_values
  3714. #define DUK_STR_QUANTIFIER_TOO_MANY_COPIES duk_str_quantifier_too_many_copies
  3715. #define DUK_STR_UNEXPECTED_CLOSING_PAREN duk_str_unexpected_closing_paren
  3716. #define DUK_STR_UNEXPECTED_END_OF_PATTERN duk_str_unexpected_end_of_pattern
  3717. #define DUK_STR_UNEXPECTED_REGEXP_TOKEN duk_str_unexpected_regexp_token
  3718. #define DUK_STR_INVALID_REGEXP_FLAGS duk_str_invalid_regexp_flags
  3719. #define DUK_STR_INVALID_BACKREFS duk_str_invalid_backrefs
  3720. #define DUK_STR_REGEXP_BACKTRACK_FAILED duk_str_regexp_backtrack_failed
  3721. #define DUK_STR_REGEXP_ADVANCE_FAILED duk_str_regexp_advance_failed
  3722. #define DUK_STR_REGEXP_INTERNAL_ERROR duk_str_regexp_internal_error
  3723. #if !defined(DUK_SINGLE_FILE)
  3724. DUK_INTERNAL_DECL const char *duk_str_invalid_quantifier_no_atom;
  3725. DUK_INTERNAL_DECL const char *duk_str_invalid_quantifier_values;
  3726. DUK_INTERNAL_DECL const char *duk_str_quantifier_too_many_copies;
  3727. DUK_INTERNAL_DECL const char *duk_str_unexpected_closing_paren;
  3728. DUK_INTERNAL_DECL const char *duk_str_unexpected_end_of_pattern;
  3729. DUK_INTERNAL_DECL const char *duk_str_unexpected_regexp_token;
  3730. DUK_INTERNAL_DECL const char *duk_str_invalid_regexp_flags;
  3731. DUK_INTERNAL_DECL const char *duk_str_invalid_backrefs;
  3732. DUK_INTERNAL_DECL const char *duk_str_regexp_backtrack_failed;
  3733. DUK_INTERNAL_DECL const char *duk_str_regexp_advance_failed;
  3734. DUK_INTERNAL_DECL const char *duk_str_regexp_internal_error;
  3735. #endif /* !DUK_SINGLE_FILE */
  3736. #define DUK_STR_VALSTACK_LIMIT duk_str_valstack_limit
  3737. #define DUK_STR_CALLSTACK_LIMIT duk_str_callstack_limit
  3738. #define DUK_STR_CATCHSTACK_LIMIT duk_str_catchstack_limit
  3739. #define DUK_STR_OBJECT_PROPERTY_LIMIT duk_str_object_property_limit
  3740. #define DUK_STR_PROTOTYPE_CHAIN_LIMIT duk_str_prototype_chain_limit
  3741. #define DUK_STR_BOUND_CHAIN_LIMIT duk_str_bound_chain_limit
  3742. #define DUK_STR_C_CALLSTACK_LIMIT duk_str_c_callstack_limit
  3743. #define DUK_STR_COMPILER_RECURSION_LIMIT duk_str_compiler_recursion_limit
  3744. #define DUK_STR_BYTECODE_LIMIT duk_str_bytecode_limit
  3745. #define DUK_STR_REG_LIMIT duk_str_reg_limit
  3746. #define DUK_STR_TEMP_LIMIT duk_str_temp_limit
  3747. #define DUK_STR_CONST_LIMIT duk_str_const_limit
  3748. #define DUK_STR_FUNC_LIMIT duk_str_func_limit
  3749. #define DUK_STR_REGEXP_COMPILER_RECURSION_LIMIT duk_str_regexp_compiler_recursion_limit
  3750. #define DUK_STR_REGEXP_EXECUTOR_RECURSION_LIMIT duk_str_regexp_executor_recursion_limit
  3751. #define DUK_STR_REGEXP_EXECUTOR_STEP_LIMIT duk_str_regexp_executor_step_limit
  3752. #if !defined(DUK_SINGLE_FILE)
  3753. DUK_INTERNAL_DECL const char *duk_str_valstack_limit;
  3754. DUK_INTERNAL_DECL const char *duk_str_callstack_limit;
  3755. DUK_INTERNAL_DECL const char *duk_str_catchstack_limit;
  3756. DUK_INTERNAL_DECL const char *duk_str_object_property_limit;
  3757. DUK_INTERNAL_DECL const char *duk_str_prototype_chain_limit;
  3758. DUK_INTERNAL_DECL const char *duk_str_bound_chain_limit;
  3759. DUK_INTERNAL_DECL const char *duk_str_c_callstack_limit;
  3760. DUK_INTERNAL_DECL const char *duk_str_compiler_recursion_limit;
  3761. DUK_INTERNAL_DECL const char *duk_str_bytecode_limit;
  3762. DUK_INTERNAL_DECL const char *duk_str_reg_limit;
  3763. DUK_INTERNAL_DECL const char *duk_str_temp_limit;
  3764. DUK_INTERNAL_DECL const char *duk_str_const_limit;
  3765. DUK_INTERNAL_DECL const char *duk_str_func_limit;
  3766. DUK_INTERNAL_DECL const char *duk_str_regexp_compiler_recursion_limit;
  3767. DUK_INTERNAL_DECL const char *duk_str_regexp_executor_recursion_limit;
  3768. DUK_INTERNAL_DECL const char *duk_str_regexp_executor_step_limit;
  3769. #endif /* !DUK_SINGLE_FILE */
  3770. #define DUK_STR_ANON duk_str_anon
  3771. #define DUK_STR_REALLOC_FAILED duk_str_realloc_failed
  3772. #if !defined(DUK_SINGLE_FILE)
  3773. DUK_INTERNAL_DECL const char *duk_str_anon;
  3774. DUK_INTERNAL_DECL const char *duk_str_realloc_failed;
  3775. #endif /* !DUK_SINGLE_FILE */
  3776. #endif /* DUK_ERRMSG_H_INCLUDED */
  3777. #line 1 "duk_js_bytecode.h"
  3778. /*
  3779. * Ecmascript bytecode
  3780. */
  3781. #ifndef DUK_JS_BYTECODE_H_INCLUDED
  3782. #define DUK_JS_BYTECODE_H_INCLUDED
  3783. /*
  3784. * Logical instruction layout
  3785. * ==========================
  3786. *
  3787. * !3!3!2!2!2!2!2!2!2!2!2!2!1!1!1!1!1!1!1!1!1!1! ! ! ! ! ! ! ! ! ! !
  3788. * !1!0!9!8!7!6!5!4!3!2!1!0!9!8!7!6!5!4!3!2!1!0!9!8!7!6!5!4!3!2!1!0!
  3789. * +---------------------------------------------------+-----------+
  3790. * ! C ! B ! A ! OP !
  3791. * +---------------------------------------------------+-----------+
  3792. *
  3793. * OP (6 bits): opcode (DUK_OP_*), access should be fastest
  3794. * A (8 bits): typically a target register number
  3795. * B (9 bits): typically first source register/constant number
  3796. * C (9 bits): typically second source register/constant number
  3797. *
  3798. * Some instructions combine BC or ABC together for larger parameter values.
  3799. * Signed integers (e.g. jump offsets) are encoded as unsigned, with an opcode
  3800. * specific bias. B and C may denote a register or a constant, see
  3801. * DUK_BC_ISREG() and DUK_BC_ISCONST().
  3802. *
  3803. * Note: macro naming is a bit misleading, e.g. "ABC" in macro name but
  3804. * the field layout is logically "CBA".
  3805. */
  3806. typedef duk_uint32_t duk_instr_t;
  3807. #define DUK_DEC_OP(x) ((x) & 0x3fUL)
  3808. #define DUK_DEC_A(x) (((x) >> 6) & 0xffUL)
  3809. #define DUK_DEC_B(x) (((x) >> 14) & 0x1ffUL)
  3810. #define DUK_DEC_C(x) (((x) >> 23) & 0x1ffUL)
  3811. #define DUK_DEC_BC(x) (((x) >> 14) & 0x3ffffUL)
  3812. #define DUK_DEC_ABC(x) (((x) >> 6) & 0x3ffffffUL)
  3813. #define DUK_ENC_OP(op) ((duk_instr_t) (op))
  3814. #define DUK_ENC_OP_ABC(op,abc) ((duk_instr_t) ( \
  3815. (((duk_instr_t) (abc)) << 6) | \
  3816. ((duk_instr_t) (op)) \
  3817. ))
  3818. #define DUK_ENC_OP_A_BC(op,a,bc) ((duk_instr_t) ( \
  3819. (((duk_instr_t) (bc)) << 14) | \
  3820. (((duk_instr_t) (a)) << 6) | \
  3821. ((duk_instr_t) (op)) \
  3822. ))
  3823. #define DUK_ENC_OP_A_B_C(op,a,b,c) ((duk_instr_t) ( \
  3824. (((duk_instr_t) (c)) << 23) | \
  3825. (((duk_instr_t) (b)) << 14) | \
  3826. (((duk_instr_t) (a)) << 6) | \
  3827. ((duk_instr_t) (op)) \
  3828. ))
  3829. #define DUK_ENC_OP_A_B(op,a,b) DUK_ENC_OP_A_B_C(op,a,b,0)
  3830. #define DUK_ENC_OP_A(op,a) DUK_ENC_OP_A_B_C(op,a,0,0)
  3831. /* Constants should be signed so that signed arithmetic involving them
  3832. * won't cause values to be coerced accidentally to unsigned.
  3833. */
  3834. #define DUK_BC_OP_MIN 0
  3835. #define DUK_BC_OP_MAX 0x3fL
  3836. #define DUK_BC_A_MIN 0
  3837. #define DUK_BC_A_MAX 0xffL
  3838. #define DUK_BC_B_MIN 0
  3839. #define DUK_BC_B_MAX 0x1ffL
  3840. #define DUK_BC_C_MIN 0
  3841. #define DUK_BC_C_MAX 0x1ffL
  3842. #define DUK_BC_BC_MIN 0
  3843. #define DUK_BC_BC_MAX 0x3ffffL
  3844. #define DUK_BC_ABC_MIN 0
  3845. #define DUK_BC_ABC_MAX 0x3ffffffL
  3846. #define DUK_BC_EXTRAOP_MIN DUK_BC_A_MIN
  3847. #define DUK_BC_EXTRAOP_MAX DUK_BC_A_MAX
  3848. #define DUK_OP_LDREG 0
  3849. #define DUK_OP_STREG 1
  3850. #define DUK_OP_LDCONST 2
  3851. #define DUK_OP_LDINT 3
  3852. #define DUK_OP_LDINTX 4
  3853. #define DUK_OP_MPUTOBJ 5
  3854. #define DUK_OP_MPUTOBJI 6
  3855. #define DUK_OP_MPUTARR 7
  3856. #define DUK_OP_MPUTARRI 8
  3857. #define DUK_OP_NEW 9
  3858. #define DUK_OP_NEWI 10
  3859. #define DUK_OP_REGEXP 11
  3860. #define DUK_OP_CSREG 12
  3861. #define DUK_OP_CSREGI 13
  3862. #define DUK_OP_GETVAR 14
  3863. #define DUK_OP_PUTVAR 15
  3864. #define DUK_OP_DECLVAR 16
  3865. #define DUK_OP_DELVAR 17
  3866. #define DUK_OP_CSVAR 18
  3867. #define DUK_OP_CSVARI 19
  3868. #define DUK_OP_CLOSURE 20
  3869. #define DUK_OP_GETPROP 21
  3870. #define DUK_OP_PUTPROP 22
  3871. #define DUK_OP_DELPROP 23
  3872. #define DUK_OP_CSPROP 24
  3873. #define DUK_OP_CSPROPI 25
  3874. #define DUK_OP_ADD 26
  3875. #define DUK_OP_SUB 27
  3876. #define DUK_OP_MUL 28
  3877. #define DUK_OP_DIV 29
  3878. #define DUK_OP_MOD 30
  3879. #define DUK_OP_BAND 31
  3880. #define DUK_OP_BOR 32
  3881. #define DUK_OP_BXOR 33
  3882. #define DUK_OP_BASL 34
  3883. #define DUK_OP_BLSR 35
  3884. #define DUK_OP_BASR 36
  3885. #define DUK_OP_EQ 37
  3886. #define DUK_OP_NEQ 38
  3887. #define DUK_OP_SEQ 39
  3888. #define DUK_OP_SNEQ 40
  3889. #define DUK_OP_GT 41
  3890. #define DUK_OP_GE 42
  3891. #define DUK_OP_LT 43
  3892. #define DUK_OP_LE 44
  3893. #define DUK_OP_IF 45
  3894. #define DUK_OP_JUMP 46
  3895. #define DUK_OP_RETURN 47
  3896. #define DUK_OP_CALL 48
  3897. #define DUK_OP_CALLI 49
  3898. #define DUK_OP_TRYCATCH 50
  3899. #define DUK_OP_EXTRA 51
  3900. #define DUK_OP_PREINCR 52 /* pre/post opcode values have constraints, */
  3901. #define DUK_OP_PREDECR 53 /* see duk_js_executor.c */
  3902. #define DUK_OP_POSTINCR 54
  3903. #define DUK_OP_POSTDECR 55
  3904. #define DUK_OP_PREINCV 56
  3905. #define DUK_OP_PREDECV 57
  3906. #define DUK_OP_POSTINCV 58
  3907. #define DUK_OP_POSTDECV 59
  3908. #define DUK_OP_PREINCP 60
  3909. #define DUK_OP_PREDECP 61
  3910. #define DUK_OP_POSTINCP 62
  3911. #define DUK_OP_POSTDECP 63
  3912. #define DUK_OP_NONE 64 /* dummy value used as marker */
  3913. /* DUK_OP_EXTRA, sub-operation in A */
  3914. #define DUK_EXTRAOP_NOP 0
  3915. #define DUK_EXTRAOP_INVALID 1
  3916. #define DUK_EXTRAOP_LDTHIS 2
  3917. #define DUK_EXTRAOP_LDUNDEF 3
  3918. #define DUK_EXTRAOP_LDNULL 4
  3919. #define DUK_EXTRAOP_LDTRUE 5
  3920. #define DUK_EXTRAOP_LDFALSE 6
  3921. #define DUK_EXTRAOP_NEWOBJ 7
  3922. #define DUK_EXTRAOP_NEWARR 8
  3923. #define DUK_EXTRAOP_SETALEN 9
  3924. #define DUK_EXTRAOP_TYPEOF 10
  3925. #define DUK_EXTRAOP_TYPEOFID 11
  3926. #define DUK_EXTRAOP_INITENUM 12
  3927. #define DUK_EXTRAOP_NEXTENUM 13
  3928. #define DUK_EXTRAOP_INITSET 14
  3929. #define DUK_EXTRAOP_INITSETI 15
  3930. #define DUK_EXTRAOP_INITGET 16
  3931. #define DUK_EXTRAOP_INITGETI 17
  3932. #define DUK_EXTRAOP_ENDTRY 18
  3933. #define DUK_EXTRAOP_ENDCATCH 19
  3934. #define DUK_EXTRAOP_ENDFIN 20
  3935. #define DUK_EXTRAOP_THROW 21
  3936. #define DUK_EXTRAOP_INVLHS 22
  3937. #define DUK_EXTRAOP_UNM 23
  3938. #define DUK_EXTRAOP_UNP 24
  3939. #define DUK_EXTRAOP_DEBUGGER 25
  3940. #define DUK_EXTRAOP_BREAK 26
  3941. #define DUK_EXTRAOP_CONTINUE 27
  3942. #define DUK_EXTRAOP_BNOT 28
  3943. #define DUK_EXTRAOP_LNOT 29
  3944. #define DUK_EXTRAOP_INSTOF 30
  3945. #define DUK_EXTRAOP_IN 31
  3946. #define DUK_EXTRAOP_LABEL 32
  3947. #define DUK_EXTRAOP_ENDLABEL 33
  3948. /* DUK_OP_EXTRA for debugging */
  3949. #define DUK_EXTRAOP_DUMPREG 128
  3950. #define DUK_EXTRAOP_DUMPREGS 129
  3951. #define DUK_EXTRAOP_LOGMARK 130
  3952. /* DUK_OP_CALL flags in A */
  3953. #define DUK_BC_CALL_FLAG_TAILCALL (1 << 0)
  3954. #define DUK_BC_CALL_FLAG_EVALCALL (1 << 1)
  3955. /* DUK_OP_TRYCATCH flags in A */
  3956. #define DUK_BC_TRYCATCH_FLAG_HAVE_CATCH (1 << 0)
  3957. #define DUK_BC_TRYCATCH_FLAG_HAVE_FINALLY (1 << 1)
  3958. #define DUK_BC_TRYCATCH_FLAG_CATCH_BINDING (1 << 2)
  3959. #define DUK_BC_TRYCATCH_FLAG_WITH_BINDING (1 << 3)
  3960. /* DUK_OP_RETURN flags in A */
  3961. #define DUK_BC_RETURN_FLAG_FAST (1 << 0)
  3962. #define DUK_BC_RETURN_FLAG_HAVE_RETVAL (1 << 1)
  3963. /* DUK_OP_DECLVAR flags in A; bottom bits are reserved for propdesc flags (DUK_PROPDESC_FLAG_XXX) */
  3964. #define DUK_BC_DECLVAR_FLAG_UNDEF_VALUE (1 << 4) /* use 'undefined' for value automatically */
  3965. #define DUK_BC_DECLVAR_FLAG_FUNC_DECL (1 << 5) /* function declaration */
  3966. /* misc constants and helper macros */
  3967. #define DUK_BC_REGLIMIT 256 /* if B/C is >= this value, refers to a const */
  3968. #define DUK_BC_ISREG(x) ((x) < DUK_BC_REGLIMIT)
  3969. #define DUK_BC_ISCONST(x) ((x) >= DUK_BC_REGLIMIT)
  3970. #define DUK_BC_LDINT_BIAS (1L << 17)
  3971. #define DUK_BC_LDINTX_SHIFT 18
  3972. #define DUK_BC_JUMP_BIAS (1L << 25)
  3973. #endif /* DUK_JS_BYTECODE_H_INCLUDED */
  3974. #line 1 "duk_lexer.h"
  3975. /*
  3976. * Lexer defines.
  3977. */
  3978. #ifndef DUK_LEXER_H_INCLUDED
  3979. #define DUK_LEXER_H_INCLUDED
  3980. typedef void (*duk_re_range_callback)(void *user, duk_codepoint_t r1, duk_codepoint_t r2, duk_bool_t direct);
  3981. /*
  3982. * A token is interpreted as any possible production of InputElementDiv
  3983. * and InputElementRegExp, see E5 Section 7 in its entirety. Note that
  3984. * the E5 "Token" production does not cover all actual tokens of the
  3985. * language (which is explicitly stated in the specification, Section 7.5).
  3986. * Null and boolean literals are defined as part of both ReservedWord
  3987. * (E5 Section 7.6.1) and Literal (E5 Section 7.8) productions. Here,
  3988. * null and boolean values have literal tokens, and are not reserved
  3989. * words.
  3990. *
  3991. * Decimal literal negative/positive sign is -not- part of DUK_TOK_NUMBER.
  3992. * The number tokens always have a non-negative value. The unary minus
  3993. * operator in "-1.0" is optimized during compilation to yield a single
  3994. * negative constant.
  3995. *
  3996. * Token numbering is free except that reserved words are required to be
  3997. * in a continuous range and in a particular order. See genstrings.py.
  3998. */
  3999. #define DUK_LEXER_INITCTX(ctx) duk_lexer_initctx((ctx))
  4000. #define DUK_LEXER_SETPOINT(ctx,pt) duk_lexer_setpoint((ctx), (pt))
  4001. #define DUK_LEXER_GETPOINT(ctx,pt) do { (pt)->offset = (ctx)->offsets[0]; \
  4002. (pt)->line = (ctx)->lines[0]; } while (0)
  4003. /* currently 6 characters of lookup are actually needed (duk_lexer.c) */
  4004. #define DUK_LEXER_WINDOW_SIZE 8
  4005. #define DUK_TOK_MINVAL 0
  4006. /* returned after EOF (infinite amount) */
  4007. #define DUK_TOK_EOF 0
  4008. /* line terminator or multi-line comment with internal lineterm (E5 Sections 7.3, 7.4) */
  4009. #define DUK_TOK_LINETERM 1
  4010. /* single-line comment or multi-line comment without internal lineterm (E5 Section 7.4) */
  4011. #define DUK_TOK_COMMENT 2
  4012. /* identifier names (E5 Section 7.6) */
  4013. #define DUK_TOK_IDENTIFIER 3
  4014. /* reserved words: keywords */
  4015. #define DUK_TOK_START_RESERVED 4
  4016. #define DUK_TOK_BREAK 4
  4017. #define DUK_TOK_CASE 5
  4018. #define DUK_TOK_CATCH 6
  4019. #define DUK_TOK_CONTINUE 7
  4020. #define DUK_TOK_DEBUGGER 8
  4021. #define DUK_TOK_DEFAULT 9
  4022. #define DUK_TOK_DELETE 10
  4023. #define DUK_TOK_DO 11
  4024. #define DUK_TOK_ELSE 12
  4025. #define DUK_TOK_FINALLY 13
  4026. #define DUK_TOK_FOR 14
  4027. #define DUK_TOK_FUNCTION 15
  4028. #define DUK_TOK_IF 16
  4029. #define DUK_TOK_IN 17
  4030. #define DUK_TOK_INSTANCEOF 18
  4031. #define DUK_TOK_NEW 19
  4032. #define DUK_TOK_RETURN 20
  4033. #define DUK_TOK_SWITCH 21
  4034. #define DUK_TOK_THIS 22
  4035. #define DUK_TOK_THROW 23
  4036. #define DUK_TOK_TRY 24
  4037. #define DUK_TOK_TYPEOF 25
  4038. #define DUK_TOK_VAR 26
  4039. #define DUK_TOK_VOID 27
  4040. #define DUK_TOK_WHILE 28
  4041. #define DUK_TOK_WITH 29
  4042. /* reserved words: future reserved words */
  4043. #define DUK_TOK_CLASS 30
  4044. #define DUK_TOK_CONST 31
  4045. #define DUK_TOK_ENUM 32
  4046. #define DUK_TOK_EXPORT 33
  4047. #define DUK_TOK_EXTENDS 34
  4048. #define DUK_TOK_IMPORT 35
  4049. #define DUK_TOK_SUPER 36
  4050. /* "null", "true", and "false" are always reserved words.
  4051. * Note that "get" and "set" are not!
  4052. */
  4053. #define DUK_TOK_NULL 37
  4054. #define DUK_TOK_TRUE 38
  4055. #define DUK_TOK_FALSE 39
  4056. /* reserved words: additional future reserved words in strict mode */
  4057. #define DUK_TOK_START_STRICT_RESERVED 40 /* inclusive */
  4058. #define DUK_TOK_IMPLEMENTS 40
  4059. #define DUK_TOK_INTERFACE 41
  4060. #define DUK_TOK_LET 42
  4061. #define DUK_TOK_PACKAGE 43
  4062. #define DUK_TOK_PRIVATE 44
  4063. #define DUK_TOK_PROTECTED 45
  4064. #define DUK_TOK_PUBLIC 46
  4065. #define DUK_TOK_STATIC 47
  4066. #define DUK_TOK_YIELD 48
  4067. #define DUK_TOK_END_RESERVED 49 /* exclusive */
  4068. /* "get" and "set" are tokens but NOT ReservedWords. They are currently
  4069. * parsed and identifiers and these defines are actually now unused.
  4070. */
  4071. #define DUK_TOK_GET 49
  4072. #define DUK_TOK_SET 50
  4073. /* punctuators (unlike the spec, also includes "/" and "/=") */
  4074. #define DUK_TOK_LCURLY 51
  4075. #define DUK_TOK_RCURLY 52
  4076. #define DUK_TOK_LBRACKET 53
  4077. #define DUK_TOK_RBRACKET 54
  4078. #define DUK_TOK_LPAREN 55
  4079. #define DUK_TOK_RPAREN 56
  4080. #define DUK_TOK_PERIOD 57
  4081. #define DUK_TOK_SEMICOLON 58
  4082. #define DUK_TOK_COMMA 59
  4083. #define DUK_TOK_LT 60
  4084. #define DUK_TOK_GT 61
  4085. #define DUK_TOK_LE 62
  4086. #define DUK_TOK_GE 63
  4087. #define DUK_TOK_EQ 64
  4088. #define DUK_TOK_NEQ 65
  4089. #define DUK_TOK_SEQ 66
  4090. #define DUK_TOK_SNEQ 67
  4091. #define DUK_TOK_ADD 68
  4092. #define DUK_TOK_SUB 69
  4093. #define DUK_TOK_MUL 70
  4094. #define DUK_TOK_DIV 71
  4095. #define DUK_TOK_MOD 72
  4096. #define DUK_TOK_INCREMENT 73
  4097. #define DUK_TOK_DECREMENT 74
  4098. #define DUK_TOK_ALSHIFT 75 /* named "arithmetic" because result is signed */
  4099. #define DUK_TOK_ARSHIFT 76
  4100. #define DUK_TOK_RSHIFT 77
  4101. #define DUK_TOK_BAND 78
  4102. #define DUK_TOK_BOR 79
  4103. #define DUK_TOK_BXOR 80
  4104. #define DUK_TOK_LNOT 81
  4105. #define DUK_TOK_BNOT 82
  4106. #define DUK_TOK_LAND 83
  4107. #define DUK_TOK_LOR 84
  4108. #define DUK_TOK_QUESTION 85
  4109. #define DUK_TOK_COLON 86
  4110. #define DUK_TOK_EQUALSIGN 87
  4111. #define DUK_TOK_ADD_EQ 88
  4112. #define DUK_TOK_SUB_EQ 89
  4113. #define DUK_TOK_MUL_EQ 90
  4114. #define DUK_TOK_DIV_EQ 91
  4115. #define DUK_TOK_MOD_EQ 92
  4116. #define DUK_TOK_ALSHIFT_EQ 93
  4117. #define DUK_TOK_ARSHIFT_EQ 94
  4118. #define DUK_TOK_RSHIFT_EQ 95
  4119. #define DUK_TOK_BAND_EQ 96
  4120. #define DUK_TOK_BOR_EQ 97
  4121. #define DUK_TOK_BXOR_EQ 98
  4122. /* literals (E5 Section 7.8), except null, true, false, which are treated
  4123. * like reserved words (above).
  4124. */
  4125. #define DUK_TOK_NUMBER 99
  4126. #define DUK_TOK_STRING 100
  4127. #define DUK_TOK_REGEXP 101
  4128. #define DUK_TOK_MAXVAL 101 /* inclusive */
  4129. /* Convert heap string index to a token (reserved words) */
  4130. #define DUK_STRIDX_TO_TOK(x) ((x) - DUK_STRIDX_START_RESERVED + DUK_TOK_START_RESERVED)
  4131. /* Sanity check */
  4132. #if (DUK_TOK_MAXVAL > 255)
  4133. #error DUK_TOK_MAXVAL too large, code assumes it fits into 8 bits
  4134. #endif
  4135. /* Sanity checks for string and token defines */
  4136. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_BREAK) != DUK_TOK_BREAK)
  4137. #error mismatch in token defines
  4138. #endif
  4139. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_CASE) != DUK_TOK_CASE)
  4140. #error mismatch in token defines
  4141. #endif
  4142. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_CATCH) != DUK_TOK_CATCH)
  4143. #error mismatch in token defines
  4144. #endif
  4145. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_CONTINUE) != DUK_TOK_CONTINUE)
  4146. #error mismatch in token defines
  4147. #endif
  4148. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_DEBUGGER) != DUK_TOK_DEBUGGER)
  4149. #error mismatch in token defines
  4150. #endif
  4151. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_DEFAULT) != DUK_TOK_DEFAULT)
  4152. #error mismatch in token defines
  4153. #endif
  4154. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_DELETE) != DUK_TOK_DELETE)
  4155. #error mismatch in token defines
  4156. #endif
  4157. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_DO) != DUK_TOK_DO)
  4158. #error mismatch in token defines
  4159. #endif
  4160. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_ELSE) != DUK_TOK_ELSE)
  4161. #error mismatch in token defines
  4162. #endif
  4163. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_FINALLY) != DUK_TOK_FINALLY)
  4164. #error mismatch in token defines
  4165. #endif
  4166. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_FOR) != DUK_TOK_FOR)
  4167. #error mismatch in token defines
  4168. #endif
  4169. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_LC_FUNCTION) != DUK_TOK_FUNCTION)
  4170. #error mismatch in token defines
  4171. #endif
  4172. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_IF) != DUK_TOK_IF)
  4173. #error mismatch in token defines
  4174. #endif
  4175. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_IN) != DUK_TOK_IN)
  4176. #error mismatch in token defines
  4177. #endif
  4178. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_INSTANCEOF) != DUK_TOK_INSTANCEOF)
  4179. #error mismatch in token defines
  4180. #endif
  4181. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_NEW) != DUK_TOK_NEW)
  4182. #error mismatch in token defines
  4183. #endif
  4184. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_RETURN) != DUK_TOK_RETURN)
  4185. #error mismatch in token defines
  4186. #endif
  4187. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_SWITCH) != DUK_TOK_SWITCH)
  4188. #error mismatch in token defines
  4189. #endif
  4190. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_THIS) != DUK_TOK_THIS)
  4191. #error mismatch in token defines
  4192. #endif
  4193. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_THROW) != DUK_TOK_THROW)
  4194. #error mismatch in token defines
  4195. #endif
  4196. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_TRY) != DUK_TOK_TRY)
  4197. #error mismatch in token defines
  4198. #endif
  4199. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_TYPEOF) != DUK_TOK_TYPEOF)
  4200. #error mismatch in token defines
  4201. #endif
  4202. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_VAR) != DUK_TOK_VAR)
  4203. #error mismatch in token defines
  4204. #endif
  4205. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_VOID) != DUK_TOK_VOID)
  4206. #error mismatch in token defines
  4207. #endif
  4208. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_WHILE) != DUK_TOK_WHILE)
  4209. #error mismatch in token defines
  4210. #endif
  4211. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_WITH) != DUK_TOK_WITH)
  4212. #error mismatch in token defines
  4213. #endif
  4214. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_CLASS) != DUK_TOK_CLASS)
  4215. #error mismatch in token defines
  4216. #endif
  4217. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_CONST) != DUK_TOK_CONST)
  4218. #error mismatch in token defines
  4219. #endif
  4220. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_ENUM) != DUK_TOK_ENUM)
  4221. #error mismatch in token defines
  4222. #endif
  4223. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_EXPORT) != DUK_TOK_EXPORT)
  4224. #error mismatch in token defines
  4225. #endif
  4226. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_EXTENDS) != DUK_TOK_EXTENDS)
  4227. #error mismatch in token defines
  4228. #endif
  4229. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_IMPORT) != DUK_TOK_IMPORT)
  4230. #error mismatch in token defines
  4231. #endif
  4232. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_SUPER) != DUK_TOK_SUPER)
  4233. #error mismatch in token defines
  4234. #endif
  4235. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_LC_NULL) != DUK_TOK_NULL)
  4236. #error mismatch in token defines
  4237. #endif
  4238. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_TRUE) != DUK_TOK_TRUE)
  4239. #error mismatch in token defines
  4240. #endif
  4241. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_FALSE) != DUK_TOK_FALSE)
  4242. #error mismatch in token defines
  4243. #endif
  4244. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_IMPLEMENTS) != DUK_TOK_IMPLEMENTS)
  4245. #error mismatch in token defines
  4246. #endif
  4247. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_INTERFACE) != DUK_TOK_INTERFACE)
  4248. #error mismatch in token defines
  4249. #endif
  4250. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_LET) != DUK_TOK_LET)
  4251. #error mismatch in token defines
  4252. #endif
  4253. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_PACKAGE) != DUK_TOK_PACKAGE)
  4254. #error mismatch in token defines
  4255. #endif
  4256. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_PRIVATE) != DUK_TOK_PRIVATE)
  4257. #error mismatch in token defines
  4258. #endif
  4259. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_PROTECTED) != DUK_TOK_PROTECTED)
  4260. #error mismatch in token defines
  4261. #endif
  4262. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_PUBLIC) != DUK_TOK_PUBLIC)
  4263. #error mismatch in token defines
  4264. #endif
  4265. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_STATIC) != DUK_TOK_STATIC)
  4266. #error mismatch in token defines
  4267. #endif
  4268. #if (DUK_STRIDX_TO_TOK(DUK_STRIDX_YIELD) != DUK_TOK_YIELD)
  4269. #error mismatch in token defines
  4270. #endif
  4271. /* Regexp tokens */
  4272. #define DUK_RETOK_EOF 0
  4273. #define DUK_RETOK_DISJUNCTION 1
  4274. #define DUK_RETOK_QUANTIFIER 2
  4275. #define DUK_RETOK_ASSERT_START 3
  4276. #define DUK_RETOK_ASSERT_END 4
  4277. #define DUK_RETOK_ASSERT_WORD_BOUNDARY 5
  4278. #define DUK_RETOK_ASSERT_NOT_WORD_BOUNDARY 6
  4279. #define DUK_RETOK_ASSERT_START_POS_LOOKAHEAD 7
  4280. #define DUK_RETOK_ASSERT_START_NEG_LOOKAHEAD 8
  4281. #define DUK_RETOK_ATOM_PERIOD 9
  4282. #define DUK_RETOK_ATOM_CHAR 10
  4283. #define DUK_RETOK_ATOM_DIGIT 11
  4284. #define DUK_RETOK_ATOM_NOT_DIGIT 12
  4285. #define DUK_RETOK_ATOM_WHITE 13
  4286. #define DUK_RETOK_ATOM_NOT_WHITE 14
  4287. #define DUK_RETOK_ATOM_WORD_CHAR 15
  4288. #define DUK_RETOK_ATOM_NOT_WORD_CHAR 16
  4289. #define DUK_RETOK_ATOM_BACKREFERENCE 17
  4290. #define DUK_RETOK_ATOM_START_CAPTURE_GROUP 18
  4291. #define DUK_RETOK_ATOM_START_NONCAPTURE_GROUP 19
  4292. #define DUK_RETOK_ATOM_START_CHARCLASS 20
  4293. #define DUK_RETOK_ATOM_START_CHARCLASS_INVERTED 21
  4294. #define DUK_RETOK_ATOM_END_GROUP 22
  4295. /* constants for duk_lexer_ctx.buf */
  4296. #define DUK_LEXER_TEMP_BUF_INITIAL 64
  4297. #define DUK_LEXER_TEMP_BUF_LIMIT 256
  4298. /* A token value. Can be memcpy()'d, but note that slot1/slot2 values are on the valstack. */
  4299. struct duk_token {
  4300. duk_small_int_t t; /* token type (with reserved word identification) */
  4301. duk_small_int_t t_nores; /* token type (with reserved words as DUK_TOK_IDENTIFER) */
  4302. duk_double_t num; /* numeric value of token */
  4303. duk_hstring *str1; /* string 1 of token (borrowed, stored to ctx->slot1_idx) */
  4304. duk_hstring *str2; /* string 2 of token (borrowed, stored to ctx->slot1_idx) */
  4305. duk_size_t start_offset; /* start byte offset of token in lexer input */
  4306. duk_int_t start_line; /* start line of token (first char) */
  4307. duk_int_t num_escapes; /* number of escapes and line continuations (for directive prologue) */
  4308. duk_bool_t lineterm; /* token was preceded by a lineterm */
  4309. duk_bool_t allow_auto_semi; /* token allows automatic semicolon insertion (eof or preceded by newline) */
  4310. };
  4311. #define DUK_RE_QUANTIFIER_INFINITE ((duk_uint32_t) 0xffffffffUL)
  4312. /* A regexp token value. */
  4313. struct duk_re_token {
  4314. duk_small_int_t t; /* token type */
  4315. duk_small_int_t greedy;
  4316. duk_uint_fast32_t num; /* numeric value (character, count) */
  4317. duk_uint_fast32_t qmin;
  4318. duk_uint_fast32_t qmax;
  4319. };
  4320. /* A structure for 'snapshotting' a point for rewinding */
  4321. struct duk_lexer_point {
  4322. duk_size_t offset;
  4323. duk_int_t line;
  4324. };
  4325. /* Lexer context. Same context is used for Ecmascript and Regexp parsing. */
  4326. struct duk_lexer_ctx {
  4327. duk_hthread *thr; /* thread; minimizes argument passing */
  4328. const duk_uint8_t *input; /* input string (may be a user pointer) */
  4329. duk_size_t input_length; /* input byte length */
  4330. duk_size_t input_offset; /* input offset for window leading edge (not window[0]) */
  4331. duk_codepoint_t window[DUK_LEXER_WINDOW_SIZE]; /* window of unicode code points */
  4332. duk_size_t offsets[DUK_LEXER_WINDOW_SIZE]; /* input byte offset for each char */
  4333. duk_int_t lines[DUK_LEXER_WINDOW_SIZE]; /* input lines for each char */
  4334. duk_int_t input_line; /* input linenumber at input_offset (not window[0]), init to 1 */
  4335. duk_idx_t slot1_idx; /* valstack slot for 1st token value */
  4336. duk_idx_t slot2_idx; /* valstack slot for 2nd token value */
  4337. duk_idx_t buf_idx; /* valstack slot for temp buffer */
  4338. duk_hbuffer_dynamic *buf; /* temp accumulation buffer (on valstack) */
  4339. duk_int_t token_count; /* number of tokens parsed */
  4340. duk_int_t token_limit; /* maximum token count before error (sanity backstop) */
  4341. };
  4342. /*
  4343. * Prototypes
  4344. */
  4345. DUK_INTERNAL_DECL void duk_lexer_initctx(duk_lexer_ctx *lex_ctx);
  4346. DUK_INTERNAL_DECL void duk_lexer_setpoint(duk_lexer_ctx *lex_ctx, duk_lexer_point *pt);
  4347. DUK_INTERNAL_DECL
  4348. void duk_lexer_parse_js_input_element(duk_lexer_ctx *lex_ctx,
  4349. duk_token *out_token,
  4350. duk_bool_t strict_mode,
  4351. duk_bool_t regexp_mode);
  4352. #ifdef DUK_USE_REGEXP_SUPPORT
  4353. DUK_INTERNAL_DECL void duk_lexer_parse_re_token(duk_lexer_ctx *lex_ctx, duk_re_token *out_token);
  4354. DUK_INTERNAL_DECL void duk_lexer_parse_re_ranges(duk_lexer_ctx *lex_ctx, duk_re_range_callback gen_range, void *userdata);
  4355. #endif /* DUK_USE_REGEXP_SUPPORT */
  4356. #endif /* DUK_LEXER_H_INCLUDED */
  4357. #line 1 "duk_js_compiler.h"
  4358. /*
  4359. * Ecmascript compiler.
  4360. */
  4361. #ifndef DUK_JS_COMPILER_H_INCLUDED
  4362. #define DUK_JS_COMPILER_H_INCLUDED
  4363. /* ecmascript compiler limits */
  4364. #if defined(DUK_USE_DEEP_C_STACK)
  4365. #define DUK_COMPILER_RECURSION_LIMIT 2500L
  4366. #else
  4367. #define DUK_COMPILER_RECURSION_LIMIT 50L
  4368. #endif
  4369. #define DUK_COMPILER_TOKEN_LIMIT 100000000L /* 1e8: protects against deeply nested inner functions */
  4370. /* maximum loopcount for peephole optimization */
  4371. #define DUK_COMPILER_PEEPHOLE_MAXITER 3
  4372. /* maximum bytecode length in instructions */
  4373. #define DUK_COMPILER_MAX_BYTECODE_LENGTH (256L * 1024L * 1024L) /* 1 GB */
  4374. /*
  4375. * Compiler intermediate values
  4376. *
  4377. * Intermediate values describe either plain values (e.g. strings or
  4378. * numbers) or binary operations which have not yet been coerced into
  4379. * either a left-hand-side or right-hand-side role (e.g. object property).
  4380. */
  4381. #define DUK_IVAL_NONE 0 /* no value */
  4382. #define DUK_IVAL_PLAIN 1 /* register, constant, or value */
  4383. #define DUK_IVAL_ARITH 2 /* binary arithmetic; DUK_OP_ADD, DUK_OP_EQ, other binary ops */
  4384. #define DUK_IVAL_ARITH_EXTRAOP 3 /* binary arithmetic using extraops; DUK_EXTRAOP_INSTOF etc */
  4385. #define DUK_IVAL_PROP 4 /* property access */
  4386. #define DUK_IVAL_VAR 5 /* variable access */
  4387. #define DUK_ISPEC_NONE 0 /* no value */
  4388. #define DUK_ISPEC_VALUE 1 /* value resides in 'valstack_idx' */
  4389. #define DUK_ISPEC_REGCONST 2 /* value resides in a register or constant */
  4390. /* bit mask which indicates that a regconst is a constant instead of a register */
  4391. #define DUK_JS_CONST_MARKER 0x80000000UL
  4392. /* type to represent a reg/const reference during compilation */
  4393. typedef duk_uint32_t duk_regconst_t;
  4394. /* type to represent a straight register reference, with <0 indicating none */
  4395. typedef duk_int32_t duk_reg_t;
  4396. typedef struct {
  4397. duk_small_uint_t t; /* DUK_ISPEC_XXX */
  4398. duk_regconst_t regconst;
  4399. duk_idx_t valstack_idx; /* always set; points to a reserved valstack slot */
  4400. } duk_ispec;
  4401. typedef struct {
  4402. /*
  4403. * PLAIN: x1
  4404. * ARITH: x1 <op> x2
  4405. * PROP: x1.x2
  4406. * VAR: x1 (name)
  4407. */
  4408. /* XXX: can be optimized for smaller footprint esp. on 32-bit environments */
  4409. duk_small_uint_t t; /* DUK_IVAL_XXX */
  4410. duk_small_uint_t op; /* bytecode opcode (or extraop) for binary ops */
  4411. duk_ispec x1;
  4412. duk_ispec x2;
  4413. } duk_ivalue;
  4414. /*
  4415. * Bytecode instruction representation during compilation
  4416. *
  4417. * Contains the actual instruction and (optionally) debug info.
  4418. */
  4419. struct duk_compiler_instr {
  4420. duk_instr_t ins;
  4421. #if defined(DUK_USE_PC2LINE)
  4422. duk_uint32_t line;
  4423. #endif
  4424. };
  4425. /*
  4426. * Compiler state
  4427. */
  4428. #define DUK_LABEL_FLAG_ALLOW_BREAK (1 << 0)
  4429. #define DUK_LABEL_FLAG_ALLOW_CONTINUE (1 << 1)
  4430. #define DUK_DECL_TYPE_VAR 0
  4431. #define DUK_DECL_TYPE_FUNC 1
  4432. /* XXX: optimize to 16 bytes */
  4433. typedef struct {
  4434. duk_small_uint_t flags;
  4435. duk_int_t label_id; /* numeric label_id (-1 reserved as marker) */
  4436. duk_hstring *h_label; /* borrowed label name */
  4437. duk_int_t catch_depth; /* catch depth at point of definition */
  4438. duk_int_t pc_label; /* pc of label statement:
  4439. * pc+1: break jump site
  4440. * pc+2: continue jump site
  4441. */
  4442. /* Fast jumps (which avoid longjmp) jump directly to the jump sites
  4443. * which are always known even while the iteration/switch statement
  4444. * is still being parsed. A final peephole pass "straightens out"
  4445. * the jumps.
  4446. */
  4447. } duk_labelinfo;
  4448. /* Compiling state of one function, eventually converted to duk_hcompiledfunction */
  4449. struct duk_compiler_func {
  4450. /* These pointers are at the start of the struct so that they pack
  4451. * nicely. Mixing pointers and integer values is bad on some
  4452. * platforms (e.g. if int is 32 bits and pointers are 64 bits).
  4453. */
  4454. duk_hstring *h_name; /* function name (borrowed reference), ends up in _name */
  4455. duk_hbuffer_dynamic *h_code; /* C array of duk_compiler_instr */
  4456. duk_hobject *h_consts; /* array */
  4457. duk_hobject *h_funcs; /* array of function templates: [func1, offset1, line1, func2, offset2, line2]
  4458. * offset/line points to closing brace to allow skipping on pass 2
  4459. */
  4460. duk_hobject *h_decls; /* array of declarations: [ name1, val1, name2, val2, ... ]
  4461. * valN = (typeN) | (fnum << 8), where fnum is inner func number (0 for vars)
  4462. * record function and variable declarations in pass 1
  4463. */
  4464. duk_hobject *h_labelnames; /* array of active label names */
  4465. duk_hbuffer_dynamic *h_labelinfos; /* C array of duk_labelinfo */
  4466. duk_hobject *h_argnames; /* array of formal argument names (-> _Formals) */
  4467. duk_hobject *h_varmap; /* variable map for pass 2 (identifier -> register number or null (unmapped)) */
  4468. /* value stack indices for tracking objects */
  4469. duk_idx_t code_idx;
  4470. duk_idx_t consts_idx;
  4471. duk_idx_t funcs_idx;
  4472. duk_idx_t decls_idx;
  4473. duk_idx_t labelnames_idx;
  4474. duk_idx_t labelinfos_idx;
  4475. duk_idx_t argnames_idx;
  4476. duk_idx_t varmap_idx;
  4477. /* temp reg handling */
  4478. duk_reg_t temp_first; /* first register that is a temporary (below: variables) */
  4479. duk_reg_t temp_next; /* next temporary register to allocate */
  4480. duk_reg_t temp_max; /* highest value of temp_reg (temp_max - 1 is highest used reg) */
  4481. /* shuffle registers if large number of regs/consts */
  4482. duk_reg_t shuffle1;
  4483. duk_reg_t shuffle2;
  4484. duk_reg_t shuffle3;
  4485. /* stats for current expression being parsed */
  4486. duk_int_t nud_count;
  4487. duk_int_t led_count;
  4488. duk_int_t paren_level; /* parenthesis count, 0 = top level */
  4489. duk_bool_t expr_lhs; /* expression is left-hand-side compatible */
  4490. duk_bool_t allow_in; /* current paren level allows 'in' token */
  4491. /* misc */
  4492. duk_int_t stmt_next; /* statement id allocation (running counter) */
  4493. duk_int_t label_next; /* label id allocation (running counter) */
  4494. duk_int_t catch_depth; /* catch stack depth */
  4495. duk_int_t with_depth; /* with stack depth (affects identifier lookups) */
  4496. duk_int_t fnum_next; /* inner function numbering */
  4497. duk_int_t num_formals; /* number of formal arguments */
  4498. duk_reg_t reg_stmt_value; /* register for writing value of 'non-empty' statements (global or eval code), -1 is marker */
  4499. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  4500. duk_int_t min_line; /* XXX: typing (duk_hcompiledfunction has duk_uint32_t) */
  4501. duk_int_t max_line;
  4502. #endif
  4503. /* status booleans */
  4504. duk_bool_t is_function; /* is an actual function (not global/eval code) */
  4505. duk_bool_t is_eval; /* is eval code */
  4506. duk_bool_t is_global; /* is global code */
  4507. duk_bool_t is_setget; /* is a setter/getter */
  4508. duk_bool_t is_decl; /* is a function declaration (as opposed to function expression) */
  4509. duk_bool_t is_strict; /* function is strict */
  4510. duk_bool_t is_notail; /* function must not be tailcalled */
  4511. duk_bool_t in_directive_prologue; /* parsing in "directive prologue", recognize directives */
  4512. duk_bool_t in_scanning; /* parsing in "scanning" phase (first pass) */
  4513. duk_bool_t may_direct_eval; /* function may call direct eval */
  4514. duk_bool_t id_access_arguments; /* function refers to 'arguments' identifier */
  4515. duk_bool_t id_access_slow; /* function makes one or more slow path accesses */
  4516. duk_bool_t is_arguments_shadowed; /* argument/function declaration shadows 'arguments' */
  4517. duk_bool_t needs_shuffle; /* function needs shuffle registers */
  4518. duk_bool_t reject_regexp_in_adv; /* reject RegExp literal on next advance() call; needed for handling IdentifierName productions */
  4519. };
  4520. struct duk_compiler_ctx {
  4521. duk_hthread *thr;
  4522. /* filename being compiled (ends up in functions' '_filename' property) */
  4523. duk_hstring *h_filename; /* borrowed reference */
  4524. /* lexing (tokenization) state (contains two valstack slot indices) */
  4525. duk_lexer_ctx lex;
  4526. /* current and previous token for parsing */
  4527. duk_token prev_token;
  4528. duk_token curr_token;
  4529. duk_idx_t tok11_idx; /* curr_token slot1 (matches 'lex' slot1_idx) */
  4530. duk_idx_t tok12_idx; /* curr_token slot2 (matches 'lex' slot2_idx) */
  4531. duk_idx_t tok21_idx; /* prev_token slot1 */
  4532. duk_idx_t tok22_idx; /* prev_token slot2 */
  4533. /* recursion limit */
  4534. duk_int_t recursion_depth;
  4535. duk_int_t recursion_limit;
  4536. /* code emission temporary */
  4537. duk_int_t emit_jumpslot_pc;
  4538. /* current function being compiled (embedded instead of pointer for more compact access) */
  4539. duk_compiler_func curr_func;
  4540. };
  4541. /*
  4542. * Prototypes
  4543. */
  4544. #define DUK_JS_COMPILE_FLAG_EVAL (1 << 0) /* source is eval code (not program) */
  4545. #define DUK_JS_COMPILE_FLAG_STRICT (1 << 1) /* strict outer context */
  4546. #define DUK_JS_COMPILE_FLAG_FUNCEXPR (1 << 2) /* source is a function expression (used for Function constructor) */
  4547. DUK_INTERNAL_DECL void duk_js_compile(duk_hthread *thr, const duk_uint8_t *src_buffer, duk_size_t src_length, duk_small_uint_t flags);
  4548. #endif /* DUK_JS_COMPILER_H_INCLUDED */
  4549. #line 1 "duk_regexp.h"
  4550. /*
  4551. * Regular expression structs, constants, and bytecode defines.
  4552. */
  4553. #ifndef DUK_REGEXP_H_INCLUDED
  4554. #define DUK_REGEXP_H_INCLUDED
  4555. /* maximum bytecode copies for {n,m} quantifiers */
  4556. #define DUK_RE_MAX_ATOM_COPIES 1000
  4557. /* regexp compilation limits */
  4558. #if defined(DUK_USE_DEEP_C_STACK)
  4559. #define DUK_RE_COMPILE_RECURSION_LIMIT 10000
  4560. #else
  4561. #define DUK_RE_COMPILE_RECURSION_LIMIT 100
  4562. #endif
  4563. #define DUK_RE_COMPILE_TOKEN_LIMIT 100000000L /* 1e8 */
  4564. /* regexp execution limits */
  4565. #if defined(DUK_USE_DEEP_C_STACK)
  4566. #define DUK_RE_EXECUTE_RECURSION_LIMIT 10000
  4567. #else
  4568. #define DUK_RE_EXECUTE_RECURSION_LIMIT 100
  4569. #endif
  4570. #define DUK_RE_EXECUTE_STEPS_LIMIT 1000000000L /* 1e9 */
  4571. /* regexp opcodes */
  4572. #define DUK_REOP_MATCH 1
  4573. #define DUK_REOP_CHAR 2
  4574. #define DUK_REOP_PERIOD 3
  4575. #define DUK_REOP_RANGES 4
  4576. #define DUK_REOP_INVRANGES 5
  4577. #define DUK_REOP_JUMP 6
  4578. #define DUK_REOP_SPLIT1 7
  4579. #define DUK_REOP_SPLIT2 8
  4580. #define DUK_REOP_SQMINIMAL 9
  4581. #define DUK_REOP_SQGREEDY 10
  4582. #define DUK_REOP_SAVE 11
  4583. #define DUK_REOP_WIPERANGE 12
  4584. #define DUK_REOP_LOOKPOS 13
  4585. #define DUK_REOP_LOOKNEG 14
  4586. #define DUK_REOP_BACKREFERENCE 15
  4587. #define DUK_REOP_ASSERT_START 16
  4588. #define DUK_REOP_ASSERT_END 17
  4589. #define DUK_REOP_ASSERT_WORD_BOUNDARY 18
  4590. #define DUK_REOP_ASSERT_NOT_WORD_BOUNDARY 19
  4591. /* flags */
  4592. #define DUK_RE_FLAG_GLOBAL (1 << 0)
  4593. #define DUK_RE_FLAG_IGNORE_CASE (1 << 1)
  4594. #define DUK_RE_FLAG_MULTILINE (1 << 2)
  4595. struct duk_re_matcher_ctx {
  4596. duk_hthread *thr;
  4597. duk_uint32_t re_flags;
  4598. const duk_uint8_t *input;
  4599. const duk_uint8_t *input_end;
  4600. const duk_uint8_t *bytecode;
  4601. const duk_uint8_t *bytecode_end;
  4602. const duk_uint8_t **saved; /* allocated from valstack (fixed buffer) */
  4603. duk_uint32_t nsaved;
  4604. duk_uint32_t recursion_depth;
  4605. duk_uint32_t recursion_limit;
  4606. duk_uint32_t steps_count;
  4607. duk_uint32_t steps_limit;
  4608. };
  4609. struct duk_re_compiler_ctx {
  4610. duk_hthread *thr;
  4611. duk_uint32_t re_flags;
  4612. duk_lexer_ctx lex;
  4613. duk_re_token curr_token;
  4614. duk_hbuffer_dynamic *buf;
  4615. duk_uint32_t captures; /* highest capture number emitted so far (used as: ++captures) */
  4616. duk_uint32_t highest_backref;
  4617. duk_uint32_t recursion_depth;
  4618. duk_uint32_t recursion_limit;
  4619. duk_uint32_t nranges; /* internal temporary value, used for char classes */
  4620. };
  4621. /*
  4622. * Prototypes
  4623. */
  4624. DUK_INTERNAL_DECL void duk_regexp_compile(duk_hthread *thr);
  4625. DUK_INTERNAL_DECL void duk_regexp_create_instance(duk_hthread *thr);
  4626. DUK_INTERNAL_DECL void duk_regexp_match(duk_hthread *thr);
  4627. DUK_INTERNAL_DECL void duk_regexp_match_force_global(duk_hthread *thr); /* hacky helper for String.prototype.split() */
  4628. #endif /* DUK_REGEXP_H_INCLUDED */
  4629. #line 1 "duk_tval.h"
  4630. /*
  4631. * Tagged type definition (duk_tval) and accessor macros.
  4632. *
  4633. * Access all fields through the accessor macros, as the representation
  4634. * is quite tricky.
  4635. *
  4636. * There are two packed type alternatives: an 8-byte representation
  4637. * based on an IEEE double (preferred for compactness), and a 12-byte
  4638. * representation (portability). The latter is needed also in e.g.
  4639. * 64-bit environments (it usually pads to 16 bytes per value).
  4640. *
  4641. * Selecting the tagged type format involves many trade-offs (memory
  4642. * use, size and performance of generated code, portability, etc),
  4643. * see doc/types.txt for a detailed discussion (especially of how the
  4644. * IEEE double format is used to pack tagged values).
  4645. *
  4646. * NB: because macro arguments are often expressions, macros should
  4647. * avoid evaluating their argument more than once.
  4648. */
  4649. #ifndef DUK_TVAL_H_INCLUDED
  4650. #define DUK_TVAL_H_INCLUDED
  4651. /* sanity */
  4652. #if !defined(DUK_USE_DOUBLE_LE) && !defined(DUK_USE_DOUBLE_ME) && !defined(DUK_USE_DOUBLE_BE)
  4653. #error unsupported: cannot determine byte order variant
  4654. #endif
  4655. #ifdef DUK_USE_PACKED_TVAL
  4656. /* ======================================================================== */
  4657. /*
  4658. * Packed 8-byte representation
  4659. */
  4660. /* sanity */
  4661. #if !defined(DUK_USE_PACKED_TVAL_POSSIBLE)
  4662. #error packed representation not supported
  4663. #endif
  4664. /* use duk_double_union as duk_tval directly */
  4665. typedef union duk_double_union duk_tval;
  4666. /* tags */
  4667. #define DUK_TAG_NORMALIZED_NAN 0x7ff8UL /* the NaN variant we use */
  4668. /* avoid tag 0xfff0, no risk of confusion with negative infinity */
  4669. #if defined(DUK_USE_FASTINT)
  4670. #define DUK_TAG_FASTINT 0xfff1UL /* embed: integer value */
  4671. #endif
  4672. #define DUK_TAG_UNDEFINED 0xfff2UL /* embed: 0 or 1 (normal or unused) */
  4673. #define DUK_TAG_NULL 0xfff3UL /* embed: nothing */
  4674. #define DUK_TAG_BOOLEAN 0xfff4UL /* embed: 0 or 1 (false or true) */
  4675. /* DUK_TAG_NUMBER would logically go here, but it has multiple 'tags' */
  4676. #define DUK_TAG_POINTER 0xfff5UL /* embed: void ptr */
  4677. #define DUK_TAG_LIGHTFUNC 0xfff6UL /* embed: func ptr */
  4678. #define DUK_TAG_STRING 0xfff7UL /* embed: duk_hstring ptr */
  4679. #define DUK_TAG_OBJECT 0xfff8UL /* embed: duk_hobject ptr */
  4680. #define DUK_TAG_BUFFER 0xfff9UL /* embed: duk_hbuffer ptr */
  4681. /* for convenience */
  4682. #define DUK_XTAG_UNDEFINED_ACTUAL 0xfff20000UL
  4683. #define DUK_XTAG_UNDEFINED_UNUSED 0xfff20001UL
  4684. #define DUK_XTAG_NULL 0xfff30000UL
  4685. #define DUK_XTAG_BOOLEAN_FALSE 0xfff40000UL
  4686. #define DUK_XTAG_BOOLEAN_TRUE 0xfff40001UL
  4687. /* two casts to avoid gcc warning: "warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]" */
  4688. #ifdef DUK_USE_64BIT_OPS
  4689. #ifdef DUK_USE_DOUBLE_ME
  4690. #define DUK__TVAL_SET_TAGGEDPOINTER(v,h,tag) do { \
  4691. (v)->ull[DUK_DBL_IDX_ULL0] = (((duk_uint64_t) (tag)) << 16) | (((duk_uint64_t) (duk_uint32_t) (h)) << 32); \
  4692. } while (0)
  4693. #else
  4694. #define DUK__TVAL_SET_TAGGEDPOINTER(v,h,tag) do { \
  4695. (v)->ull[DUK_DBL_IDX_ULL0] = (((duk_uint64_t) (tag)) << 48) | ((duk_uint64_t) (duk_uint32_t) (h)); \
  4696. } while (0)
  4697. #endif
  4698. #else /* DUK_USE_64BIT_OPS */
  4699. #define DUK__TVAL_SET_TAGGEDPOINTER(v,h,tag) do { \
  4700. (v)->ui[DUK_DBL_IDX_UI0] = ((duk_uint32_t) (tag)) << 16; \
  4701. (v)->ui[DUK_DBL_IDX_UI1] = (duk_uint32_t) (h); \
  4702. } while (0)
  4703. #endif /* DUK_USE_64BIT_OPS */
  4704. #ifdef DUK_USE_64BIT_OPS
  4705. /* Double casting for pointer to avoid gcc warning (cast from pointer to integer of different size) */
  4706. #ifdef DUK_USE_DOUBLE_ME
  4707. #define DUK__TVAL_SET_LIGHTFUNC(v,fp,flags) do { \
  4708. (v)->ull[DUK_DBL_IDX_ULL0] = (((duk_uint64_t) DUK_TAG_LIGHTFUNC) << 16) | \
  4709. ((duk_uint64_t) (flags)) | \
  4710. (((duk_uint64_t) (duk_uint32_t) (fp)) << 32); \
  4711. } while (0)
  4712. #else
  4713. #define DUK__TVAL_SET_LIGHTFUNC(v,fp,flags) do { \
  4714. (v)->ull[DUK_DBL_IDX_ULL0] = (((duk_uint64_t) DUK_TAG_LIGHTFUNC) << 48) | \
  4715. (((duk_uint64_t) (flags)) << 32) | \
  4716. ((duk_uint64_t) (duk_uint32_t) (fp)); \
  4717. } while (0)
  4718. #endif
  4719. #else /* DUK_USE_64BIT_OPS */
  4720. #define DUK__TVAL_SET_LIGHTFUNC(v,fp,flags) do { \
  4721. (v)->ui[DUK_DBL_IDX_UI0] = (((duk_uint32_t) DUK_TAG_LIGHTFUNC) << 16) | ((duk_uint32_t) (flags)); \
  4722. (v)->ui[DUK_DBL_IDX_UI1] = (duk_uint32_t) (fp); \
  4723. } while (0)
  4724. #endif /* DUK_USE_64BIT_OPS */
  4725. #if defined(DUK_USE_FASTINT)
  4726. /* Note: masking is done for 'i' to deal with negative numbers correctly */
  4727. #ifdef DUK_USE_DOUBLE_ME
  4728. #define DUK__TVAL_SET_FASTINT(v,i) do { \
  4729. (v)->ui[DUK_DBL_IDX_UI0] = ((duk_uint32_t) DUK_TAG_FASTINT) << 16 | (((duk_uint32_t) ((i) >> 32)) & 0x0000ffffUL); \
  4730. (v)->ui[DUK_DBL_IDX_UI1] = (duk_uint32_t) (i); \
  4731. } while (0)
  4732. #define DUK__TVAL_SET_FASTINT_U32(v,i) do { \
  4733. (v)->ui[DUK_DBL_IDX_UI0] = ((duk_uint32_t) DUK_TAG_FASTINT) << 16; \
  4734. (v)->ui[DUK_DBL_IDX_UI1] = (duk_uint32_t) (i); \
  4735. } while (0)
  4736. #else
  4737. #define DUK__TVAL_SET_FASTINT(v,i) do { \
  4738. (v)->ull[DUK_DBL_IDX_ULL0] = (((duk_uint64_t) DUK_TAG_FASTINT) << 48) | (((duk_uint64_t) (i)) & 0x0000ffffffffffffULL); \
  4739. } while (0)
  4740. #define DUK__TVAL_SET_FASTINT_U32(v,i) do { \
  4741. (v)->ull[DUK_DBL_IDX_ULL0] = (((duk_uint64_t) DUK_TAG_FASTINT) << 48) | (duk_uint64_t) (i); \
  4742. } while (0)
  4743. #endif
  4744. #define DUK__TVAL_SET_FASTINT_I32(v,i) do { \
  4745. duk_int64_t duk__tmp = (duk_int64_t) (i); \
  4746. DUK_TVAL_SET_FASTINT((v), duk__tmp); \
  4747. } while (0)
  4748. /* XXX: clumsy sign extend and masking of 16 topmost bits */
  4749. #ifdef DUK_USE_DOUBLE_ME
  4750. #define DUK__TVAL_GET_FASTINT(v) (((duk_int64_t) ((((duk_uint64_t) (v)->ui[DUK_DBL_IDX_UI0]) << 32) | ((duk_uint64_t) (v)->ui[DUK_DBL_IDX_UI1]))) << 16 >> 16)
  4751. #else
  4752. #define DUK__TVAL_GET_FASTINT(v) ((((duk_int64_t) (v)->ull[DUK_DBL_IDX_ULL0]) << 16) >> 16)
  4753. #endif
  4754. #define DUK__TVAL_GET_FASTINT_U32(v) ((v)->ui[DUK_DBL_IDX_UI1])
  4755. #define DUK__TVAL_GET_FASTINT_I32(v) ((duk_int32_t) (v)->ui[DUK_DBL_IDX_UI1])
  4756. #endif /* DUK_USE_FASTINT */
  4757. #define DUK_TVAL_SET_UNDEFINED_ACTUAL(v) DUK_DBLUNION_SET_HIGH32((v), DUK_XTAG_UNDEFINED_ACTUAL)
  4758. #define DUK_TVAL_SET_UNDEFINED_UNUSED(v) DUK_DBLUNION_SET_HIGH32((v), DUK_XTAG_UNDEFINED_UNUSED)
  4759. /* Note: 16-bit initializer suffices (unlike for undefined/boolean) */
  4760. #define DUK_TVAL_SET_NULL(v) do { \
  4761. (v)->us[DUK_DBL_IDX_US0] = (duk_uint16_t) DUK_TAG_NULL; \
  4762. } while (0)
  4763. #define DUK_TVAL_SET_BOOLEAN(v,val) DUK_DBLUNION_SET_HIGH32((v), (((duk_uint32_t) DUK_TAG_BOOLEAN) << 16) | ((duk_uint32_t) (val)))
  4764. #define DUK_TVAL_SET_NAN(v) DUK_DBLUNION_SET_NAN_FULL((v))
  4765. /* Assumes that caller has normalized NaNs, otherwise trouble ahead. */
  4766. #if defined(DUK_USE_FASTINT)
  4767. #define DUK_TVAL_SET_DOUBLE(v,d) DUK_DBLUNION_SET_DOUBLE((v), (d))
  4768. #define DUK_TVAL_SET_FASTINT(v,i) DUK__TVAL_SET_FASTINT((v), (i))
  4769. #define DUK_TVAL_SET_FASTINT_I32(v,i) DUK__TVAL_SET_FASTINT_I32((v), (i))
  4770. #define DUK_TVAL_SET_FASTINT_U32(v,i) DUK__TVAL_SET_FASTINT_U32((v), (i))
  4771. #define DUK_TVAL_SET_NUMBER_CHKFAST(v,d) duk_tval_set_number_chkfast((v), (d))
  4772. #define DUK_TVAL_SET_NUMBER(v,d) DUK_DBLUNION_SET_DOUBLE((v), (d))
  4773. #define DUK_TVAL_CHKFAST_INPLACE(v) do { \
  4774. duk_tval *duk__tv; \
  4775. duk_double_t duk__d; \
  4776. duk__tv = (v); \
  4777. if (DUK_TVAL_IS_DOUBLE(duk__tv)) { \
  4778. duk__d = DUK_TVAL_GET_DOUBLE(duk__tv); \
  4779. DUK_TVAL_SET_NUMBER_CHKFAST(duk__tv, duk__d); \
  4780. } \
  4781. } while (0)
  4782. #else
  4783. #define DUK_TVAL_SET_NUMBER(v,d) DUK_DBLUNION_SET_DOUBLE((v), (d))
  4784. #define DUK_TVAL_SET_NUMBER_CHKFAST(v,d) DUK_TVAL_SET_NUMBER((v), (d))
  4785. #define DUK_TVAL_SET_DOUBLE(v,d) DUK_TVAL_SET_NUMBER((v), (d))
  4786. #define DUK_TVAL_CHKFAST_INPLACE(v) do { } while (0)
  4787. #endif
  4788. #define DUK_TVAL_SET_LIGHTFUNC(v,fp,flags) DUK__TVAL_SET_LIGHTFUNC((v), (fp), (flags))
  4789. #define DUK_TVAL_SET_STRING(v,h) DUK__TVAL_SET_TAGGEDPOINTER((v), (h), DUK_TAG_STRING)
  4790. #define DUK_TVAL_SET_OBJECT(v,h) DUK__TVAL_SET_TAGGEDPOINTER((v), (h), DUK_TAG_OBJECT)
  4791. #define DUK_TVAL_SET_BUFFER(v,h) DUK__TVAL_SET_TAGGEDPOINTER((v), (h), DUK_TAG_BUFFER)
  4792. #define DUK_TVAL_SET_POINTER(v,p) DUK__TVAL_SET_TAGGEDPOINTER((v), (p), DUK_TAG_POINTER)
  4793. #define DUK_TVAL_SET_TVAL(v,x) do { *(v) = *(x); } while (0)
  4794. /* getters */
  4795. #define DUK_TVAL_GET_BOOLEAN(v) ((int) (v)->us[DUK_DBL_IDX_US1])
  4796. #if defined(DUK_USE_FASTINT)
  4797. #define DUK_TVAL_GET_DOUBLE(v) ((v)->d)
  4798. #define DUK_TVAL_GET_FASTINT(v) DUK__TVAL_GET_FASTINT((v))
  4799. #define DUK_TVAL_GET_FASTINT_U32(v) DUK__TVAL_GET_FASTINT_U32((v))
  4800. #define DUK_TVAL_GET_FASTINT_I32(v) DUK__TVAL_GET_FASTINT_I32((v))
  4801. #define DUK_TVAL_GET_NUMBER(v) duk_tval_get_number_packed((v))
  4802. #else
  4803. #define DUK_TVAL_GET_NUMBER(v) ((v)->d)
  4804. #define DUK_TVAL_GET_DOUBLE(v) ((v)->d)
  4805. #endif
  4806. #define DUK_TVAL_GET_LIGHTFUNC(v,out_fp,out_flags) do { \
  4807. (out_flags) = (v)->ui[DUK_DBL_IDX_UI0] & 0xffffUL; \
  4808. (out_fp) = (duk_c_function) (v)->ui[DUK_DBL_IDX_UI1]; \
  4809. } while (0)
  4810. #define DUK_TVAL_GET_LIGHTFUNC_FUNCPTR(v) ((duk_c_function) ((v)->ui[DUK_DBL_IDX_UI1]))
  4811. #define DUK_TVAL_GET_LIGHTFUNC_FLAGS(v) (((int) (v)->ui[DUK_DBL_IDX_UI0]) & 0xffffUL)
  4812. #define DUK_TVAL_GET_STRING(v) ((duk_hstring *) (v)->vp[DUK_DBL_IDX_VP1])
  4813. #define DUK_TVAL_GET_OBJECT(v) ((duk_hobject *) (v)->vp[DUK_DBL_IDX_VP1])
  4814. #define DUK_TVAL_GET_BUFFER(v) ((duk_hbuffer *) (v)->vp[DUK_DBL_IDX_VP1])
  4815. #define DUK_TVAL_GET_POINTER(v) ((void *) (v)->vp[DUK_DBL_IDX_VP1])
  4816. #define DUK_TVAL_GET_HEAPHDR(v) ((duk_heaphdr *) (v)->vp[DUK_DBL_IDX_VP1])
  4817. /* decoding */
  4818. #define DUK_TVAL_GET_TAG(v) ((duk_small_uint_t) (v)->us[DUK_DBL_IDX_US0])
  4819. #define DUK_TVAL_IS_UNDEFINED(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_UNDEFINED)
  4820. #define DUK_TVAL_IS_UNDEFINED_ACTUAL(v) ((v)->ui[DUK_DBL_IDX_UI0] == DUK_XTAG_UNDEFINED_ACTUAL)
  4821. #define DUK_TVAL_IS_UNDEFINED_UNUSED(v) ((v)->ui[DUK_DBL_IDX_UI0] == DUK_XTAG_UNDEFINED_UNUSED)
  4822. #define DUK_TVAL_IS_NULL(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_NULL)
  4823. #define DUK_TVAL_IS_BOOLEAN(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_BOOLEAN)
  4824. #define DUK_TVAL_IS_BOOLEAN_TRUE(v) ((v)->ui[DUK_DBL_IDX_UI0] == DUK_XTAG_BOOLEAN_TRUE)
  4825. #define DUK_TVAL_IS_BOOLEAN_FALSE(v) ((v)->ui[DUK_DBL_IDX_UI0] == DUK_XTAG_BOOLEAN_FALSE)
  4826. #define DUK_TVAL_IS_LIGHTFUNC(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_LIGHTFUNC)
  4827. #define DUK_TVAL_IS_STRING(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_STRING)
  4828. #define DUK_TVAL_IS_OBJECT(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_OBJECT)
  4829. #define DUK_TVAL_IS_BUFFER(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_BUFFER)
  4830. #define DUK_TVAL_IS_POINTER(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_POINTER)
  4831. #if defined(DUK_USE_FASTINT)
  4832. /* 0xfff0 is -Infinity */
  4833. #define DUK_TVAL_IS_DOUBLE(v) (DUK_TVAL_GET_TAG((v)) <= 0xfff0UL)
  4834. #define DUK_TVAL_IS_FASTINT(v) (DUK_TVAL_GET_TAG((v)) == DUK_TAG_FASTINT)
  4835. #define DUK_TVAL_IS_NUMBER(v) (DUK_TVAL_GET_TAG((v)) <= 0xfff1UL)
  4836. #else
  4837. #define DUK_TVAL_IS_NUMBER(v) (DUK_TVAL_GET_TAG((v)) <= 0xfff0UL)
  4838. #define DUK_TVAL_IS_DOUBLE(v) DUK_TVAL_IS_NUMBER((v))
  4839. #endif
  4840. #define DUK_TVAL_IS_HEAP_ALLOCATED(v) (DUK_TVAL_GET_TAG((v)) >= DUK_TAG_STRING)
  4841. #if defined(DUK_USE_FASTINT)
  4842. /* Inlining is only effective in a single file build. */
  4843. DUK_INTERNAL_DECL DUK_ALWAYS_INLINE duk_double_t duk_tval_get_number_packed(duk_tval *tv);
  4844. #endif
  4845. #else /* DUK_USE_PACKED_TVAL */
  4846. /* ======================================================================== */
  4847. /*
  4848. * Portable 12-byte representation
  4849. */
  4850. /* Note: not initializing all bytes is normally not an issue: Duktape won't
  4851. * read or use the uninitialized bytes so valgrind won't issue warnings.
  4852. * In some special cases a harmless valgrind warning may be issued though.
  4853. * For example, the DumpHeap debugger command writes out a compiled function's
  4854. * 'data' area as is, including any uninitialized bytes, which causes a
  4855. * valgrind warning.
  4856. */
  4857. typedef struct duk_tval_struct duk_tval;
  4858. struct duk_tval_struct {
  4859. duk_small_uint_t t;
  4860. duk_small_uint_t v_extra;
  4861. union {
  4862. duk_double_t d;
  4863. duk_small_int_t i;
  4864. #if defined(DUK_USE_FASTINT)
  4865. duk_int64_t fi; /* if present, forces 16-byte duk_tval */
  4866. #endif
  4867. void *voidptr;
  4868. duk_hstring *hstring;
  4869. duk_hobject *hobject;
  4870. duk_hcompiledfunction *hcompiledfunction;
  4871. duk_hnativefunction *hnativefunction;
  4872. duk_hthread *hthread;
  4873. duk_hbuffer *hbuffer;
  4874. duk_heaphdr *heaphdr;
  4875. duk_c_function lightfunc;
  4876. } v;
  4877. };
  4878. #define DUK__TAG_NUMBER 0 /* not exposed */
  4879. #if defined(DUK_USE_FASTINT)
  4880. #define DUK_TAG_FASTINT 1
  4881. #endif
  4882. #define DUK_TAG_UNDEFINED 2
  4883. #define DUK_TAG_NULL 3
  4884. #define DUK_TAG_BOOLEAN 4
  4885. #define DUK_TAG_POINTER 5
  4886. #define DUK_TAG_LIGHTFUNC 6
  4887. #define DUK_TAG_STRING 7
  4888. #define DUK_TAG_OBJECT 8
  4889. #define DUK_TAG_BUFFER 9
  4890. /* DUK__TAG_NUMBER is intentionally first, as it is the default clause in code
  4891. * to support the 8-byte representation. Further, it is a non-heap-allocated
  4892. * type so it should come before DUK_TAG_STRING. Finally, it should not break
  4893. * the tag value ranges covered by case-clauses in a switch-case.
  4894. */
  4895. /* setters */
  4896. #define DUK_TVAL_SET_UNDEFINED_ACTUAL(tv) do { \
  4897. (tv)->t = DUK_TAG_UNDEFINED; \
  4898. (tv)->v.i = 0; \
  4899. } while (0)
  4900. #define DUK_TVAL_SET_UNDEFINED_UNUSED(tv) do { \
  4901. (tv)->t = DUK_TAG_UNDEFINED; \
  4902. (tv)->v.i = 1; \
  4903. } while (0)
  4904. #define DUK_TVAL_SET_NULL(tv) do { \
  4905. (tv)->t = DUK_TAG_NULL; \
  4906. } while (0)
  4907. #define DUK_TVAL_SET_BOOLEAN(tv,val) do { \
  4908. (tv)->t = DUK_TAG_BOOLEAN; \
  4909. (tv)->v.i = (val); \
  4910. } while (0)
  4911. #if defined(DUK_USE_FASTINT)
  4912. #define DUK_TVAL_SET_DOUBLE(tv,val) do { \
  4913. (tv)->t = DUK__TAG_NUMBER; \
  4914. (tv)->v.d = (val); \
  4915. } while (0)
  4916. #define DUK_TVAL_SET_FASTINT(tv,val) do { \
  4917. (tv)->t = DUK_TAG_FASTINT; \
  4918. (tv)->v.fi = (val); \
  4919. } while (0)
  4920. #define DUK_TVAL_SET_FASTINT_U32(tv,val) do { \
  4921. (tv)->t = DUK_TAG_FASTINT; \
  4922. (tv)->v.fi = (duk_int64_t) (val); \
  4923. } while (0)
  4924. #define DUK_TVAL_SET_FASTINT_I32(tv,val) do { \
  4925. (tv)->t = DUK_TAG_FASTINT; \
  4926. (tv)->v.fi = (duk_int64_t) (val); \
  4927. } while (0)
  4928. #define DUK_TVAL_SET_NUMBER_CHKFAST(tv,d) \
  4929. duk_tval_set_number_chkfast((tv), (d))
  4930. #define DUK_TVAL_SET_NUMBER(tv,val) \
  4931. DUK_TVAL_SET_DOUBLE((tv), (val))
  4932. #define DUK_TVAL_CHKFAST_INPLACE(v) do { \
  4933. duk_tval *duk__tv; \
  4934. duk_double_t duk__d; \
  4935. duk__tv = (v); \
  4936. if (DUK_TVAL_IS_DOUBLE(duk__tv)) { \
  4937. duk__d = DUK_TVAL_GET_DOUBLE(duk__tv); \
  4938. DUK_TVAL_SET_NUMBER_CHKFAST(duk__tv, duk__d); \
  4939. } \
  4940. } while (0)
  4941. #else
  4942. #define DUK_TVAL_SET_NUMBER(tv,val) do { \
  4943. (tv)->t = DUK__TAG_NUMBER; \
  4944. (tv)->v.d = (val); \
  4945. } while (0)
  4946. #define DUK_TVAL_SET_NUMBER_CHKFAST(v,d) \
  4947. DUK_TVAL_SET_NUMBER((tv), (d))
  4948. #define DUK_TVAL_SET_DOUBLE(v,d) \
  4949. DUK_TVAL_SET_NUMBER((tv), (d))
  4950. #define DUK_TVAL_CHKFAST_INPLACE(v) do { } while (0)
  4951. #endif /* DUK_USE_FASTINT */
  4952. #define DUK_TVAL_SET_POINTER(tv,hptr) do { \
  4953. (tv)->t = DUK_TAG_POINTER; \
  4954. (tv)->v.voidptr = (hptr); \
  4955. } while (0)
  4956. #define DUK_TVAL_SET_LIGHTFUNC(tv,fp,flags) do { \
  4957. (tv)->t = DUK_TAG_LIGHTFUNC; \
  4958. (tv)->v_extra = (flags); \
  4959. (tv)->v.lightfunc = (duk_c_function) (fp); \
  4960. } while (0)
  4961. #define DUK_TVAL_SET_STRING(tv,hptr) do { \
  4962. (tv)->t = DUK_TAG_STRING; \
  4963. (tv)->v.hstring = (hptr); \
  4964. } while (0)
  4965. #define DUK_TVAL_SET_OBJECT(tv,hptr) do { \
  4966. (tv)->t = DUK_TAG_OBJECT; \
  4967. (tv)->v.hobject = (hptr); \
  4968. } while (0)
  4969. #define DUK_TVAL_SET_BUFFER(tv,hptr) do { \
  4970. (tv)->t = DUK_TAG_BUFFER; \
  4971. (tv)->v.hbuffer = (hptr); \
  4972. } while (0)
  4973. #define DUK_TVAL_SET_NAN(tv) do { \
  4974. /* in non-packed representation we don't care about which NaN is used */ \
  4975. (tv)->t = DUK__TAG_NUMBER; \
  4976. (tv)->v.d = DUK_DOUBLE_NAN; \
  4977. } while (0)
  4978. #define DUK_TVAL_SET_TVAL(v,x) do { *(v) = *(x); } while (0)
  4979. /* getters */
  4980. #define DUK_TVAL_GET_BOOLEAN(tv) ((tv)->v.i)
  4981. #if defined(DUK_USE_FASTINT)
  4982. #define DUK_TVAL_GET_DOUBLE(tv) ((tv)->v.d)
  4983. #define DUK_TVAL_GET_FASTINT(tv) ((tv)->v.fi)
  4984. #define DUK_TVAL_GET_FASTINT_U32(tv) ((duk_uint32_t) ((tv)->v.fi))
  4985. #define DUK_TVAL_GET_FASTINT_I32(tv) ((duk_int32_t) ((tv)->v.fi))
  4986. #if 0
  4987. #define DUK_TVAL_GET_NUMBER(tv) (DUK_TVAL_IS_FASTINT((tv)) ? \
  4988. (duk_double_t) DUK_TVAL_GET_FASTINT((tv)) : \
  4989. DUK_TVAL_GET_DOUBLE((tv)))
  4990. #define DUK_TVAL_GET_NUMBER(tv) duk_tval_get_number_unpacked((tv))
  4991. #else
  4992. /* This seems reasonable overall. */
  4993. #define DUK_TVAL_GET_NUMBER(tv) (DUK_TVAL_IS_FASTINT((tv)) ? \
  4994. duk_tval_get_number_unpacked_fastint((tv)) : \
  4995. DUK_TVAL_GET_DOUBLE((tv)))
  4996. #endif
  4997. #else
  4998. #define DUK_TVAL_GET_NUMBER(tv) ((tv)->v.d)
  4999. #define DUK_TVAL_GET_DOUBLE(tv) ((tv)->v.d)
  5000. #endif /* DUK_USE_FASTINT */
  5001. #define DUK_TVAL_GET_POINTER(tv) ((tv)->v.voidptr)
  5002. #define DUK_TVAL_GET_LIGHTFUNC(tv,out_fp,out_flags) do { \
  5003. (out_flags) = (duk_uint32_t) (tv)->v_extra; \
  5004. (out_fp) = (tv)->v.lightfunc; \
  5005. } while (0)
  5006. #define DUK_TVAL_GET_LIGHTFUNC_FUNCPTR(tv) ((tv)->v.lightfunc)
  5007. #define DUK_TVAL_GET_LIGHTFUNC_FLAGS(tv) ((duk_uint32_t) ((tv)->v_extra))
  5008. #define DUK_TVAL_GET_STRING(tv) ((tv)->v.hstring)
  5009. #define DUK_TVAL_GET_OBJECT(tv) ((tv)->v.hobject)
  5010. #define DUK_TVAL_GET_BUFFER(tv) ((tv)->v.hbuffer)
  5011. #define DUK_TVAL_GET_HEAPHDR(tv) ((tv)->v.heaphdr)
  5012. /* decoding */
  5013. #define DUK_TVAL_GET_TAG(tv) ((tv)->t)
  5014. #define DUK_TVAL_IS_UNDEFINED(tv) ((tv)->t == DUK_TAG_UNDEFINED)
  5015. #define DUK_TVAL_IS_UNDEFINED_ACTUAL(tv) (((tv)->t == DUK_TAG_UNDEFINED) && ((tv)->v.i == 0))
  5016. #define DUK_TVAL_IS_UNDEFINED_UNUSED(tv) (((tv)->t == DUK_TAG_UNDEFINED) && ((tv)->v.i != 0))
  5017. #define DUK_TVAL_IS_NULL(tv) ((tv)->t == DUK_TAG_NULL)
  5018. #define DUK_TVAL_IS_BOOLEAN(tv) ((tv)->t == DUK_TAG_BOOLEAN)
  5019. #define DUK_TVAL_IS_BOOLEAN_TRUE(tv) (((tv)->t == DUK_TAG_BOOLEAN) && ((tv)->v.i != 0))
  5020. #define DUK_TVAL_IS_BOOLEAN_FALSE(tv) (((tv)->t == DUK_TAG_BOOLEAN) && ((tv)->v.i == 0))
  5021. #if defined(DUK_USE_FASTINT)
  5022. #define DUK_TVAL_IS_DOUBLE(tv) ((tv)->t == DUK__TAG_NUMBER)
  5023. #define DUK_TVAL_IS_FASTINT(tv) ((tv)->t == DUK_TAG_FASTINT)
  5024. #define DUK_TVAL_IS_NUMBER(tv) ((tv)->t == DUK__TAG_NUMBER || \
  5025. (tv)->t == DUK_TAG_FASTINT)
  5026. #else
  5027. #define DUK_TVAL_IS_NUMBER(tv) ((tv)->t == DUK__TAG_NUMBER)
  5028. #define DUK_TVAL_IS_DOUBLE(v) DUK_TVAL_IS_NUMBER((v))
  5029. #endif /* DUK_USE_FASTINT */
  5030. #define DUK_TVAL_IS_POINTER(tv) ((tv)->t == DUK_TAG_POINTER)
  5031. #define DUK_TVAL_IS_LIGHTFUNC(tv) ((tv)->t == DUK_TAG_LIGHTFUNC)
  5032. #define DUK_TVAL_IS_STRING(tv) ((tv)->t == DUK_TAG_STRING)
  5033. #define DUK_TVAL_IS_OBJECT(tv) ((tv)->t == DUK_TAG_OBJECT)
  5034. #define DUK_TVAL_IS_BUFFER(tv) ((tv)->t == DUK_TAG_BUFFER)
  5035. #define DUK_TVAL_IS_HEAP_ALLOCATED(tv) ((tv)->t >= DUK_TAG_STRING)
  5036. #if defined(DUK_USE_FASTINT)
  5037. /* Inlining is only effective in a single file build. */
  5038. #if 0
  5039. DUK_INTERNAL_DECL DUK_ALWAYS_INLINE duk_double_t duk_tval_get_number_unpacked(duk_tval *tv);
  5040. #endif
  5041. DUK_INTERNAL_DECL DUK_ALWAYS_INLINE duk_double_t duk_tval_get_number_unpacked_fastint(duk_tval *tv);
  5042. #endif
  5043. #endif /* DUK_USE_PACKED_TVAL */
  5044. /*
  5045. * Convenience (independent of representation)
  5046. */
  5047. #define DUK_TVAL_SET_BOOLEAN_TRUE(v) DUK_TVAL_SET_BOOLEAN(v, 1)
  5048. #define DUK_TVAL_SET_BOOLEAN_FALSE(v) DUK_TVAL_SET_BOOLEAN(v, 0)
  5049. /* Lightfunc flags packing and unpacking. */
  5050. /* Sign extend: 0x0000##00 -> 0x##000000 -> sign extend to 0xssssss## */
  5051. #define DUK_LFUNC_FLAGS_GET_MAGIC(lf_flags) \
  5052. ((((duk_int32_t) (lf_flags)) << 16) >> 24)
  5053. #define DUK_LFUNC_FLAGS_GET_LENGTH(lf_flags) \
  5054. (((lf_flags) >> 4) & 0x0f)
  5055. #define DUK_LFUNC_FLAGS_GET_NARGS(lf_flags) \
  5056. ((lf_flags) & 0x0f)
  5057. #define DUK_LFUNC_FLAGS_PACK(magic,length,nargs) \
  5058. (((magic) & 0xff) << 8) | ((length) << 4) | (nargs)
  5059. #define DUK_LFUNC_NARGS_VARARGS 0x0f /* varargs marker */
  5060. #define DUK_LFUNC_NARGS_MIN 0x00
  5061. #define DUK_LFUNC_NARGS_MAX 0x0e /* max, excl. varargs marker */
  5062. #define DUK_LFUNC_LENGTH_MIN 0x00
  5063. #define DUK_LFUNC_LENGTH_MAX 0x0f
  5064. #define DUK_LFUNC_MAGIC_MIN (-0x80)
  5065. #define DUK_LFUNC_MAGIC_MAX 0x7f
  5066. /* fastint constants etc */
  5067. #if defined(DUK_USE_FASTINT)
  5068. #define DUK_FASTINT_MIN (-0x800000000000LL)
  5069. #define DUK_FASTINT_MAX 0x7fffffffffffLL
  5070. #define DUK_FASTINT_BITS 48
  5071. DUK_INTERNAL_DECL void duk_tval_set_number_chkfast(duk_tval *tv, duk_double_t x);
  5072. #endif
  5073. #endif /* DUK_TVAL_H_INCLUDED */
  5074. #line 1 "duk_heaphdr.h"
  5075. /*
  5076. * Heap header definition and assorted macros, including ref counting.
  5077. * Access all fields through the accessor macros.
  5078. */
  5079. #ifndef DUK_HEAPHDR_H_INCLUDED
  5080. #define DUK_HEAPHDR_H_INCLUDED
  5081. /*
  5082. * Common heap header
  5083. *
  5084. * All heap objects share the same flags and refcount fields. Objects other
  5085. * than strings also need to have a single or double linked list pointers
  5086. * for insertion into the "heap allocated" list. Strings are held in the
  5087. * heap-wide string table so they don't need link pointers.
  5088. *
  5089. * Technically, 'h_refcount' must be wide enough to guarantee that it cannot
  5090. * wrap (otherwise objects might be freed incorrectly after wrapping). This
  5091. * means essentially that the refcount field must be as wide as data pointers.
  5092. * On 64-bit platforms this means that the refcount needs to be 64 bits even
  5093. * if an 'int' is 32 bits. This is a bit unfortunate, and compromising on
  5094. * this might be reasonable in the future.
  5095. *
  5096. * Heap header size on 32-bit platforms: 8 bytes without reference counting,
  5097. * 16 bytes with reference counting.
  5098. */
  5099. struct duk_heaphdr {
  5100. duk_uint32_t h_flags;
  5101. #if defined(DUK_USE_REFERENCE_COUNTING)
  5102. #if defined(DUK_USE_REFCOUNT16)
  5103. duk_uint16_t h_refcount16;
  5104. #else
  5105. duk_size_t h_refcount;
  5106. #endif
  5107. #endif
  5108. #if defined(DUK_USE_HEAPPTR16)
  5109. duk_uint16_t h_next16;
  5110. #else
  5111. duk_heaphdr *h_next;
  5112. #endif
  5113. #if defined(DUK_USE_DOUBLE_LINKED_HEAP)
  5114. /* refcounting requires direct heap frees, which in turn requires a dual linked heap */
  5115. #if defined(DUK_USE_HEAPPTR16)
  5116. duk_uint16_t h_prev16;
  5117. #else
  5118. duk_heaphdr *h_prev;
  5119. #endif
  5120. #endif
  5121. /* When DUK_USE_HEAPPTR16 (and DUK_USE_REFCOUNT16) is in use, the
  5122. * struct won't align nicely to 4 bytes. This 16-bit extra field
  5123. * is added to make the alignment clean; the field can be used by
  5124. * heap objects when 16-bit packing is used. This field is now
  5125. * conditional to DUK_USE_HEAPPTR16 only, but it is intended to be
  5126. * used with DUK_USE_REFCOUNT16 and DUK_USE_DOUBLE_LINKED_HEAP;
  5127. * this only matter to low memory environments anyway.
  5128. */
  5129. #if defined(DUK_USE_HEAPPTR16)
  5130. duk_uint16_t h_extra16;
  5131. #endif
  5132. };
  5133. struct duk_heaphdr_string {
  5134. /* 16 bits would be enough for shared heaphdr flags and duk_hstring
  5135. * flags. The initial parts of duk_heaphdr_string and duk_heaphdr
  5136. * must match so changing the flags field size here would be quite
  5137. * awkward. However, to minimize struct size, we can pack at least
  5138. * 16 bits of duk_hstring data into the flags field.
  5139. */
  5140. duk_uint32_t h_flags;
  5141. #if defined(DUK_USE_REFERENCE_COUNTING)
  5142. #if defined(DUK_USE_REFCOUNT16)
  5143. duk_uint16_t h_refcount16;
  5144. #else
  5145. duk_size_t h_refcount;
  5146. #endif
  5147. #endif
  5148. };
  5149. #define DUK_HEAPHDR_FLAGS_TYPE_MASK 0x00000003UL
  5150. #define DUK_HEAPHDR_FLAGS_FLAG_MASK (~DUK_HEAPHDR_FLAGS_TYPE_MASK)
  5151. /* 2 bits for heap type */
  5152. #define DUK_HEAPHDR_FLAGS_HEAP_START 2 /* 4 heap flags */
  5153. #define DUK_HEAPHDR_FLAGS_USER_START 6 /* 26 user flags */
  5154. #define DUK_HEAPHDR_HEAP_FLAG_NUMBER(n) (DUK_HEAPHDR_FLAGS_HEAP_START + (n))
  5155. #define DUK_HEAPHDR_USER_FLAG_NUMBER(n) (DUK_HEAPHDR_FLAGS_USER_START + (n))
  5156. #define DUK_HEAPHDR_HEAP_FLAG(n) (1UL << (DUK_HEAPHDR_FLAGS_HEAP_START + (n)))
  5157. #define DUK_HEAPHDR_USER_FLAG(n) (1UL << (DUK_HEAPHDR_FLAGS_USER_START + (n)))
  5158. #define DUK_HEAPHDR_FLAG_REACHABLE DUK_HEAPHDR_HEAP_FLAG(0) /* mark-and-sweep: reachable */
  5159. #define DUK_HEAPHDR_FLAG_TEMPROOT DUK_HEAPHDR_HEAP_FLAG(1) /* mark-and-sweep: children not processed */
  5160. #define DUK_HEAPHDR_FLAG_FINALIZABLE DUK_HEAPHDR_HEAP_FLAG(2) /* mark-and-sweep: finalizable (on current pass) */
  5161. #define DUK_HEAPHDR_FLAG_FINALIZED DUK_HEAPHDR_HEAP_FLAG(3) /* mark-and-sweep: finalized (on previous pass) */
  5162. #define DUK_HTYPE_MIN 1
  5163. #define DUK_HTYPE_STRING 1
  5164. #define DUK_HTYPE_OBJECT 2
  5165. #define DUK_HTYPE_BUFFER 3
  5166. #define DUK_HTYPE_MAX 3
  5167. #if defined(DUK_USE_HEAPPTR16)
  5168. #define DUK_HEAPHDR_GET_NEXT(heap,h) \
  5169. ((duk_heaphdr *) DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (h)->h_next16))
  5170. #define DUK_HEAPHDR_SET_NEXT(heap,h,val) do { \
  5171. (h)->h_next16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) val); \
  5172. } while (0)
  5173. #else
  5174. #define DUK_HEAPHDR_GET_NEXT(heap,h) ((h)->h_next)
  5175. #define DUK_HEAPHDR_SET_NEXT(heap,h,val) do { \
  5176. (h)->h_next = (val); \
  5177. } while (0)
  5178. #endif
  5179. #if defined(DUK_USE_DOUBLE_LINKED_HEAP)
  5180. #if defined(DUK_USE_HEAPPTR16)
  5181. #define DUK_HEAPHDR_GET_PREV(heap,h) \
  5182. ((duk_heaphdr *) DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (h)->h_prev16))
  5183. #define DUK_HEAPHDR_SET_PREV(heap,h,val) do { \
  5184. (h)->h_prev16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) (val)); \
  5185. } while (0)
  5186. #else
  5187. #define DUK_HEAPHDR_GET_PREV(heap,h) ((h)->h_prev)
  5188. #define DUK_HEAPHDR_SET_PREV(heap,h,val) do { \
  5189. (h)->h_prev = (val); \
  5190. } while (0)
  5191. #endif
  5192. #endif
  5193. #if defined(DUK_USE_REFERENCE_COUNTING)
  5194. #if defined(DUK_USE_REFCOUNT16)
  5195. #define DUK_HEAPHDR_GET_REFCOUNT(h) ((h)->h_refcount16)
  5196. #define DUK_HEAPHDR_SET_REFCOUNT(h,val) do { \
  5197. (h)->h_refcount16 = (val); \
  5198. } while (0)
  5199. #define DUK_HEAPHDR_PREINC_REFCOUNT(h) (++(h)->h_refcount16) /* result: updated refcount */
  5200. #define DUK_HEAPHDR_PREDEC_REFCOUNT(h) (--(h)->h_refcount16) /* result: updated refcount */
  5201. #else
  5202. #define DUK_HEAPHDR_GET_REFCOUNT(h) ((h)->h_refcount)
  5203. #define DUK_HEAPHDR_SET_REFCOUNT(h,val) do { \
  5204. (h)->h_refcount = (val); \
  5205. } while (0)
  5206. #define DUK_HEAPHDR_PREINC_REFCOUNT(h) (++(h)->h_refcount) /* result: updated refcount */
  5207. #define DUK_HEAPHDR_PREDEC_REFCOUNT(h) (--(h)->h_refcount) /* result: updated refcount */
  5208. #endif
  5209. #else
  5210. /* refcount macros not defined without refcounting, caller must #ifdef now */
  5211. #endif /* DUK_USE_REFERENCE_COUNTING */
  5212. /*
  5213. * Note: type is treated as a field separate from flags, so some masking is
  5214. * involved in the macros below.
  5215. */
  5216. #define DUK_HEAPHDR_GET_FLAGS_RAW(h) ((h)->h_flags)
  5217. #define DUK_HEAPHDR_GET_FLAGS(h) ((h)->h_flags & DUK_HEAPHDR_FLAGS_FLAG_MASK)
  5218. #define DUK_HEAPHDR_SET_FLAGS(h,val) do { \
  5219. (h)->h_flags = ((h)->h_flags & ~(DUK_HEAPHDR_FLAGS_FLAG_MASK)) | (val); \
  5220. } while (0)
  5221. #define DUK_HEAPHDR_GET_TYPE(h) ((h)->h_flags & DUK_HEAPHDR_FLAGS_TYPE_MASK)
  5222. #define DUK_HEAPHDR_SET_TYPE(h,val) do { \
  5223. (h)->h_flags = ((h)->h_flags & ~(DUK_HEAPHDR_FLAGS_TYPE_MASK)) | (val); \
  5224. } while (0)
  5225. #define DUK_HEAPHDR_HTYPE_VALID(h) ( \
  5226. DUK_HEAPHDR_GET_TYPE((h)) >= DUK_HTYPE_MIN && \
  5227. DUK_HEAPHDR_GET_TYPE((h)) <= DUK_HTYPE_MAX \
  5228. )
  5229. #define DUK_HEAPHDR_SET_TYPE_AND_FLAGS(h,tval,fval) do { \
  5230. (h)->h_flags = ((tval) & DUK_HEAPHDR_FLAGS_TYPE_MASK) | \
  5231. ((fval) & DUK_HEAPHDR_FLAGS_FLAG_MASK); \
  5232. } while (0)
  5233. #define DUK_HEAPHDR_SET_FLAG_BITS(h,bits) do { \
  5234. DUK_ASSERT(((bits) & ~(DUK_HEAPHDR_FLAGS_FLAG_MASK)) == 0); \
  5235. (h)->h_flags |= (bits); \
  5236. } while (0)
  5237. #define DUK_HEAPHDR_CLEAR_FLAG_BITS(h,bits) do { \
  5238. DUK_ASSERT(((bits) & ~(DUK_HEAPHDR_FLAGS_FLAG_MASK)) == 0); \
  5239. (h)->h_flags &= ~((bits)); \
  5240. } while (0)
  5241. #define DUK_HEAPHDR_CHECK_FLAG_BITS(h,bits) (((h)->h_flags & (bits)) != 0)
  5242. #define DUK_HEAPHDR_SET_REACHABLE(h) DUK_HEAPHDR_SET_FLAG_BITS((h),DUK_HEAPHDR_FLAG_REACHABLE)
  5243. #define DUK_HEAPHDR_CLEAR_REACHABLE(h) DUK_HEAPHDR_CLEAR_FLAG_BITS((h),DUK_HEAPHDR_FLAG_REACHABLE)
  5244. #define DUK_HEAPHDR_HAS_REACHABLE(h) DUK_HEAPHDR_CHECK_FLAG_BITS((h),DUK_HEAPHDR_FLAG_REACHABLE)
  5245. #define DUK_HEAPHDR_SET_TEMPROOT(h) DUK_HEAPHDR_SET_FLAG_BITS((h),DUK_HEAPHDR_FLAG_TEMPROOT)
  5246. #define DUK_HEAPHDR_CLEAR_TEMPROOT(h) DUK_HEAPHDR_CLEAR_FLAG_BITS((h),DUK_HEAPHDR_FLAG_TEMPROOT)
  5247. #define DUK_HEAPHDR_HAS_TEMPROOT(h) DUK_HEAPHDR_CHECK_FLAG_BITS((h),DUK_HEAPHDR_FLAG_TEMPROOT)
  5248. #define DUK_HEAPHDR_SET_FINALIZABLE(h) DUK_HEAPHDR_SET_FLAG_BITS((h),DUK_HEAPHDR_FLAG_FINALIZABLE)
  5249. #define DUK_HEAPHDR_CLEAR_FINALIZABLE(h) DUK_HEAPHDR_CLEAR_FLAG_BITS((h),DUK_HEAPHDR_FLAG_FINALIZABLE)
  5250. #define DUK_HEAPHDR_HAS_FINALIZABLE(h) DUK_HEAPHDR_CHECK_FLAG_BITS((h),DUK_HEAPHDR_FLAG_FINALIZABLE)
  5251. #define DUK_HEAPHDR_SET_FINALIZED(h) DUK_HEAPHDR_SET_FLAG_BITS((h),DUK_HEAPHDR_FLAG_FINALIZED)
  5252. #define DUK_HEAPHDR_CLEAR_FINALIZED(h) DUK_HEAPHDR_CLEAR_FLAG_BITS((h),DUK_HEAPHDR_FLAG_FINALIZED)
  5253. #define DUK_HEAPHDR_HAS_FINALIZED(h) DUK_HEAPHDR_CHECK_FLAG_BITS((h),DUK_HEAPHDR_FLAG_FINALIZED)
  5254. /* get or set a range of flags; m=first bit number, n=number of bits */
  5255. #define DUK_HEAPHDR_GET_FLAG_RANGE(h,m,n) (((h)->h_flags >> (m)) & ((1UL << (n)) - 1UL))
  5256. #define DUK_HEAPHDR_SET_FLAG_RANGE(h,m,n,v) do { \
  5257. (h)->h_flags = \
  5258. ((h)->h_flags & (~(((1 << (n)) - 1) << (m)))) \
  5259. | ((v) << (m)); \
  5260. } while (0)
  5261. /* init pointer fields to null */
  5262. #if defined(DUK_USE_DOUBLE_LINKED_HEAP)
  5263. #define DUK_HEAPHDR_INIT_NULLS(h) do { \
  5264. DUK_HEAPHDR_SET_NEXT((h), (void *) NULL); \
  5265. DUK_HEAPHDR_SET_PREV((h), (void *) NULL); \
  5266. } while (0)
  5267. #else
  5268. #define DUK_HEAPHDR_INIT_NULLS(h) do { \
  5269. DUK_HEAPHDR_SET_NEXT((h), (void *) NULL); \
  5270. } while (0)
  5271. #endif
  5272. #define DUK_HEAPHDR_STRING_INIT_NULLS(h) /* currently nop */
  5273. /*
  5274. * Reference counting helper macros. The macros take a thread argument
  5275. * and must thus always be executed in a specific thread context. The
  5276. * thread argument is needed for features like finalization. Currently
  5277. * it is not required for INCREF, but it is included just in case.
  5278. *
  5279. * Note that 'raw' macros such as DUK_HEAPHDR_GET_REFCOUNT() are not
  5280. * defined without DUK_USE_REFERENCE_COUNTING, so caller must #ifdef
  5281. * around them.
  5282. */
  5283. #if defined(DUK_USE_REFERENCE_COUNTING)
  5284. /* Fast variants, inline refcount operations except for refzero handling.
  5285. * Can be used explicitly when speed is always more important than size.
  5286. * For a good compiler and a single file build, these are basically the
  5287. * same as a forced inline.
  5288. */
  5289. #define DUK_TVAL_INCREF_FAST(thr,tv) do { \
  5290. duk_tval *duk__tv = (tv); \
  5291. DUK_ASSERT(duk__tv != NULL); \
  5292. if (DUK_TVAL_IS_HEAP_ALLOCATED(duk__tv)) { \
  5293. duk_heaphdr *duk__h = DUK_TVAL_GET_HEAPHDR(duk__tv); \
  5294. DUK_ASSERT(duk__h != NULL); \
  5295. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(duk__h)); \
  5296. DUK_HEAPHDR_PREINC_REFCOUNT(duk__h); \
  5297. } \
  5298. } while (0)
  5299. #define DUK_TVAL_DECREF_FAST(thr,tv) do { \
  5300. duk_tval *duk__tv = (tv); \
  5301. DUK_ASSERT(duk__tv != NULL); \
  5302. if (DUK_TVAL_IS_HEAP_ALLOCATED(duk__tv)) { \
  5303. duk_heaphdr *duk__h = DUK_TVAL_GET_HEAPHDR(duk__tv); \
  5304. DUK_ASSERT(duk__h != NULL); \
  5305. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(duk__h)); \
  5306. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(duk__h) > 0); \
  5307. if (DUK_HEAPHDR_PREDEC_REFCOUNT(duk__h) == 0) { \
  5308. duk_heaphdr_refzero((thr), duk__h); \
  5309. } \
  5310. } \
  5311. } while (0)
  5312. #define DUK_HEAPHDR_INCREF_FAST(thr,h) do { \
  5313. duk_heaphdr *duk__h = (duk_heaphdr *) (h); \
  5314. DUK_ASSERT(duk__h != NULL); \
  5315. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(duk__h)); \
  5316. DUK_HEAPHDR_PREINC_REFCOUNT(duk__h); \
  5317. } while (0)
  5318. #define DUK_HEAPHDR_DECREF_FAST(thr,h) do { \
  5319. duk_heaphdr *duk__h = (duk_heaphdr *) (h); \
  5320. DUK_ASSERT(duk__h != NULL); \
  5321. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(duk__h)); \
  5322. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(duk__h) > 0); \
  5323. if (DUK_HEAPHDR_PREDEC_REFCOUNT(duk__h) == 0) { \
  5324. duk_heaphdr_refzero((thr), duk__h); \
  5325. } \
  5326. } while (0)
  5327. /* Slow variants, call to a helper to reduce code size.
  5328. * Can be used explicitly when size is always more important than speed.
  5329. */
  5330. #define DUK_TVAL_INCREF_SLOW(thr,tv) do { \
  5331. duk_tval_incref((tv)); \
  5332. } while (0)
  5333. #define DUK_TVAL_DECREF_SLOW(thr,tv) do { \
  5334. duk_tval_decref((thr), (tv)); \
  5335. } while (0)
  5336. #define DUK_HEAPHDR_INCREF_SLOW(thr,h) do { \
  5337. duk_heaphdr_incref((duk_heaphdr *) (h)); \
  5338. } while (0)
  5339. #define DUK_HEAPHDR_DECREF_SLOW(thr,h) do { \
  5340. duk_heaphdr_decref((thr), (duk_heaphdr *) (h)); \
  5341. } while (0)
  5342. /* Default variants. Selection depends on speed/size preference.
  5343. * Concretely: with gcc 4.8.1 -Os x64 the difference in final binary
  5344. * is about +1kB for _FAST variants.
  5345. */
  5346. #if defined(DUK_USE_FAST_REFCOUNT_DEFAULT)
  5347. #define DUK_TVAL_INCREF(thr,tv) DUK_TVAL_INCREF_FAST((thr),(tv))
  5348. #define DUK_TVAL_DECREF(thr,tv) DUK_TVAL_DECREF_FAST((thr),(tv))
  5349. #define DUK_HEAPHDR_INCREF(thr,h) DUK_HEAPHDR_INCREF_FAST((thr),(h))
  5350. #define DUK_HEAPHDR_DECREF(thr,h) DUK_HEAPHDR_DECREF_FAST((thr),(h))
  5351. #else
  5352. #define DUK_TVAL_INCREF(thr,tv) DUK_TVAL_INCREF_SLOW((thr),(tv))
  5353. #define DUK_TVAL_DECREF(thr,tv) DUK_TVAL_DECREF_SLOW((thr),(tv))
  5354. #define DUK_HEAPHDR_INCREF(thr,h) DUK_HEAPHDR_INCREF_SLOW((thr),(h))
  5355. #define DUK_HEAPHDR_DECREF(thr,h) DUK_HEAPHDR_DECREF_SLOW((thr),(h))
  5356. #endif
  5357. /* Casting convenience. */
  5358. #define DUK_HSTRING_INCREF(thr,h) DUK_HEAPHDR_INCREF((thr),(duk_heaphdr *) (h))
  5359. #define DUK_HSTRING_DECREF(thr,h) DUK_HEAPHDR_DECREF((thr),(duk_heaphdr *) (h))
  5360. #define DUK_HOBJECT_INCREF(thr,h) DUK_HEAPHDR_INCREF((thr),(duk_heaphdr *) (h))
  5361. #define DUK_HOBJECT_DECREF(thr,h) DUK_HEAPHDR_DECREF((thr),(duk_heaphdr *) (h))
  5362. #define DUK_HBUFFER_INCREF(thr,h) DUK_HEAPHDR_INCREF((thr),(duk_heaphdr *) (h))
  5363. #define DUK_HBUFFER_DECREF(thr,h) DUK_HEAPHDR_DECREF((thr),(duk_heaphdr *) (h))
  5364. #define DUK_HCOMPILEDFUNCTION_INCREF(thr,h) DUK_HEAPHDR_INCREF((thr),(duk_heaphdr *) &(h)->obj)
  5365. #define DUK_HCOMPILEDFUNCTION_DECREF(thr,h) DUK_HEAPHDR_DECREF((thr),(duk_heaphdr *) &(h)->obj)
  5366. #define DUK_HNATIVEFUNCTION_INCREF(thr,h) DUK_HEAPHDR_INCREF((thr),(duk_heaphdr *) &(h)->obj)
  5367. #define DUK_HNATIVEFUNCTION_DECREF(thr,h) DUK_HEAPHDR_DECREF((thr),(duk_heaphdr *) &(h)->obj)
  5368. #define DUK_HTHREAD_INCREF(thr,h) DUK_HEAPHDR_INCREF((thr),(duk_heaphdr *) &(h)->obj)
  5369. #define DUK_HTHREAD_DECREF(thr,h) DUK_HEAPHDR_DECREF((thr),(duk_heaphdr *) &(h)->obj)
  5370. /* Convenience for some situations; the above macros don't allow NULLs
  5371. * for performance reasons.
  5372. */
  5373. #define DUK_HOBJECT_INCREF_ALLOWNULL(thr,h) do { \
  5374. if ((h) != NULL) { \
  5375. DUK_HEAPHDR_INCREF((thr), (duk_heaphdr *) (h)); \
  5376. } \
  5377. } while (0)
  5378. #define DUK_HOBJECT_DECREF_ALLOWNULL(thr,h) do { \
  5379. if ((h) != NULL) { \
  5380. DUK_HEAPHDR_DECREF((thr), (duk_heaphdr *) (h)); \
  5381. } \
  5382. } while (0)
  5383. #else /* DUK_USE_REFERENCE_COUNTING */
  5384. #define DUK_TVAL_INCREF_FAST(thr,v) do {} while (0) /* nop */
  5385. #define DUK_TVAL_DECREF_FAST(thr,v) do {} while (0) /* nop */
  5386. #define DUK_TVAL_INCREF_SLOW(thr,v) do {} while (0) /* nop */
  5387. #define DUK_TVAL_DECREF_SLOW(thr,v) do {} while (0) /* nop */
  5388. #define DUK_TVAL_INCREF(thr,v) do {} while (0) /* nop */
  5389. #define DUK_TVAL_DECREF(thr,v) do {} while (0) /* nop */
  5390. #define DUK_HEAPHDR_INCREF_FAST(thr,h) do {} while (0) /* nop */
  5391. #define DUK_HEAPHDR_DECREF_FAST(thr,h) do {} while (0) /* nop */
  5392. #define DUK_HEAPHDR_INCREF_SLOW(thr,h) do {} while (0) /* nop */
  5393. #define DUK_HEAPHDR_DECREF_SLOW(thr,h) do {} while (0) /* nop */
  5394. #define DUK_HEAPHDR_INCREF(thr,h) do {} while (0) /* nop */
  5395. #define DUK_HEAPHDR_DECREF(thr,h) do {} while (0) /* nop */
  5396. #define DUK_HSTRING_INCREF(thr,h) do {} while (0) /* nop */
  5397. #define DUK_HSTRING_DECREF(thr,h) do {} while (0) /* nop */
  5398. #define DUK_HOBJECT_INCREF(thr,h) do {} while (0) /* nop */
  5399. #define DUK_HOBJECT_DECREF(thr,h) do {} while (0) /* nop */
  5400. #define DUK_HBUFFER_INCREF(thr,h) do {} while (0) /* nop */
  5401. #define DUK_HBUFFER_DECREF(thr,h) do {} while (0) /* nop */
  5402. #define DUK_HCOMPILEDFUNCTION_INCREF(thr,h) do {} while (0) /* nop */
  5403. #define DUK_HCOMPILEDFUNCTION_DECREF(thr,h) do {} while (0) /* nop */
  5404. #define DUK_HNATIVEFUNCTION_INCREF(thr,h) do {} while (0) /* nop */
  5405. #define DUK_HNATIVEFUNCTION_DECREF(thr,h) do {} while (0) /* nop */
  5406. #define DUK_HTHREAD_INCREF(thr,h) do {} while (0) /* nop */
  5407. #define DUK_HTHREAD_DECREF(thr,h) do {} while (0) /* nop */
  5408. #define DUK_HOBJECT_INCREF_ALLOWNULL(thr,h) do {} while (0) /* nop */
  5409. #define DUK_HOBJECT_DECREF_ALLOWNULL(thr,h) do {} while (0) /* nop */
  5410. #endif /* DUK_USE_REFERENCE_COUNTING */
  5411. #endif /* DUK_HEAPHDR_H_INCLUDED */
  5412. #line 1 "duk_api_internal.h"
  5413. /*
  5414. * Internal API calls which have (stack and other) semantics similar
  5415. * to the public API.
  5416. */
  5417. #ifndef DUK_API_INTERNAL_H_INCLUDED
  5418. #define DUK_API_INTERNAL_H_INCLUDED
  5419. /* duk_push_sprintf constants */
  5420. #define DUK_PUSH_SPRINTF_INITIAL_SIZE 256L
  5421. #define DUK_PUSH_SPRINTF_SANITY_LIMIT (1L * 1024L * 1024L * 1024L)
  5422. /* Flag ORed to err_code to indicate __FILE__ / __LINE__ is not
  5423. * blamed as source of error for error fileName / lineNumber.
  5424. */
  5425. #define DUK_ERRCODE_FLAG_NOBLAME_FILELINE (1L << 24)
  5426. /* Valstack resize flags */
  5427. #define DUK_VSRESIZE_FLAG_SHRINK (1 << 0)
  5428. #define DUK_VSRESIZE_FLAG_COMPACT (1 << 1)
  5429. #define DUK_VSRESIZE_FLAG_THROW (1 << 2)
  5430. /* Current convention is to use duk_size_t for value stack sizes and global indices,
  5431. * and duk_idx_t for local frame indices.
  5432. */
  5433. DUK_INTERNAL_DECL
  5434. duk_bool_t duk_valstack_resize_raw(duk_context *ctx,
  5435. duk_size_t min_new_size,
  5436. duk_small_uint_t flags);
  5437. DUK_INTERNAL_DECL duk_tval *duk_get_tval(duk_context *ctx, duk_idx_t index);
  5438. DUK_INTERNAL_DECL duk_tval *duk_require_tval(duk_context *ctx, duk_idx_t index);
  5439. DUK_INTERNAL_DECL void duk_push_tval(duk_context *ctx, duk_tval *tv);
  5440. /* Push the current 'this' binding; throw TypeError if binding is not object
  5441. * coercible (CheckObjectCoercible).
  5442. */
  5443. DUK_INTERNAL_DECL void duk_push_this_check_object_coercible(duk_context *ctx);
  5444. /* duk_push_this() + CheckObjectCoercible() + duk_to_object() */
  5445. DUK_INTERNAL_DECL duk_hobject *duk_push_this_coercible_to_object(duk_context *ctx);
  5446. /* duk_push_this() + CheckObjectCoercible() + duk_to_string() */
  5447. DUK_INTERNAL_DECL duk_hstring *duk_push_this_coercible_to_string(duk_context *ctx);
  5448. /* duk_push_(u)int() is guaranteed to support at least (un)signed 32-bit range */
  5449. #define duk_push_u32(ctx,val) \
  5450. duk_push_uint((ctx), (duk_uint_t) (val))
  5451. #define duk_push_i32(ctx,val) \
  5452. duk_push_int((ctx), (duk_int_t) (val))
  5453. /* sometimes stack and array indices need to go on the stack */
  5454. #define duk_push_idx(ctx,val) \
  5455. duk_push_int((ctx), (duk_int_t) (val))
  5456. #define duk_push_uarridx(ctx,val) \
  5457. duk_push_uint((ctx), (duk_uint_t) (val))
  5458. #define duk_push_size_t(ctx,val) \
  5459. duk_push_uint((ctx), (duk_uint_t) (val)) /* XXX: assumed to fit for now */
  5460. /* internal helper for looking up a tagged type */
  5461. #define DUK_GETTAGGED_FLAG_ALLOW_NULL (1L << 24)
  5462. #define DUK_GETTAGGED_FLAG_CHECK_CLASS (1L << 25)
  5463. #define DUK_GETTAGGED_CLASS_SHIFT 16
  5464. DUK_INTERNAL_DECL duk_heaphdr *duk_get_tagged_heaphdr_raw(duk_context *ctx, duk_idx_t index, duk_uint_t flags_and_tag);
  5465. DUK_INTERNAL_DECL duk_hstring *duk_get_hstring(duk_context *ctx, duk_idx_t index);
  5466. DUK_INTERNAL_DECL duk_hobject *duk_get_hobject(duk_context *ctx, duk_idx_t index);
  5467. DUK_INTERNAL_DECL duk_hbuffer *duk_get_hbuffer(duk_context *ctx, duk_idx_t index);
  5468. DUK_INTERNAL_DECL duk_hthread *duk_get_hthread(duk_context *ctx, duk_idx_t index);
  5469. DUK_INTERNAL_DECL duk_hcompiledfunction *duk_get_hcompiledfunction(duk_context *ctx, duk_idx_t index);
  5470. DUK_INTERNAL_DECL duk_hnativefunction *duk_get_hnativefunction(duk_context *ctx, duk_idx_t index);
  5471. #define duk_get_hobject_with_class(ctx,index,classnum) \
  5472. ((duk_hobject *) duk_get_tagged_heaphdr_raw((ctx), (index), \
  5473. DUK_TAG_OBJECT | DUK_GETTAGGED_FLAG_ALLOW_NULL | \
  5474. DUK_GETTAGGED_FLAG_CHECK_CLASS | ((classnum) << DUK_GETTAGGED_CLASS_SHIFT)))
  5475. #if 0 /* This would be pointless: unexpected type and lightfunc would both return NULL */
  5476. DUK_INTERNAL_DECL duk_hobject *duk_get_hobject_or_lfunc(duk_context *ctx, duk_idx_t index);
  5477. #endif
  5478. DUK_INTERNAL_DECL duk_hobject *duk_get_hobject_or_lfunc_coerce(duk_context *ctx, duk_idx_t index);
  5479. #if 0 /*unused*/
  5480. DUK_INTERNAL_DECL void *duk_get_voidptr(duk_context *ctx, duk_idx_t index);
  5481. #endif
  5482. DUK_INTERNAL_DECL duk_hstring *duk_to_hstring(duk_context *ctx, duk_idx_t index);
  5483. DUK_INTERNAL_DECL duk_int_t duk_to_int_clamped_raw(duk_context *ctx, duk_idx_t index, duk_int_t minval, duk_int_t maxval, duk_bool_t *out_clamped); /* out_clamped=NULL, RangeError if outside range */
  5484. DUK_INTERNAL_DECL duk_int_t duk_to_int_clamped(duk_context *ctx, duk_idx_t index, duk_int_t minval, duk_int_t maxval);
  5485. DUK_INTERNAL_DECL duk_int_t duk_to_int_check_range(duk_context *ctx, duk_idx_t index, duk_int_t minval, duk_int_t maxval);
  5486. DUK_INTERNAL_DECL duk_hstring *duk_require_hstring(duk_context *ctx, duk_idx_t index);
  5487. DUK_INTERNAL_DECL duk_hobject *duk_require_hobject(duk_context *ctx, duk_idx_t index);
  5488. DUK_INTERNAL_DECL duk_hbuffer *duk_require_hbuffer(duk_context *ctx, duk_idx_t index);
  5489. DUK_INTERNAL_DECL duk_hthread *duk_require_hthread(duk_context *ctx, duk_idx_t index);
  5490. #if 0 /*unused */
  5491. DUK_INTERNAL_DECL duk_hcompiledfunction *duk_require_hcompiledfunction(duk_context *ctx, duk_idx_t index);
  5492. #endif
  5493. DUK_INTERNAL_DECL duk_hnativefunction *duk_require_hnativefunction(duk_context *ctx, duk_idx_t index);
  5494. #define duk_require_hobject_with_class(ctx,index,classnum) \
  5495. ((duk_hobject *) duk_get_tagged_heaphdr_raw((ctx), (index), \
  5496. DUK_TAG_OBJECT | \
  5497. DUK_GETTAGGED_FLAG_CHECK_CLASS | ((classnum) << DUK_GETTAGGED_CLASS_SHIFT)))
  5498. DUK_INTERNAL_DECL duk_hobject *duk_require_hobject_or_lfunc(duk_context *ctx, duk_idx_t index);
  5499. DUK_INTERNAL_DECL duk_hobject *duk_require_hobject_or_lfunc_coerce(duk_context *ctx, duk_idx_t index);
  5500. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  5501. DUK_INTERNAL_DECL void duk_push_unused(duk_context *ctx);
  5502. #endif
  5503. DUK_INTERNAL_DECL void duk_push_hstring(duk_context *ctx, duk_hstring *h);
  5504. DUK_INTERNAL_DECL void duk_push_hstring_stridx(duk_context *ctx, duk_small_int_t stridx);
  5505. DUK_INTERNAL_DECL void duk_push_hobject(duk_context *ctx, duk_hobject *h);
  5506. DUK_INTERNAL_DECL void duk_push_hbuffer(duk_context *ctx, duk_hbuffer *h);
  5507. #define duk_push_hthread(ctx,h) \
  5508. duk_push_hobject((ctx), (duk_hobject *) (h))
  5509. #define duk_push_hcompiledfunction(ctx,h) \
  5510. duk_push_hobject((ctx), (duk_hobject *) (h))
  5511. #define duk_push_hnativefunction(ctx,h) \
  5512. duk_push_hobject((ctx), (duk_hobject *) (h))
  5513. DUK_INTERNAL_DECL void duk_push_hobject_bidx(duk_context *ctx, duk_small_int_t builtin_idx);
  5514. DUK_INTERNAL_DECL duk_idx_t duk_push_object_helper(duk_context *ctx, duk_uint_t hobject_flags_and_class, duk_small_int_t prototype_bidx);
  5515. DUK_INTERNAL_DECL duk_idx_t duk_push_object_helper_proto(duk_context *ctx, duk_uint_t hobject_flags_and_class, duk_hobject *proto);
  5516. DUK_INTERNAL_DECL duk_idx_t duk_push_object_internal(duk_context *ctx);
  5517. DUK_INTERNAL_DECL duk_idx_t duk_push_compiledfunction(duk_context *ctx);
  5518. DUK_INTERNAL_DECL void duk_push_c_function_noexotic(duk_context *ctx, duk_c_function func, duk_int_t nargs);
  5519. DUK_INTERNAL_DECL void duk_push_c_function_noconstruct_noexotic(duk_context *ctx, duk_c_function func, duk_int_t nargs);
  5520. DUK_INTERNAL_DECL void duk_push_string_funcptr(duk_context *ctx, duk_uint8_t *ptr, duk_size_t sz);
  5521. DUK_INTERNAL_DECL void duk_push_lightfunc_name(duk_context *ctx, duk_tval *tv);
  5522. DUK_INTERNAL_DECL void duk_push_lightfunc_tostring(duk_context *ctx, duk_tval *tv);
  5523. DUK_INTERNAL_DECL duk_bool_t duk_get_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx); /* [] -> [val] */
  5524. DUK_INTERNAL_DECL duk_bool_t duk_put_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx); /* [val] -> [] */
  5525. DUK_INTERNAL_DECL duk_bool_t duk_del_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx); /* [] -> [] */
  5526. DUK_INTERNAL_DECL duk_bool_t duk_has_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx); /* [] -> [] */
  5527. DUK_INTERNAL_DECL duk_bool_t duk_get_prop_stridx_boolean(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_bool_t *out_has_prop); /* [] -> [] */
  5528. DUK_INTERNAL_DECL void duk_xdef_prop(duk_context *ctx, duk_idx_t obj_index, duk_small_uint_t desc_flags); /* [key val] -> [] */
  5529. DUK_INTERNAL_DECL void duk_xdef_prop_index(duk_context *ctx, duk_idx_t obj_index, duk_uarridx_t arr_index, duk_small_uint_t desc_flags); /* [val] -> [] */
  5530. DUK_INTERNAL_DECL void duk_xdef_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_small_uint_t desc_flags); /* [val] -> [] */
  5531. DUK_INTERNAL_DECL void duk_xdef_prop_stridx_builtin(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_small_int_t builtin_idx, duk_small_uint_t desc_flags); /* [] -> [] */
  5532. DUK_INTERNAL_DECL void duk_xdef_prop_stridx_thrower(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_small_uint_t desc_flags); /* [] -> [] */
  5533. /* These are macros for now, but could be separate functions to reduce code
  5534. * footprint (check call site count before refactoring).
  5535. */
  5536. #define duk_xdef_prop_wec(ctx,obj_index) \
  5537. duk_xdef_prop((ctx), (obj_index), DUK_PROPDESC_FLAGS_WEC)
  5538. #define duk_xdef_prop_index_wec(ctx,obj_index,arr_index) \
  5539. duk_xdef_prop_index((ctx), (obj_index), (arr_index), DUK_PROPDESC_FLAGS_WEC)
  5540. #define duk_xdef_prop_stridx_wec(ctx,obj_index,stridx) \
  5541. duk_xdef_prop_stridx((ctx), (obj_index), (stridx), DUK_PROPDESC_FLAGS_WEC)
  5542. /* Set object 'length'. */
  5543. DUK_INTERNAL_DECL void duk_set_length(duk_context *ctx, duk_idx_t index, duk_size_t length);
  5544. #endif /* DUK_API_INTERNAL_H_INCLUDED */
  5545. #line 1 "duk_hstring.h"
  5546. /*
  5547. * Heap string representation.
  5548. *
  5549. * Strings are byte sequences ordinarily stored in extended UTF-8 format,
  5550. * allowing values larger than the official UTF-8 range (used internally)
  5551. * and also allowing UTF-8 encoding of surrogate pairs (CESU-8 format).
  5552. * Strings may also be invalid UTF-8 altogether which is the case e.g. with
  5553. * strings used as internal property names and raw buffers converted to
  5554. * strings. In such cases the 'clen' field contains an inaccurate value.
  5555. *
  5556. * Ecmascript requires support for 32-bit long strings. However, since each
  5557. * 16-bit codepoint can take 3 bytes in CESU-8, this representation can only
  5558. * support about 1.4G codepoint long strings in extreme cases. This is not
  5559. * really a practical issue.
  5560. */
  5561. #ifndef DUK_HSTRING_H_INCLUDED
  5562. #define DUK_HSTRING_H_INCLUDED
  5563. /* Impose a maximum string length for now. Restricted artificially to
  5564. * ensure adding a heap header length won't overflow size_t. The limit
  5565. * should be synchronized with DUK_HBUFFER_MAX_BYTELEN.
  5566. *
  5567. * E5.1 makes provisions to support strings longer than 4G characters.
  5568. * This limit should be eliminated on 64-bit platforms (and increased
  5569. * closer to maximum support on 32-bit platforms).
  5570. */
  5571. #if defined(DUK_USE_STRLEN16)
  5572. #define DUK_HSTRING_MAX_BYTELEN (0x0000ffffUL)
  5573. #else
  5574. #define DUK_HSTRING_MAX_BYTELEN (0x7fffffffUL)
  5575. #endif
  5576. /* XXX: could add flags for "is valid CESU-8" (Ecmascript compatible strings),
  5577. * "is valid UTF-8", "is valid extended UTF-8" (internal strings are not,
  5578. * regexp bytecode is), and "contains non-BMP characters". These are not
  5579. * needed right now.
  5580. */
  5581. #define DUK_HSTRING_FLAG_ARRIDX DUK_HEAPHDR_USER_FLAG(0) /* string is a valid array index */
  5582. #define DUK_HSTRING_FLAG_INTERNAL DUK_HEAPHDR_USER_FLAG(1) /* string is internal */
  5583. #define DUK_HSTRING_FLAG_RESERVED_WORD DUK_HEAPHDR_USER_FLAG(2) /* string is a reserved word (non-strict) */
  5584. #define DUK_HSTRING_FLAG_STRICT_RESERVED_WORD DUK_HEAPHDR_USER_FLAG(3) /* string is a reserved word (strict) */
  5585. #define DUK_HSTRING_FLAG_EVAL_OR_ARGUMENTS DUK_HEAPHDR_USER_FLAG(4) /* string is 'eval' or 'arguments' */
  5586. #define DUK_HSTRING_FLAG_EXTDATA DUK_HEAPHDR_USER_FLAG(5) /* string data is external (duk_hstring_external) */
  5587. #define DUK_HSTRING_HAS_ARRIDX(x) DUK_HEAPHDR_CHECK_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_ARRIDX)
  5588. #define DUK_HSTRING_HAS_INTERNAL(x) DUK_HEAPHDR_CHECK_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_INTERNAL)
  5589. #define DUK_HSTRING_HAS_RESERVED_WORD(x) DUK_HEAPHDR_CHECK_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_RESERVED_WORD)
  5590. #define DUK_HSTRING_HAS_STRICT_RESERVED_WORD(x) DUK_HEAPHDR_CHECK_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_STRICT_RESERVED_WORD)
  5591. #define DUK_HSTRING_HAS_EVAL_OR_ARGUMENTS(x) DUK_HEAPHDR_CHECK_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_EVAL_OR_ARGUMENTS)
  5592. #define DUK_HSTRING_HAS_EXTDATA(x) DUK_HEAPHDR_CHECK_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_EXTDATA)
  5593. #define DUK_HSTRING_SET_ARRIDX(x) DUK_HEAPHDR_SET_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_ARRIDX)
  5594. #define DUK_HSTRING_SET_INTERNAL(x) DUK_HEAPHDR_SET_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_INTERNAL)
  5595. #define DUK_HSTRING_SET_RESERVED_WORD(x) DUK_HEAPHDR_SET_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_RESERVED_WORD)
  5596. #define DUK_HSTRING_SET_STRICT_RESERVED_WORD(x) DUK_HEAPHDR_SET_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_STRICT_RESERVED_WORD)
  5597. #define DUK_HSTRING_SET_EVAL_OR_ARGUMENTS(x) DUK_HEAPHDR_SET_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_EVAL_OR_ARGUMENTS)
  5598. #define DUK_HSTRING_SET_EXTDATA(x) DUK_HEAPHDR_SET_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_EXTDATA)
  5599. #define DUK_HSTRING_CLEAR_ARRIDX(x) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_ARRIDX)
  5600. #define DUK_HSTRING_CLEAR_INTERNAL(x) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_INTERNAL)
  5601. #define DUK_HSTRING_CLEAR_RESERVED_WORD(x) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_RESERVED_WORD)
  5602. #define DUK_HSTRING_CLEAR_STRICT_RESERVED_WORD(x) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_STRICT_RESERVED_WORD)
  5603. #define DUK_HSTRING_CLEAR_EVAL_OR_ARGUMENTS(x) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_EVAL_OR_ARGUMENTS)
  5604. #define DUK_HSTRING_CLEAR_EXTDATA(x) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(x)->hdr, DUK_HSTRING_FLAG_EXTDATA)
  5605. #define DUK_HSTRING_IS_ASCII(x) (DUK_HSTRING_GET_BYTELEN((x)) == DUK_HSTRING_GET_CHARLEN((x)))
  5606. #define DUK_HSTRING_IS_EMPTY(x) (DUK_HSTRING_GET_BYTELEN((x)) == 0)
  5607. #if defined(DUK_USE_STRHASH16)
  5608. #define DUK_HSTRING_GET_HASH(x) ((x)->hdr.h_flags >> 16)
  5609. #define DUK_HSTRING_SET_HASH(x,v) do { \
  5610. (x)->hdr.h_flags = ((x)->hdr.h_flags & 0x0000ffffUL) | ((v) << 16); \
  5611. } while (0)
  5612. #else
  5613. #define DUK_HSTRING_GET_HASH(x) ((x)->hash)
  5614. #define DUK_HSTRING_SET_HASH(x,v) do { \
  5615. (x)->hash = (v); \
  5616. } while (0)
  5617. #endif
  5618. #if defined(DUK_USE_STRLEN16)
  5619. #define DUK_HSTRING_GET_BYTELEN(x) ((x)->blen16)
  5620. #define DUK_HSTRING_SET_BYTELEN(x,v) do { \
  5621. (x)->blen16 = (v); \
  5622. } while (0)
  5623. #define DUK_HSTRING_GET_CHARLEN(x) ((x)->clen16)
  5624. #define DUK_HSTRING_SET_CHARLEN(x,v) do { \
  5625. (x)->clen16 = (v); \
  5626. } while (0)
  5627. #else
  5628. #define DUK_HSTRING_GET_BYTELEN(x) ((x)->blen)
  5629. #define DUK_HSTRING_SET_BYTELEN(x,v) do { \
  5630. (x)->blen = (v); \
  5631. } while (0)
  5632. #define DUK_HSTRING_GET_CHARLEN(x) ((x)->clen)
  5633. #define DUK_HSTRING_SET_CHARLEN(x,v) do { \
  5634. (x)->clen = (v); \
  5635. } while (0)
  5636. #endif
  5637. #if defined(DUK_USE_HSTRING_EXTDATA)
  5638. #define DUK_HSTRING_GET_EXTDATA(x) \
  5639. ((x)->extdata)
  5640. #define DUK_HSTRING_GET_DATA(x) \
  5641. (DUK_HSTRING_HAS_EXTDATA((x)) ? \
  5642. DUK_HSTRING_GET_EXTDATA((duk_hstring_external *) (x)) : ((const duk_uint8_t *) ((x) + 1)))
  5643. #else
  5644. #define DUK_HSTRING_GET_DATA(x) \
  5645. ((const duk_uint8_t *) ((x) + 1))
  5646. #endif
  5647. #define DUK_HSTRING_GET_DATA_END(x) \
  5648. (DUK_HSTRING_GET_DATA((x)) + (x)->blen)
  5649. /* marker value; in E5 2^32-1 is not a valid array index (2^32-2 is highest valid) */
  5650. #define DUK_HSTRING_NO_ARRAY_INDEX (0xffffffffUL)
  5651. /* get array index related to string (or return DUK_HSTRING_NO_ARRAY_INDEX);
  5652. * avoids helper call if string has no array index value.
  5653. */
  5654. #define DUK_HSTRING_GET_ARRIDX_FAST(h) \
  5655. (DUK_HSTRING_HAS_ARRIDX((h)) ? duk_js_to_arrayindex_string_helper((h)) : DUK_HSTRING_NO_ARRAY_INDEX)
  5656. /* slower but more compact variant */
  5657. #define DUK_HSTRING_GET_ARRIDX_SLOW(h) \
  5658. (duk_js_to_arrayindex_string_helper((h)))
  5659. /*
  5660. * Misc
  5661. */
  5662. struct duk_hstring {
  5663. /* Smaller heaphdr than for other objects, because strings are held
  5664. * in string intern table which requires no link pointers. Much of
  5665. * the 32-bit flags field is unused by flags, so we can stuff a 16-bit
  5666. * field in there.
  5667. */
  5668. duk_heaphdr_string hdr;
  5669. /* Note: we could try to stuff a partial hash (e.g. 16 bits) into the
  5670. * shared heap header. Good hashing needs more hash bits though.
  5671. */
  5672. /* string hash */
  5673. #if defined(DUK_USE_STRHASH16)
  5674. /* If 16-bit hash is in use, stuff it into duk_heaphdr_string flags. */
  5675. #else
  5676. duk_uint32_t hash;
  5677. #endif
  5678. /* length in bytes (not counting NUL term) */
  5679. #if defined(DUK_USE_STRLEN16)
  5680. duk_uint16_t blen16;
  5681. #else
  5682. duk_uint32_t blen;
  5683. #endif
  5684. /* length in codepoints (must be E5 compatible) */
  5685. #if defined(DUK_USE_STRLEN16)
  5686. duk_uint16_t clen16;
  5687. #else
  5688. duk_uint32_t clen;
  5689. #endif
  5690. /*
  5691. * String value of 'blen+1' bytes follows (+1 for NUL termination
  5692. * convenience for C API). No alignment needs to be guaranteed
  5693. * for strings, but fields above should guarantee alignment-by-4
  5694. * (but not alignment-by-8).
  5695. */
  5696. };
  5697. /* The external string struct is defined even when the feature is inactive. */
  5698. struct duk_hstring_external {
  5699. duk_hstring str;
  5700. /*
  5701. * For an external string, the NUL-terminated string data is stored
  5702. * externally. The user must guarantee that data behind this pointer
  5703. * doesn't change while it's used.
  5704. */
  5705. const duk_uint8_t *extdata;
  5706. };
  5707. /*
  5708. * Prototypes
  5709. */
  5710. DUK_INTERNAL_DECL duk_ucodepoint_t duk_hstring_char_code_at_raw(duk_hthread *thr, duk_hstring *h, duk_uint_t pos);
  5711. #endif /* DUK_HSTRING_H_INCLUDED */
  5712. #line 1 "duk_hobject.h"
  5713. /*
  5714. * Heap object representation.
  5715. *
  5716. * Heap objects are used for Ecmascript objects, arrays, and functions,
  5717. * but also for internal control like declarative and object environment
  5718. * records. Compiled functions, native functions, and threads are also
  5719. * objects but with an extended C struct.
  5720. *
  5721. * Objects provide the required Ecmascript semantics and exotic behaviors
  5722. * especially for property access.
  5723. *
  5724. * Properties are stored in three conceptual parts:
  5725. *
  5726. * 1. A linear 'entry part' contains ordered key-value-attributes triples
  5727. * and is the main method of string properties.
  5728. *
  5729. * 2. An optional linear 'array part' is used for array objects to store a
  5730. * (dense) range of [0,N[ array indexed entries with default attributes
  5731. * (writable, enumerable, configurable). If the array part would become
  5732. * sparse or non-default attributes are required, the array part is
  5733. * abandoned and moved to the 'entry part'.
  5734. *
  5735. * 3. An optional 'hash part' is used to optimize lookups of the entry
  5736. * part; it is used only for objects with sufficiently many properties
  5737. * and can be abandoned without loss of information.
  5738. *
  5739. * These three conceptual parts are stored in a single memory allocated area.
  5740. * This minimizes memory allocation overhead but also means that all three
  5741. * parts are resized together, and makes property access a bit complicated.
  5742. */
  5743. #ifndef DUK_HOBJECT_H_INCLUDED
  5744. #define DUK_HOBJECT_H_INCLUDED
  5745. /* there are currently 26 flag bits available */
  5746. #define DUK_HOBJECT_FLAG_EXTENSIBLE DUK_HEAPHDR_USER_FLAG(0) /* object is extensible */
  5747. #define DUK_HOBJECT_FLAG_CONSTRUCTABLE DUK_HEAPHDR_USER_FLAG(1) /* object is constructable */
  5748. #define DUK_HOBJECT_FLAG_BOUND DUK_HEAPHDR_USER_FLAG(2) /* object established using Function.prototype.bind() */
  5749. #define DUK_HOBJECT_FLAG_COMPILEDFUNCTION DUK_HEAPHDR_USER_FLAG(4) /* object is a compiled function (duk_hcompiledfunction) */
  5750. #define DUK_HOBJECT_FLAG_NATIVEFUNCTION DUK_HEAPHDR_USER_FLAG(5) /* object is a native function (duk_hnativefunction) */
  5751. #define DUK_HOBJECT_FLAG_THREAD DUK_HEAPHDR_USER_FLAG(6) /* object is a thread (duk_hthread) */
  5752. #define DUK_HOBJECT_FLAG_ARRAY_PART DUK_HEAPHDR_USER_FLAG(7) /* object has an array part (a_size may still be 0) */
  5753. #define DUK_HOBJECT_FLAG_STRICT DUK_HEAPHDR_USER_FLAG(8) /* function: function object is strict */
  5754. #define DUK_HOBJECT_FLAG_NOTAIL DUK_HEAPHDR_USER_FLAG(9) /* function: function must not be tailcalled */
  5755. #define DUK_HOBJECT_FLAG_NEWENV DUK_HEAPHDR_USER_FLAG(10) /* function: create new environment when called (see duk_hcompiledfunction) */
  5756. #define DUK_HOBJECT_FLAG_NAMEBINDING DUK_HEAPHDR_USER_FLAG(11) /* function: create binding for func name (function templates only, used for named function expressions) */
  5757. #define DUK_HOBJECT_FLAG_CREATEARGS DUK_HEAPHDR_USER_FLAG(12) /* function: create an arguments object on function call */
  5758. #define DUK_HOBJECT_FLAG_ENVRECCLOSED DUK_HEAPHDR_USER_FLAG(13) /* envrec: (declarative) record is closed */
  5759. #define DUK_HOBJECT_FLAG_EXOTIC_ARRAY DUK_HEAPHDR_USER_FLAG(14) /* 'Array' object, array length and index exotic behavior */
  5760. #define DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ DUK_HEAPHDR_USER_FLAG(15) /* 'String' object, array index exotic behavior */
  5761. #define DUK_HOBJECT_FLAG_EXOTIC_ARGUMENTS DUK_HEAPHDR_USER_FLAG(16) /* 'Arguments' object and has arguments exotic behavior (non-strict callee) */
  5762. #define DUK_HOBJECT_FLAG_EXOTIC_DUKFUNC DUK_HEAPHDR_USER_FLAG(17) /* Duktape/C (nativefunction) object, exotic 'length' */
  5763. #define DUK_HOBJECT_FLAG_EXOTIC_BUFFEROBJ DUK_HEAPHDR_USER_FLAG(18) /* 'Buffer' object, array index exotic behavior, virtual 'length' */
  5764. #define DUK_HOBJECT_FLAG_EXOTIC_PROXYOBJ DUK_HEAPHDR_USER_FLAG(19) /* 'Proxy' object */
  5765. /* bit 20 unused */
  5766. #define DUK_HOBJECT_FLAG_CLASS_BASE DUK_HEAPHDR_USER_FLAG_NUMBER(21)
  5767. #define DUK_HOBJECT_FLAG_CLASS_BITS 5
  5768. #define DUK_HOBJECT_GET_CLASS_NUMBER(h) \
  5769. DUK_HEAPHDR_GET_FLAG_RANGE(&(h)->hdr, DUK_HOBJECT_FLAG_CLASS_BASE, DUK_HOBJECT_FLAG_CLASS_BITS)
  5770. #define DUK_HOBJECT_SET_CLASS_NUMBER(h,v) \
  5771. DUK_HEAPHDR_SET_FLAG_RANGE(&(h)->hdr, DUK_HOBJECT_FLAG_CLASS_BASE, DUK_HOBJECT_FLAG_CLASS_BITS, (v))
  5772. /* Macro for creating flag initializer from a class number.
  5773. * Unsigned type cast is needed to avoid warnings about coercing
  5774. * a signed integer to an unsigned one; the largest class values
  5775. * have the highest bit (bit 31) set which causes this.
  5776. */
  5777. #define DUK_HOBJECT_CLASS_AS_FLAGS(v) (((duk_uint_t) (v)) << DUK_HOBJECT_FLAG_CLASS_BASE)
  5778. /* E5 Section 8.6.2 + custom classes */
  5779. #define DUK_HOBJECT_CLASS_UNUSED 0
  5780. #define DUK_HOBJECT_CLASS_ARGUMENTS 1
  5781. #define DUK_HOBJECT_CLASS_ARRAY 2
  5782. #define DUK_HOBJECT_CLASS_BOOLEAN 3
  5783. #define DUK_HOBJECT_CLASS_DATE 4
  5784. #define DUK_HOBJECT_CLASS_ERROR 5
  5785. #define DUK_HOBJECT_CLASS_FUNCTION 6
  5786. #define DUK_HOBJECT_CLASS_JSON 7
  5787. #define DUK_HOBJECT_CLASS_MATH 8
  5788. #define DUK_HOBJECT_CLASS_NUMBER 9
  5789. #define DUK_HOBJECT_CLASS_OBJECT 10
  5790. #define DUK_HOBJECT_CLASS_REGEXP 11
  5791. #define DUK_HOBJECT_CLASS_STRING 12
  5792. #define DUK_HOBJECT_CLASS_GLOBAL 13
  5793. #define DUK_HOBJECT_CLASS_OBJENV 14 /* custom */
  5794. #define DUK_HOBJECT_CLASS_DECENV 15 /* custom */
  5795. #define DUK_HOBJECT_CLASS_BUFFER 16 /* custom */
  5796. #define DUK_HOBJECT_CLASS_POINTER 17 /* custom */
  5797. #define DUK_HOBJECT_CLASS_THREAD 18 /* custom */
  5798. #define DUK_HOBJECT_IS_OBJENV(h) (DUK_HOBJECT_GET_CLASS_NUMBER((h)) == DUK_HOBJECT_CLASS_OBJENV)
  5799. #define DUK_HOBJECT_IS_DECENV(h) (DUK_HOBJECT_GET_CLASS_NUMBER((h)) == DUK_HOBJECT_CLASS_DECENV)
  5800. #define DUK_HOBJECT_IS_ENV(h) (DUK_HOBJECT_IS_OBJENV((h)) || DUK_HOBJECT_IS_DECENV((h)))
  5801. #define DUK_HOBJECT_IS_ARRAY(h) (DUK_HOBJECT_GET_CLASS_NUMBER((h)) == DUK_HOBJECT_CLASS_ARRAY)
  5802. #define DUK_HOBJECT_IS_COMPILEDFUNCTION(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_COMPILEDFUNCTION)
  5803. #define DUK_HOBJECT_IS_NATIVEFUNCTION(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NATIVEFUNCTION)
  5804. #define DUK_HOBJECT_IS_THREAD(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_THREAD)
  5805. #define DUK_HOBJECT_IS_NONBOUND_FUNCTION(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, \
  5806. DUK_HOBJECT_FLAG_COMPILEDFUNCTION | \
  5807. DUK_HOBJECT_FLAG_NATIVEFUNCTION)
  5808. #define DUK_HOBJECT_IS_FUNCTION(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, \
  5809. DUK_HOBJECT_FLAG_BOUND | \
  5810. DUK_HOBJECT_FLAG_COMPILEDFUNCTION | \
  5811. DUK_HOBJECT_FLAG_NATIVEFUNCTION)
  5812. #define DUK_HOBJECT_IS_CALLABLE(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, \
  5813. DUK_HOBJECT_FLAG_BOUND | \
  5814. DUK_HOBJECT_FLAG_COMPILEDFUNCTION | \
  5815. DUK_HOBJECT_FLAG_NATIVEFUNCTION)
  5816. /* object has any exotic behavior(s) */
  5817. #define DUK_HOBJECT_EXOTIC_BEHAVIOR_FLAGS (DUK_HOBJECT_FLAG_EXOTIC_ARRAY | \
  5818. DUK_HOBJECT_FLAG_EXOTIC_ARGUMENTS | \
  5819. DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ | \
  5820. DUK_HOBJECT_FLAG_EXOTIC_DUKFUNC | \
  5821. DUK_HOBJECT_FLAG_EXOTIC_BUFFEROBJ | \
  5822. DUK_HOBJECT_FLAG_EXOTIC_PROXYOBJ)
  5823. #define DUK_HOBJECT_HAS_EXOTIC_BEHAVIOR(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_EXOTIC_BEHAVIOR_FLAGS)
  5824. #define DUK_HOBJECT_HAS_EXTENSIBLE(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXTENSIBLE)
  5825. #define DUK_HOBJECT_HAS_CONSTRUCTABLE(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_CONSTRUCTABLE)
  5826. #define DUK_HOBJECT_HAS_BOUND(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_BOUND)
  5827. #define DUK_HOBJECT_HAS_COMPILEDFUNCTION(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_COMPILEDFUNCTION)
  5828. #define DUK_HOBJECT_HAS_NATIVEFUNCTION(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NATIVEFUNCTION)
  5829. #define DUK_HOBJECT_HAS_THREAD(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_THREAD)
  5830. #define DUK_HOBJECT_HAS_ARRAY_PART(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_ARRAY_PART)
  5831. #define DUK_HOBJECT_HAS_STRICT(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_STRICT)
  5832. #define DUK_HOBJECT_HAS_NOTAIL(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NOTAIL)
  5833. #define DUK_HOBJECT_HAS_NEWENV(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NEWENV)
  5834. #define DUK_HOBJECT_HAS_NAMEBINDING(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NAMEBINDING)
  5835. #define DUK_HOBJECT_HAS_CREATEARGS(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_CREATEARGS)
  5836. #define DUK_HOBJECT_HAS_ENVRECCLOSED(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_ENVRECCLOSED)
  5837. #define DUK_HOBJECT_HAS_EXOTIC_ARRAY(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_ARRAY)
  5838. #define DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ)
  5839. #define DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_ARGUMENTS)
  5840. #define DUK_HOBJECT_HAS_EXOTIC_DUKFUNC(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_DUKFUNC)
  5841. #define DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_BUFFEROBJ)
  5842. #define DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(h) DUK_HEAPHDR_CHECK_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_PROXYOBJ)
  5843. #define DUK_HOBJECT_SET_EXTENSIBLE(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXTENSIBLE)
  5844. #define DUK_HOBJECT_SET_CONSTRUCTABLE(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_CONSTRUCTABLE)
  5845. #define DUK_HOBJECT_SET_BOUND(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_BOUND)
  5846. #define DUK_HOBJECT_SET_COMPILEDFUNCTION(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_COMPILEDFUNCTION)
  5847. #define DUK_HOBJECT_SET_NATIVEFUNCTION(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NATIVEFUNCTION)
  5848. #define DUK_HOBJECT_SET_THREAD(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_THREAD)
  5849. #define DUK_HOBJECT_SET_ARRAY_PART(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_ARRAY_PART)
  5850. #define DUK_HOBJECT_SET_STRICT(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_STRICT)
  5851. #define DUK_HOBJECT_SET_NOTAIL(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NOTAIL)
  5852. #define DUK_HOBJECT_SET_NEWENV(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NEWENV)
  5853. #define DUK_HOBJECT_SET_NAMEBINDING(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NAMEBINDING)
  5854. #define DUK_HOBJECT_SET_CREATEARGS(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_CREATEARGS)
  5855. #define DUK_HOBJECT_SET_ENVRECCLOSED(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_ENVRECCLOSED)
  5856. #define DUK_HOBJECT_SET_EXOTIC_ARRAY(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_ARRAY)
  5857. #define DUK_HOBJECT_SET_EXOTIC_STRINGOBJ(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ)
  5858. #define DUK_HOBJECT_SET_EXOTIC_ARGUMENTS(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_ARGUMENTS)
  5859. #define DUK_HOBJECT_SET_EXOTIC_DUKFUNC(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_DUKFUNC)
  5860. #define DUK_HOBJECT_SET_EXOTIC_BUFFEROBJ(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_BUFFEROBJ)
  5861. #define DUK_HOBJECT_SET_EXOTIC_PROXYOBJ(h) DUK_HEAPHDR_SET_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_PROXYOBJ)
  5862. #define DUK_HOBJECT_CLEAR_EXTENSIBLE(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXTENSIBLE)
  5863. #define DUK_HOBJECT_CLEAR_CONSTRUCTABLE(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_CONSTRUCTABLE)
  5864. #define DUK_HOBJECT_CLEAR_BOUND(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_BOUND)
  5865. #define DUK_HOBJECT_CLEAR_COMPILEDFUNCTION(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_COMPILEDFUNCTION)
  5866. #define DUK_HOBJECT_CLEAR_NATIVEFUNCTION(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NATIVEFUNCTION)
  5867. #define DUK_HOBJECT_CLEAR_THREAD(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_THREAD)
  5868. #define DUK_HOBJECT_CLEAR_ARRAY_PART(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_ARRAY_PART)
  5869. #define DUK_HOBJECT_CLEAR_STRICT(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_STRICT)
  5870. #define DUK_HOBJECT_CLEAR_NOTAIL(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NOTAIL)
  5871. #define DUK_HOBJECT_CLEAR_NEWENV(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NEWENV)
  5872. #define DUK_HOBJECT_CLEAR_NAMEBINDING(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_NAMEBINDING)
  5873. #define DUK_HOBJECT_CLEAR_CREATEARGS(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_CREATEARGS)
  5874. #define DUK_HOBJECT_CLEAR_ENVRECCLOSED(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_ENVRECCLOSED)
  5875. #define DUK_HOBJECT_CLEAR_EXOTIC_ARRAY(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_ARRAY)
  5876. #define DUK_HOBJECT_CLEAR_EXOTIC_STRINGOBJ(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ)
  5877. #define DUK_HOBJECT_CLEAR_EXOTIC_ARGUMENTS(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_ARGUMENTS)
  5878. #define DUK_HOBJECT_CLEAR_EXOTIC_DUKFUNC(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_DUKFUNC)
  5879. #define DUK_HOBJECT_CLEAR_EXOTIC_BUFFEROBJ(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_BUFFEROBJ)
  5880. #define DUK_HOBJECT_CLEAR_EXOTIC_PROXYOBJ(h) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(h)->hdr, DUK_HOBJECT_FLAG_EXOTIC_PROXYOBJ)
  5881. /* flags used for property attributes in duk_propdesc and packed flags */
  5882. #define DUK_PROPDESC_FLAG_WRITABLE (1 << 0) /* E5 Section 8.6.1 */
  5883. #define DUK_PROPDESC_FLAG_ENUMERABLE (1 << 1) /* E5 Section 8.6.1 */
  5884. #define DUK_PROPDESC_FLAG_CONFIGURABLE (1 << 2) /* E5 Section 8.6.1 */
  5885. #define DUK_PROPDESC_FLAG_ACCESSOR (1 << 3) /* accessor */
  5886. #define DUK_PROPDESC_FLAG_VIRTUAL (1 << 4) /* property is virtual: used in duk_propdesc, never stored
  5887. * (used by e.g. buffer virtual properties)
  5888. */
  5889. #define DUK_PROPDESC_FLAGS_MASK (DUK_PROPDESC_FLAG_WRITABLE | \
  5890. DUK_PROPDESC_FLAG_ENUMERABLE | \
  5891. DUK_PROPDESC_FLAG_CONFIGURABLE | \
  5892. DUK_PROPDESC_FLAG_ACCESSOR)
  5893. /* additional flags which are passed in the same flags argument as property
  5894. * flags but are not stored in object properties.
  5895. */
  5896. #define DUK_PROPDESC_FLAG_NO_OVERWRITE (1 << 4) /* internal define property: skip write silently if exists */
  5897. /* convenience */
  5898. #define DUK_PROPDESC_FLAGS_NONE 0
  5899. #define DUK_PROPDESC_FLAGS_W (DUK_PROPDESC_FLAG_WRITABLE)
  5900. #define DUK_PROPDESC_FLAGS_E (DUK_PROPDESC_FLAG_ENUMERABLE)
  5901. #define DUK_PROPDESC_FLAGS_C (DUK_PROPDESC_FLAG_CONFIGURABLE)
  5902. #define DUK_PROPDESC_FLAGS_WE (DUK_PROPDESC_FLAG_WRITABLE | DUK_PROPDESC_FLAG_ENUMERABLE)
  5903. #define DUK_PROPDESC_FLAGS_WC (DUK_PROPDESC_FLAG_WRITABLE | DUK_PROPDESC_FLAG_CONFIGURABLE)
  5904. #define DUK_PROPDESC_FLAGS_EC (DUK_PROPDESC_FLAG_ENUMERABLE | DUK_PROPDESC_FLAG_CONFIGURABLE)
  5905. #define DUK_PROPDESC_FLAGS_WEC (DUK_PROPDESC_FLAG_WRITABLE | \
  5906. DUK_PROPDESC_FLAG_ENUMERABLE | \
  5907. DUK_PROPDESC_FLAG_CONFIGURABLE)
  5908. /*
  5909. * Macros to access the 'props' allocation.
  5910. */
  5911. #if defined(DUK_USE_HEAPPTR16)
  5912. #define DUK_HOBJECT_GET_PROPS(heap,h) \
  5913. ((duk_uint8_t *) DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, ((duk_heaphdr *) (h))->h_extra16))
  5914. #define DUK_HOBJECT_SET_PROPS(heap,h,x) do { \
  5915. ((duk_heaphdr *) (h))->h_extra16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) (x)); \
  5916. } while (0)
  5917. #else
  5918. #define DUK_HOBJECT_GET_PROPS(heap,h) \
  5919. ((h)->props)
  5920. #define DUK_HOBJECT_SET_PROPS(heap,h,x) do { \
  5921. (h)->props = (x); \
  5922. } while (0)
  5923. #endif
  5924. #if defined(DUK_USE_HOBJECT_LAYOUT_1)
  5925. /* LAYOUT 1 */
  5926. #define DUK_HOBJECT_E_GET_KEY_BASE(heap,h) \
  5927. ((duk_hstring **) ( \
  5928. DUK_HOBJECT_GET_PROPS((heap), (h)) \
  5929. ))
  5930. #define DUK_HOBJECT_E_GET_VALUE_BASE(heap,h) \
  5931. ((duk_propvalue *) ( \
  5932. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  5933. DUK_HOBJECT_GET_ESIZE((h)) * sizeof(duk_hstring *) \
  5934. ))
  5935. #define DUK_HOBJECT_E_GET_FLAGS_BASE(heap,h) \
  5936. ((duk_uint8_t *) ( \
  5937. DUK_HOBJECT_GET_PROPS((heap), (h)) + DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_hstring *) + sizeof(duk_propvalue)) \
  5938. ))
  5939. #define DUK_HOBJECT_A_GET_BASE(heap,h) \
  5940. ((duk_tval *) ( \
  5941. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  5942. DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_hstring *) + sizeof(duk_propvalue) + sizeof(duk_uint8_t)) \
  5943. ))
  5944. #define DUK_HOBJECT_H_GET_BASE(heap,h) \
  5945. ((duk_uint32_t *) ( \
  5946. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  5947. DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_hstring *) + sizeof(duk_propvalue) + sizeof(duk_uint8_t)) + \
  5948. DUK_HOBJECT_GET_ASIZE((h)) * sizeof(duk_tval) \
  5949. ))
  5950. #define DUK_HOBJECT_P_COMPUTE_SIZE(n_ent,n_arr,n_hash) \
  5951. ( \
  5952. (n_ent) * (sizeof(duk_hstring *) + sizeof(duk_propvalue) + sizeof(duk_uint8_t)) + \
  5953. (n_arr) * sizeof(duk_tval) + \
  5954. (n_hash) * sizeof(duk_uint32_t) \
  5955. )
  5956. #define DUK_HOBJECT_P_SET_REALLOC_PTRS(p_base,set_e_k,set_e_pv,set_e_f,set_a,set_h,n_ent,n_arr,n_hash) do { \
  5957. (set_e_k) = (duk_hstring **) (p_base); \
  5958. (set_e_pv) = (duk_propvalue *) ((set_e_k) + (n_ent)); \
  5959. (set_e_f) = (duk_uint8_t *) ((set_e_pv) + (n_ent)); \
  5960. (set_a) = (duk_tval *) ((set_e_f) + (n_ent)); \
  5961. (set_h) = (duk_uint32_t *) ((set_a) + (n_arr)); \
  5962. } while (0)
  5963. #elif defined(DUK_USE_HOBJECT_LAYOUT_2)
  5964. /* LAYOUT 2 */
  5965. #if defined(DUK_USE_ALIGN_4)
  5966. #define DUK_HOBJECT_E_FLAG_PADDING(e_sz) ((4 - (e_sz)) & 0x03)
  5967. #elif defined(DUK_USE_ALIGN_8)
  5968. #define DUK_HOBJECT_E_FLAG_PADDING(e_sz) ((8 - (e_sz)) & 0x07)
  5969. #else
  5970. #define DUK_HOBJECT_E_FLAG_PADDING(e_sz) 0
  5971. #endif
  5972. #define DUK_HOBJECT_E_GET_KEY_BASE(heap,h) \
  5973. ((duk_hstring **) ( \
  5974. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  5975. DUK_HOBJECT_GET_ESIZE((h)) * sizeof(duk_propvalue) \
  5976. ))
  5977. #define DUK_HOBJECT_E_GET_VALUE_BASE(heap,h) \
  5978. ((duk_propvalue *) ( \
  5979. DUK_HOBJECT_GET_PROPS((heap), (h)) \
  5980. ))
  5981. #define DUK_HOBJECT_E_GET_FLAGS_BASE(heap,h) \
  5982. ((duk_uint8_t *) ( \
  5983. DUK_HOBJECT_GET_PROPS((heap), (h)) + DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_hstring *) + sizeof(duk_propvalue)) \
  5984. ))
  5985. #define DUK_HOBJECT_A_GET_BASE(heap,h) \
  5986. ((duk_tval *) ( \
  5987. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  5988. DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_hstring *) + sizeof(duk_propvalue) + sizeof(duk_uint8_t)) + \
  5989. DUK_HOBJECT_E_FLAG_PADDING(DUK_HOBJECT_GET_ESIZE((h))) \
  5990. ))
  5991. #define DUK_HOBJECT_H_GET_BASE(heap,h) \
  5992. ((duk_uint32_t *) ( \
  5993. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  5994. DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_hstring *) + sizeof(duk_propvalue) + sizeof(duk_uint8_t)) + \
  5995. DUK_HOBJECT_E_FLAG_PADDING(DUK_HOBJECT_GET_ESIZE((h))) + \
  5996. DUK_HOBJECT_GET_ASIZE((h)) * sizeof(duk_tval) \
  5997. ))
  5998. #define DUK_HOBJECT_P_COMPUTE_SIZE(n_ent,n_arr,n_hash) \
  5999. ( \
  6000. (n_ent) * (sizeof(duk_hstring *) + sizeof(duk_propvalue) + sizeof(duk_uint8_t)) + \
  6001. DUK_HOBJECT_E_FLAG_PADDING((n_ent)) + \
  6002. (n_arr) * sizeof(duk_tval) + \
  6003. (n_hash) * sizeof(duk_uint32_t) \
  6004. )
  6005. #define DUK_HOBJECT_P_SET_REALLOC_PTRS(p_base,set_e_k,set_e_pv,set_e_f,set_a,set_h,n_ent,n_arr,n_hash) do { \
  6006. (set_e_pv) = (duk_propvalue *) (p_base); \
  6007. (set_e_k) = (duk_hstring **) ((set_e_pv) + (n_ent)); \
  6008. (set_e_f) = (duk_uint8_t *) ((set_e_k) + (n_ent)); \
  6009. (set_a) = (duk_tval *) (((duk_uint8_t *) (set_e_f)) + \
  6010. sizeof(duk_uint8_t) * (n_ent) + \
  6011. DUK_HOBJECT_E_FLAG_PADDING((n_ent))); \
  6012. (set_h) = (duk_uint32_t *) ((set_a) + (n_arr)); \
  6013. } while (0)
  6014. #elif defined(DUK_USE_HOBJECT_LAYOUT_3)
  6015. /* LAYOUT 3 */
  6016. #define DUK_HOBJECT_E_GET_KEY_BASE(heap,h) \
  6017. ((duk_hstring **) ( \
  6018. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  6019. DUK_HOBJECT_GET_ESIZE((h)) * sizeof(duk_propvalue) + \
  6020. DUK_HOBJECT_GET_ASIZE((h)) * sizeof(duk_tval) \
  6021. ))
  6022. #define DUK_HOBJECT_E_GET_VALUE_BASE(heap,h) \
  6023. ((duk_propvalue *) ( \
  6024. DUK_HOBJECT_GET_PROPS((heap), (h)) \
  6025. ))
  6026. #define DUK_HOBJECT_E_GET_FLAGS_BASE(heap,h) \
  6027. ((duk_uint8_t *) ( \
  6028. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  6029. DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_propvalue) + sizeof(duk_hstring *)) + \
  6030. DUK_HOBJECT_GET_ASIZE((h)) * sizeof(duk_tval) + \
  6031. DUK_HOBJECT_GET_HSIZE((h)) * sizeof(duk_uint32_t) \
  6032. ))
  6033. #define DUK_HOBJECT_A_GET_BASE(heap,h) \
  6034. ((duk_tval *) ( \
  6035. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  6036. DUK_HOBJECT_GET_ESIZE((h)) * sizeof(duk_propvalue) \
  6037. ))
  6038. #define DUK_HOBJECT_H_GET_BASE(heap,h) \
  6039. ((duk_uint32_t *) ( \
  6040. DUK_HOBJECT_GET_PROPS((heap), (h)) + \
  6041. DUK_HOBJECT_GET_ESIZE((h)) * (sizeof(duk_propvalue) + sizeof(duk_hstring *)) + \
  6042. DUK_HOBJECT_GET_ASIZE((h)) * sizeof(duk_tval) \
  6043. ))
  6044. #define DUK_HOBJECT_P_COMPUTE_SIZE(n_ent,n_arr,n_hash) \
  6045. ( \
  6046. (n_ent) * (sizeof(duk_propvalue) + sizeof(duk_hstring *) + sizeof(duk_uint8_t)) + \
  6047. (n_arr) * sizeof(duk_tval) + \
  6048. (n_hash) * sizeof(duk_uint32_t) \
  6049. )
  6050. #define DUK_HOBJECT_P_SET_REALLOC_PTRS(p_base,set_e_k,set_e_pv,set_e_f,set_a,set_h,n_ent,n_arr,n_hash) do { \
  6051. (set_e_pv) = (duk_propvalue *) (p_base); \
  6052. (set_a) = (duk_tval *) ((set_e_pv) + (n_ent)); \
  6053. (set_e_k) = (duk_hstring **) ((set_a) + (n_arr)); \
  6054. (set_h) = (duk_uint32_t *) ((set_e_k) + (n_ent)); \
  6055. (set_e_f) = (duk_uint8_t *) ((set_h) + (n_hash)); \
  6056. } while (0)
  6057. #else
  6058. #error invalid hobject layout defines
  6059. #endif /* hobject property layout */
  6060. #define DUK_HOBJECT_E_ALLOC_SIZE(h) \
  6061. DUK_HOBJECT_P_COMPUTE_SIZE(DUK_HOBJECT_GET_ESIZE((h)), DUK_HOBJECT_GET_ASIZE((h)), DUK_HOBJECT_GET_HSIZE((h)))
  6062. #define DUK_HOBJECT_E_GET_KEY(heap,h,i) (DUK_HOBJECT_E_GET_KEY_BASE((heap), (h))[(i)])
  6063. #define DUK_HOBJECT_E_GET_KEY_PTR(heap,h,i) (&DUK_HOBJECT_E_GET_KEY_BASE((heap), (h))[(i)])
  6064. #define DUK_HOBJECT_E_GET_VALUE(heap,h,i) (DUK_HOBJECT_E_GET_VALUE_BASE((heap), (h))[(i)])
  6065. #define DUK_HOBJECT_E_GET_VALUE_PTR(heap,h,i) (&DUK_HOBJECT_E_GET_VALUE_BASE((heap), (h))[(i)])
  6066. #define DUK_HOBJECT_E_GET_VALUE_TVAL(heap,h,i) (DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).v)
  6067. #define DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(heap,h,i) (&DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).v)
  6068. #define DUK_HOBJECT_E_GET_VALUE_GETTER(heap,h,i) (DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).a.get)
  6069. #define DUK_HOBJECT_E_GET_VALUE_GETTER_PTR(heap,h,i) (&DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).a.get)
  6070. #define DUK_HOBJECT_E_GET_VALUE_SETTER(heap,h,i) (DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).a.set)
  6071. #define DUK_HOBJECT_E_GET_VALUE_SETTER_PTR(heap,h,i) (&DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).a.set)
  6072. #define DUK_HOBJECT_E_GET_FLAGS(heap,h,i) (DUK_HOBJECT_E_GET_FLAGS_BASE((heap), (h))[(i)])
  6073. #define DUK_HOBJECT_E_GET_FLAGS_PTR(heap,h,i) (&DUK_HOBJECT_E_GET_FLAGS_BASE((heap), (h))[(i)])
  6074. #define DUK_HOBJECT_A_GET_VALUE(heap,h,i) (DUK_HOBJECT_A_GET_BASE((heap), (h))[(i)])
  6075. #define DUK_HOBJECT_A_GET_VALUE_PTR(heap,h,i) (&DUK_HOBJECT_A_GET_BASE((heap), (h))[(i)])
  6076. #define DUK_HOBJECT_H_GET_INDEX(heap,h,i) (DUK_HOBJECT_H_GET_BASE((heap), (h))[(i)])
  6077. #define DUK_HOBJECT_H_GET_INDEX_PTR(heap,h,i) (&DUK_HOBJECT_H_GET_BASE((heap), (h))[(i)])
  6078. #define DUK_HOBJECT_E_SET_KEY(heap,h,i,k) do { \
  6079. DUK_HOBJECT_E_GET_KEY((heap), (h), (i)) = (k); \
  6080. } while (0)
  6081. #define DUK_HOBJECT_E_SET_VALUE(heap,h,i,v) do { \
  6082. DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)) = (v); \
  6083. } while (0)
  6084. #define DUK_HOBJECT_E_SET_VALUE_TVAL(heap,h,i,v) do { \
  6085. DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).v = (v); \
  6086. } while (0)
  6087. #define DUK_HOBJECT_E_SET_VALUE_GETTER(heap,h,i,v) do { \
  6088. DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).a.get = (v); \
  6089. } while (0)
  6090. #define DUK_HOBJECT_E_SET_VALUE_SETTER(heap,h,i,v) do { \
  6091. DUK_HOBJECT_E_GET_VALUE((heap), (h), (i)).a.set = (v); \
  6092. } while (0)
  6093. #define DUK_HOBJECT_E_SET_FLAGS(heap,h,i,f) do { \
  6094. DUK_HOBJECT_E_GET_FLAGS((heap), (h), (i)) = (f); \
  6095. } while (0)
  6096. #define DUK_HOBJECT_A_SET_VALUE(heap,h,i,v) do { \
  6097. DUK_HOBJECT_A_GET_VALUE((heap), (h), (i)) = (v); \
  6098. } while (0)
  6099. #define DUK_HOBJECT_A_SET_VALUE_TVAL(heap,h,i,v) \
  6100. DUK_HOBJECT_A_SET_VALUE((heap), (h), (i), (v)) /* alias for above */
  6101. #define DUK_HOBJECT_H_SET_INDEX(heap,h,i,v) do { \
  6102. DUK_HOBJECT_H_GET_INDEX((heap), (h), (i)) = (v); \
  6103. } while (0)
  6104. #define DUK_HOBJECT_E_SET_FLAG_BITS(heap,h,i,mask) do { \
  6105. DUK_HOBJECT_E_GET_FLAGS_BASE((heap), (h))[(i)] |= (mask); \
  6106. } while (0)
  6107. #define DUK_HOBJECT_E_CLEAR_FLAG_BITS(heap,h,i,mask) do { \
  6108. DUK_HOBJECT_E_GET_FLAGS_BASE((heap), (h))[(i)] &= ~(mask); \
  6109. } while (0)
  6110. #define DUK_HOBJECT_E_SLOT_IS_WRITABLE(heap,h,i) ((DUK_HOBJECT_E_GET_FLAGS((heap), (h), (i)) & DUK_PROPDESC_FLAG_WRITABLE) != 0)
  6111. #define DUK_HOBJECT_E_SLOT_IS_ENUMERABLE(heap,h,i) ((DUK_HOBJECT_E_GET_FLAGS((heap), (h), (i)) & DUK_PROPDESC_FLAG_ENUMERABLE) != 0)
  6112. #define DUK_HOBJECT_E_SLOT_IS_CONFIGURABLE(heap,h,i) ((DUK_HOBJECT_E_GET_FLAGS((heap), (h), (i)) & DUK_PROPDESC_FLAG_CONFIGURABLE) != 0)
  6113. #define DUK_HOBJECT_E_SLOT_IS_ACCESSOR(heap,h,i) ((DUK_HOBJECT_E_GET_FLAGS((heap), (h), (i)) & DUK_PROPDESC_FLAG_ACCESSOR) != 0)
  6114. #define DUK_HOBJECT_E_SLOT_SET_WRITABLE(heap,h,i) DUK_HOBJECT_E_SET_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_WRITABLE)
  6115. #define DUK_HOBJECT_E_SLOT_SET_ENUMERABLE(heap,h,i) DUK_HOBJECT_E_SET_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_ENUMERABLE)
  6116. #define DUK_HOBJECT_E_SLOT_SET_CONFIGURABLE(heap,h,i) DUK_HOBJECT_E_SET_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_CONFIGURABLE)
  6117. #define DUK_HOBJECT_E_SLOT_SET_ACCESSOR(heap,h,i) DUK_HOBJECT_E_SET_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_ACCESSOR)
  6118. #define DUK_HOBJECT_E_SLOT_CLEAR_WRITABLE(heap,h,i) DUK_HOBJECT_E_CLEAR_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_WRITABLE)
  6119. #define DUK_HOBJECT_E_SLOT_CLEAR_ENUMERABLE(heap,h,i) DUK_HOBJECT_E_CLEAR_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_ENUMERABLE)
  6120. #define DUK_HOBJECT_E_SLOT_CLEAR_CONFIGURABLE(heap,h,i) DUK_HOBJECT_E_CLEAR_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_CONFIGURABLE)
  6121. #define DUK_HOBJECT_E_SLOT_CLEAR_ACCESSOR(heap,h,i) DUK_HOBJECT_E_CLEAR_FLAG_BITS((heap), (h), (i),DUK_PROPDESC_FLAG_ACCESSOR)
  6122. #define DUK_PROPDESC_IS_WRITABLE(p) (((p)->flags & DUK_PROPDESC_FLAG_WRITABLE) != 0)
  6123. #define DUK_PROPDESC_IS_ENUMERABLE(p) (((p)->flags & DUK_PROPDESC_FLAG_ENUMERABLE) != 0)
  6124. #define DUK_PROPDESC_IS_CONFIGURABLE(p) (((p)->flags & DUK_PROPDESC_FLAG_CONFIGURABLE) != 0)
  6125. #define DUK_PROPDESC_IS_ACCESSOR(p) (((p)->flags & DUK_PROPDESC_FLAG_ACCESSOR) != 0)
  6126. #define DUK_HOBJECT_HASHIDX_UNUSED 0xffffffffUL
  6127. #define DUK_HOBJECT_HASHIDX_DELETED 0xfffffffeUL
  6128. /*
  6129. * Macros for accessing size fields
  6130. */
  6131. #if defined(DUK_USE_OBJSIZES16)
  6132. #define DUK_HOBJECT_GET_ESIZE(h) ((h)->e_size16)
  6133. #define DUK_HOBJECT_SET_ESIZE(h,v) do { (h)->e_size16 = (v); } while (0)
  6134. #define DUK_HOBJECT_GET_ENEXT(h) ((h)->e_next16)
  6135. #define DUK_HOBJECT_SET_ENEXT(h,v) do { (h)->e_next16 = (v); } while (0)
  6136. #define DUK_HOBJECT_POSTINC_ENEXT(h) ((h)->e_next16++)
  6137. #define DUK_HOBJECT_GET_ASIZE(h) ((h)->a_size16)
  6138. #define DUK_HOBJECT_SET_ASIZE(h,v) do { (h)->a_size16 = (v); } while (0)
  6139. #if defined(DUK_USE_HOBJECT_HASH_PART)
  6140. #define DUK_HOBJECT_GET_HSIZE(h) ((h)->h_size16)
  6141. #define DUK_HOBJECT_SET_HSIZE(h,v) do { (h)->h_size16 = (v); } while (0)
  6142. #else
  6143. #define DUK_HOBJECT_GET_HSIZE(h) 0
  6144. #define DUK_HOBJECT_SET_HSIZE(h,v) do { DUK_ASSERT((v) == 0); } while (0)
  6145. #endif
  6146. #else
  6147. #define DUK_HOBJECT_GET_ESIZE(h) ((h)->e_size)
  6148. #define DUK_HOBJECT_SET_ESIZE(h,v) do { (h)->e_size = (v); } while (0)
  6149. #define DUK_HOBJECT_GET_ENEXT(h) ((h)->e_next)
  6150. #define DUK_HOBJECT_SET_ENEXT(h,v) do { (h)->e_next = (v); } while (0)
  6151. #define DUK_HOBJECT_POSTINC_ENEXT(h) ((h)->e_next++)
  6152. #define DUK_HOBJECT_GET_ASIZE(h) ((h)->a_size)
  6153. #define DUK_HOBJECT_SET_ASIZE(h,v) do { (h)->a_size = (v); } while (0)
  6154. #if defined(DUK_USE_HOBJECT_HASH_PART)
  6155. #define DUK_HOBJECT_GET_HSIZE(h) ((h)->h_size)
  6156. #define DUK_HOBJECT_SET_HSIZE(h,v) do { (h)->h_size = (v); } while (0)
  6157. #else
  6158. #define DUK_HOBJECT_GET_HSIZE(h) 0
  6159. #define DUK_HOBJECT_SET_HSIZE(h,v) do { DUK_ASSERT((v) == 0); } while (0)
  6160. #endif
  6161. #endif
  6162. /*
  6163. * Misc
  6164. */
  6165. /* Maximum prototype traversal depth. Sanity limit which handles e.g.
  6166. * prototype loops (even complex ones like 1->2->3->4->2->3->4->2->3->4).
  6167. */
  6168. #define DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY 10000L
  6169. /* Maximum traversal depth for "bound function" chains. */
  6170. #define DUK_HOBJECT_BOUND_CHAIN_SANITY 10000L
  6171. /*
  6172. * Ecmascript [[Class]]
  6173. */
  6174. /* range check not necessary because all 4-bit values are mapped */
  6175. #define DUK_HOBJECT_CLASS_NUMBER_TO_STRIDX(n) duk_class_number_to_stridx[(n)]
  6176. #define DUK_HOBJECT_GET_CLASS_STRING(heap,h) \
  6177. DUK_HEAP_GET_STRING( \
  6178. (heap), \
  6179. DUK_HOBJECT_CLASS_NUMBER_TO_STRIDX(DUK_HOBJECT_GET_CLASS_NUMBER((h))) \
  6180. )
  6181. /*
  6182. * Macros for property handling
  6183. */
  6184. #if defined(DUK_USE_HEAPPTR16)
  6185. #define DUK_HOBJECT_GET_PROTOTYPE(heap,h) \
  6186. ((duk_hobject *) DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (h)->prototype16))
  6187. #define DUK_HOBJECT_SET_PROTOTYPE(heap,h,x) do { \
  6188. (h)->prototype16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) (x)); \
  6189. } while (0)
  6190. #else
  6191. #define DUK_HOBJECT_GET_PROTOTYPE(heap,h) \
  6192. ((h)->prototype)
  6193. #define DUK_HOBJECT_SET_PROTOTYPE(heap,h,x) do { \
  6194. (h)->prototype = (x); \
  6195. } while (0)
  6196. #endif
  6197. /* note: this updates refcounts */
  6198. #define DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr,h,p) duk_hobject_set_prototype((thr), (h), (p))
  6199. /*
  6200. * Resizing and hash behavior
  6201. */
  6202. /* Sanity limit on max number of properties (allocated, not necessarily used).
  6203. * This is somewhat arbitrary, but if we're close to 2**32 properties some
  6204. * algorithms will fail (e.g. hash size selection, next prime selection).
  6205. * Also, we use negative array/entry table indices to indicate 'not found',
  6206. * so anything above 0x80000000 will cause trouble now.
  6207. */
  6208. #if defined(DUK_USE_OBJSIZES16)
  6209. #define DUK_HOBJECT_MAX_PROPERTIES 0x0000ffffUL
  6210. #else
  6211. #define DUK_HOBJECT_MAX_PROPERTIES 0x7fffffffUL /* 2**31-1 ~= 2G properties */
  6212. #endif
  6213. /* higher value conserves memory; also note that linear scan is cache friendly */
  6214. #define DUK_HOBJECT_E_USE_HASH_LIMIT 32
  6215. /* hash size relative to entries size: for value X, approx. hash_prime(e_size + e_size / X) */
  6216. #define DUK_HOBJECT_H_SIZE_DIVISOR 4 /* hash size approx. 1.25 times entries size */
  6217. /* if new_size < L * old_size, resize without abandon check; L = 3-bit fixed point, e.g. 9 -> 9/8 = 112.5% */
  6218. #define DUK_HOBJECT_A_FAST_RESIZE_LIMIT 9 /* 112.5%, i.e. new size less than 12.5% higher -> fast resize */
  6219. /* if density < L, abandon array part, L = 3-bit fixed point, e.g. 2 -> 2/8 = 25% */
  6220. /* limit is quite low: one array entry is 8 bytes, one normal entry is 4+1+8+4 = 17 bytes (with hash entry) */
  6221. #define DUK_HOBJECT_A_ABANDON_LIMIT 2 /* 25%, i.e. less than 25% used -> abandon */
  6222. /* internal align target for props allocation, must be 2*n for some n */
  6223. #if defined(DUK_USE_ALIGN_4)
  6224. #define DUK_HOBJECT_ALIGN_TARGET 4
  6225. #elif defined(DUK_USE_ALIGN_8)
  6226. #define DUK_HOBJECT_ALIGN_TARGET 8
  6227. #else
  6228. #define DUK_HOBJECT_ALIGN_TARGET 1
  6229. #endif
  6230. /* controls for minimum entry part growth */
  6231. #define DUK_HOBJECT_E_MIN_GROW_ADD 16
  6232. #define DUK_HOBJECT_E_MIN_GROW_DIVISOR 8 /* 2^3 -> 1/8 = 12.5% min growth */
  6233. /* controls for minimum array part growth */
  6234. #define DUK_HOBJECT_A_MIN_GROW_ADD 16
  6235. #define DUK_HOBJECT_A_MIN_GROW_DIVISOR 8 /* 2^3 -> 1/8 = 12.5% min growth */
  6236. /* probe sequence */
  6237. #define DUK_HOBJECT_HASH_INITIAL(hash,h_size) ((hash) % (h_size))
  6238. #define DUK_HOBJECT_HASH_PROBE_STEP(hash) DUK_UTIL_GET_HASH_PROBE_STEP((hash))
  6239. /*
  6240. * PC-to-line constants
  6241. */
  6242. #define DUK_PC2LINE_SKIP 64
  6243. /* maximum length for a SKIP-1 diffstream: 35 bits per entry, rounded up to bytes */
  6244. #define DUK_PC2LINE_MAX_DIFF_LENGTH (((DUK_PC2LINE_SKIP - 1) * 35 + 7) / 8)
  6245. /*
  6246. * Struct defs
  6247. */
  6248. struct duk_propaccessor {
  6249. duk_hobject *get;
  6250. duk_hobject *set;
  6251. };
  6252. union duk_propvalue {
  6253. /* The get/set pointers could be 16-bit pointer compressed but it
  6254. * would make no difference on 32-bit platforms because duk_tval is
  6255. * 8 bytes or more anyway.
  6256. */
  6257. duk_tval v;
  6258. duk_propaccessor a;
  6259. };
  6260. struct duk_propdesc {
  6261. /* read-only values 'lifted' for ease of use */
  6262. duk_small_int_t flags;
  6263. duk_hobject *get;
  6264. duk_hobject *set;
  6265. /* for updating (all are set to < 0 for virtual properties) */
  6266. duk_int_t e_idx; /* prop index in 'entry part', < 0 if not there */
  6267. duk_int_t h_idx; /* prop index in 'hash part', < 0 if not there */
  6268. duk_int_t a_idx; /* prop index in 'array part', < 0 if not there */
  6269. };
  6270. struct duk_hobject {
  6271. duk_heaphdr hdr;
  6272. /*
  6273. * 'props' contains {key,value,flags} entries, optional array entries, and
  6274. * an optional hash lookup table for non-array entries in a single 'sliced'
  6275. * allocation. There are several layout options, which differ slightly in
  6276. * generated code size/speed and alignment/padding; duk_features.h selects
  6277. * the layout used.
  6278. *
  6279. * Layout 1 (DUK_USE_HOBJECT_LAYOUT_1):
  6280. *
  6281. * e_size * sizeof(duk_hstring *) bytes of entry keys (e_next gc reachable)
  6282. * e_size * sizeof(duk_propvalue) bytes of entry values (e_next gc reachable)
  6283. * e_size * sizeof(duk_uint8_t) bytes of entry flags (e_next gc reachable)
  6284. * a_size * sizeof(duk_tval) bytes of (opt) array values (plain only) (all gc reachable)
  6285. * h_size * sizeof(duk_uint32_t) bytes of (opt) hash indexes to entries (e_size),
  6286. * 0xffffffffUL = unused, 0xfffffffeUL = deleted
  6287. *
  6288. * Layout 2 (DUK_USE_HOBJECT_LAYOUT_2):
  6289. *
  6290. * e_size * sizeof(duk_propvalue) bytes of entry values (e_next gc reachable)
  6291. * e_size * sizeof(duk_hstring *) bytes of entry keys (e_next gc reachable)
  6292. * e_size * sizeof(duk_uint8_t) + pad bytes of entry flags (e_next gc reachable)
  6293. * a_size * sizeof(duk_tval) bytes of (opt) array values (plain only) (all gc reachable)
  6294. * h_size * sizeof(duk_uint32_t) bytes of (opt) hash indexes to entries (e_size),
  6295. * 0xffffffffUL = unused, 0xfffffffeUL = deleted
  6296. *
  6297. * Layout 3 (DUK_USE_HOBJECT_LAYOUT_3):
  6298. *
  6299. * e_size * sizeof(duk_propvalue) bytes of entry values (e_next gc reachable)
  6300. * a_size * sizeof(duk_tval) bytes of (opt) array values (plain only) (all gc reachable)
  6301. * e_size * sizeof(duk_hstring *) bytes of entry keys (e_next gc reachable)
  6302. * h_size * sizeof(duk_uint32_t) bytes of (opt) hash indexes to entries (e_size),
  6303. * 0xffffffffUL = unused, 0xfffffffeUL = deleted
  6304. * e_size * sizeof(duk_uint8_t) bytes of entry flags (e_next gc reachable)
  6305. *
  6306. * In layout 1, the 'e_next' count is rounded to 4 or 8 on platforms
  6307. * requiring 4 or 8 byte alignment. This ensures proper alignment
  6308. * for the entries, at the cost of memory footprint. However, it's
  6309. * probably preferable to use another layout on such platforms instead.
  6310. *
  6311. * In layout 2, the key and value parts are swapped to avoid padding
  6312. * the key array on platforms requiring alignment by 8. The flags part
  6313. * is padded to get alignment for array entries. The 'e_next' count does
  6314. * not need to be rounded as in layout 1.
  6315. *
  6316. * In layout 3, entry values and array values are always aligned properly,
  6317. * and assuming pointers are at most 8 bytes, so are the entry keys. Hash
  6318. * indices will be properly aligned (assuming pointers are at least 4 bytes).
  6319. * Finally, flags don't need additional alignment. This layout provides
  6320. * compact allocations without padding (even on platforms with alignment
  6321. * requirements) at the cost of a bit slower lookups.
  6322. *
  6323. * Objects with few keys don't have a hash index; keys are looked up linearly,
  6324. * which is cache efficient because the keys are consecutive. Larger objects
  6325. * have a hash index part which contains integer indexes to the entries part.
  6326. *
  6327. * A single allocation reduces memory allocation overhead but requires more
  6328. * work when any part needs to be resized. A sliced allocation for entries
  6329. * makes linear key matching faster on most platforms (more locality) and
  6330. * skimps on flags size (which would be followed by 3 bytes of padding in
  6331. * most architectures if entries were placed in a struct).
  6332. *
  6333. * 'props' also contains internal properties distinguished with a non-BMP
  6334. * prefix. Often used properties should be placed early in 'props' whenever
  6335. * possible to make accessing them as fast a possible.
  6336. */
  6337. #if defined(DUK_USE_HEAPPTR16)
  6338. /* Located in duk_heaphdr h_extra16. Subclasses of duk_hobject (like
  6339. * duk_hcompiledfunction) are not free to use h_extra16 for this reason.
  6340. */
  6341. #else
  6342. duk_uint8_t *props;
  6343. #endif
  6344. /* prototype: the only internal property lifted outside 'e' as it is so central */
  6345. #if defined(DUK_USE_HEAPPTR16)
  6346. duk_uint16_t prototype16;
  6347. #else
  6348. duk_hobject *prototype;
  6349. #endif
  6350. #if defined(DUK_USE_OBJSIZES16)
  6351. duk_uint16_t e_size16;
  6352. duk_uint16_t e_next16;
  6353. duk_uint16_t a_size16;
  6354. #if defined(DUK_USE_HOBJECT_HASH_PART)
  6355. duk_uint16_t h_size16;
  6356. #endif
  6357. #else
  6358. duk_uint32_t e_size; /* entry part size */
  6359. duk_uint32_t e_next; /* index for next new key ([0,e_next[ are gc reachable) */
  6360. duk_uint32_t a_size; /* array part size (entirely gc reachable) */
  6361. #if defined(DUK_USE_HOBJECT_HASH_PART)
  6362. duk_uint32_t h_size; /* hash part size or 0 if unused */
  6363. #endif
  6364. #endif
  6365. };
  6366. /*
  6367. * Exposed data
  6368. */
  6369. #if !defined(DUK_SINGLE_FILE)
  6370. DUK_INTERNAL_DECL duk_uint8_t duk_class_number_to_stridx[32];
  6371. #endif /* !DUK_SINGLE_FILE */
  6372. /*
  6373. * Prototypes
  6374. */
  6375. /* alloc and init */
  6376. DUK_INTERNAL_DECL duk_hobject *duk_hobject_alloc(duk_heap *heap, duk_uint_t hobject_flags);
  6377. #if 0 /* unused */
  6378. DUK_INTERNAL_DECL duk_hobject *duk_hobject_alloc_checked(duk_hthread *thr, duk_uint_t hobject_flags);
  6379. #endif
  6380. DUK_INTERNAL_DECL duk_hcompiledfunction *duk_hcompiledfunction_alloc(duk_heap *heap, duk_uint_t hobject_flags);
  6381. DUK_INTERNAL_DECL duk_hnativefunction *duk_hnativefunction_alloc(duk_heap *heap, duk_uint_t hobject_flags);
  6382. DUK_INTERNAL_DECL duk_hthread *duk_hthread_alloc(duk_heap *heap, duk_uint_t hobject_flags);
  6383. /* low-level property functions */
  6384. DUK_INTERNAL_DECL void duk_hobject_find_existing_entry(duk_heap *heap, duk_hobject *obj, duk_hstring *key, duk_int_t *e_idx, duk_int_t *h_idx);
  6385. DUK_INTERNAL_DECL duk_tval *duk_hobject_find_existing_entry_tval_ptr(duk_heap *heap, duk_hobject *obj, duk_hstring *key);
  6386. DUK_INTERNAL_DECL duk_tval *duk_hobject_find_existing_entry_tval_ptr_and_attrs(duk_heap *heap, duk_hobject *obj, duk_hstring *key, duk_int_t *out_attrs);
  6387. DUK_INTERNAL_DECL duk_tval *duk_hobject_find_existing_array_entry_tval_ptr(duk_heap *heap, duk_hobject *obj, duk_uarridx_t i);
  6388. /* core property functions */
  6389. DUK_INTERNAL_DECL duk_bool_t duk_hobject_getprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key);
  6390. DUK_INTERNAL_DECL duk_bool_t duk_hobject_putprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key, duk_tval *tv_val, duk_bool_t throw_flag);
  6391. DUK_INTERNAL_DECL duk_bool_t duk_hobject_delprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key, duk_bool_t throw_flag);
  6392. DUK_INTERNAL_DECL duk_bool_t duk_hobject_hasprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key);
  6393. /* internal property functions */
  6394. #define DUK_DELPROP_FLAG_THROW (1 << 0)
  6395. #define DUK_DELPROP_FLAG_FORCE (1 << 1)
  6396. DUK_INTERNAL_DECL duk_bool_t duk_hobject_delprop_raw(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_small_uint_t flags);
  6397. DUK_INTERNAL_DECL duk_bool_t duk_hobject_hasprop_raw(duk_hthread *thr, duk_hobject *obj, duk_hstring *key);
  6398. DUK_INTERNAL_DECL void duk_hobject_define_property_internal(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_small_uint_t flags);
  6399. DUK_INTERNAL_DECL void duk_hobject_define_property_internal_arridx(duk_hthread *thr, duk_hobject *obj, duk_uarridx_t arr_idx, duk_small_uint_t flags);
  6400. DUK_INTERNAL_DECL void duk_hobject_define_accessor_internal(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_hobject *getter, duk_hobject *setter, duk_small_uint_t propflags);
  6401. DUK_INTERNAL_DECL void duk_hobject_set_length(duk_hthread *thr, duk_hobject *obj, duk_uint32_t length); /* XXX: duk_uarridx_t? */
  6402. DUK_INTERNAL_DECL void duk_hobject_set_length_zero(duk_hthread *thr, duk_hobject *obj);
  6403. DUK_INTERNAL_DECL duk_uint32_t duk_hobject_get_length(duk_hthread *thr, duk_hobject *obj); /* XXX: duk_uarridx_t? */
  6404. /* helpers for defineProperty() and defineProperties() */
  6405. DUK_INTERNAL_DECL
  6406. void duk_hobject_prepare_property_descriptor(duk_context *ctx,
  6407. duk_idx_t idx_in,
  6408. duk_uint_t *out_defprop_flags,
  6409. duk_idx_t *out_idx_value,
  6410. duk_hobject **out_getter,
  6411. duk_hobject **out_setter);
  6412. DUK_INTERNAL_DECL
  6413. void duk_hobject_define_property_helper(duk_context *ctx,
  6414. duk_uint_t defprop_flags,
  6415. duk_hobject *obj,
  6416. duk_hstring *key,
  6417. duk_idx_t idx_value,
  6418. duk_hobject *get,
  6419. duk_hobject *set);
  6420. /* Object built-in methods */
  6421. DUK_INTERNAL_DECL duk_ret_t duk_hobject_object_get_own_property_descriptor(duk_context *ctx);
  6422. DUK_INTERNAL_DECL void duk_hobject_object_seal_freeze_helper(duk_hthread *thr, duk_hobject *obj, duk_bool_t is_freeze);
  6423. DUK_INTERNAL_DECL duk_bool_t duk_hobject_object_is_sealed_frozen_helper(duk_hthread *thr, duk_hobject *obj, duk_bool_t is_frozen);
  6424. DUK_INTERNAL_DECL duk_bool_t duk_hobject_object_ownprop_helper(duk_context *ctx, duk_small_uint_t required_desc_flags);
  6425. /* internal properties */
  6426. DUK_INTERNAL_DECL duk_bool_t duk_hobject_get_internal_value(duk_heap *heap, duk_hobject *obj, duk_tval *tv);
  6427. DUK_INTERNAL_DECL duk_hstring *duk_hobject_get_internal_value_string(duk_heap *heap, duk_hobject *obj);
  6428. DUK_INTERNAL_DECL duk_hbuffer *duk_hobject_get_internal_value_buffer(duk_heap *heap, duk_hobject *obj);
  6429. /* hobject management functions */
  6430. DUK_INTERNAL_DECL void duk_hobject_compact_props(duk_hthread *thr, duk_hobject *obj);
  6431. /* ES6 proxy */
  6432. #if defined(DUK_USE_ES6_PROXY)
  6433. DUK_INTERNAL_DECL duk_bool_t duk_hobject_proxy_check(duk_hthread *thr, duk_hobject *obj, duk_hobject **out_target, duk_hobject **out_handler);
  6434. #endif
  6435. /* enumeration */
  6436. DUK_INTERNAL_DECL void duk_hobject_enumerator_create(duk_context *ctx, duk_small_uint_t enum_flags);
  6437. DUK_INTERNAL_DECL duk_ret_t duk_hobject_get_enumerated_keys(duk_context *ctx, duk_small_uint_t enum_flags);
  6438. DUK_INTERNAL_DECL duk_bool_t duk_hobject_enumerator_next(duk_context *ctx, duk_bool_t get_value);
  6439. /* macros */
  6440. DUK_INTERNAL_DECL void duk_hobject_set_prototype(duk_hthread *thr, duk_hobject *h, duk_hobject *p);
  6441. /* finalization */
  6442. DUK_INTERNAL_DECL void duk_hobject_run_finalizer(duk_hthread *thr, duk_hobject *obj);
  6443. /* pc2line */
  6444. #if defined(DUK_USE_PC2LINE)
  6445. DUK_INTERNAL_DECL void duk_hobject_pc2line_pack(duk_hthread *thr, duk_compiler_instr *instrs, duk_uint_fast32_t length);
  6446. DUK_INTERNAL_DECL duk_uint_fast32_t duk_hobject_pc2line_query(duk_context *ctx, duk_idx_t idx_func, duk_uint_fast32_t pc);
  6447. #endif
  6448. /* misc */
  6449. DUK_INTERNAL_DECL duk_bool_t duk_hobject_prototype_chain_contains(duk_hthread *thr, duk_hobject *h, duk_hobject *p, duk_bool_t ignore_loop);
  6450. #endif /* DUK_HOBJECT_H_INCLUDED */
  6451. #line 1 "duk_hcompiledfunction.h"
  6452. /*
  6453. * Heap compiled function (Ecmascript function) representation.
  6454. *
  6455. * There is a single data buffer containing the Ecmascript function's
  6456. * bytecode, constants, and inner functions.
  6457. */
  6458. #ifndef DUK_HCOMPILEDFUNCTION_H_INCLUDED
  6459. #define DUK_HCOMPILEDFUNCTION_H_INCLUDED
  6460. /*
  6461. * Field accessor macros
  6462. */
  6463. /* XXX: casts could be improved, especially for GET/SET DATA */
  6464. #if defined(DUK_USE_HEAPPTR16)
  6465. #define DUK_HCOMPILEDFUNCTION_GET_DATA(heap,h) \
  6466. ((duk_hbuffer_fixed *) DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (h)->data16))
  6467. #define DUK_HCOMPILEDFUNCTION_SET_DATA(heap,h,v) do { \
  6468. (h)->data16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) (v)); \
  6469. } while (0)
  6470. #define DUK_HCOMPILEDFUNCTION_GET_FUNCS(heap,h) \
  6471. ((duk_hobject **) (DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (h)->funcs16)))
  6472. #define DUK_HCOMPILEDFUNCTION_SET_FUNCS(heap,h,v) do { \
  6473. (h)->funcs16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) (v)); \
  6474. } while (0)
  6475. #define DUK_HCOMPILEDFUNCTION_GET_BYTECODE(heap,h) \
  6476. ((duk_instr_t *) (DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (h)->bytecode16)))
  6477. #define DUK_HCOMPILEDFUNCTION_SET_BYTECODE(heap,h,v) do { \
  6478. (h)->bytecode16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) (v)); \
  6479. } while (0)
  6480. #else
  6481. #define DUK_HCOMPILEDFUNCTION_GET_DATA(heap,h) \
  6482. ((duk_hbuffer_fixed *) (h)->data)
  6483. #define DUK_HCOMPILEDFUNCTION_SET_DATA(heap,h,v) do { \
  6484. (h)->data = (duk_hbuffer *) (v); \
  6485. } while (0)
  6486. #define DUK_HCOMPILEDFUNCTION_GET_FUNCS(heap,h) \
  6487. ((h)->funcs)
  6488. #define DUK_HCOMPILEDFUNCTION_SET_FUNCS(heap,h,v) do { \
  6489. (h)->funcs = (v); \
  6490. } while (0)
  6491. #define DUK_HCOMPILEDFUNCTION_GET_BYTECODE(heap,h) \
  6492. ((h)->bytecode)
  6493. #define DUK_HCOMPILEDFUNCTION_SET_BYTECODE(heap,h,v) do { \
  6494. (h)->bytecode = (v); \
  6495. } while (0)
  6496. #endif
  6497. /*
  6498. * Accessor macros for function specific data areas
  6499. */
  6500. /* Note: assumes 'data' is always a fixed buffer */
  6501. #define DUK_HCOMPILEDFUNCTION_GET_BUFFER_BASE(heap,h) \
  6502. DUK_HBUFFER_FIXED_GET_DATA_PTR((heap), DUK_HCOMPILEDFUNCTION_GET_DATA((heap), (h)))
  6503. #define DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(heap,h) \
  6504. ((duk_tval *) DUK_HCOMPILEDFUNCTION_GET_BUFFER_BASE((heap), (h)))
  6505. #define DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(heap,h) \
  6506. DUK_HCOMPILEDFUNCTION_GET_FUNCS((heap), (h))
  6507. #define DUK_HCOMPILEDFUNCTION_GET_CODE_BASE(heap,h) \
  6508. DUK_HCOMPILEDFUNCTION_GET_BYTECODE((heap), (h))
  6509. #define DUK_HCOMPILEDFUNCTION_GET_CONSTS_END(heap,h) \
  6510. ((duk_tval *) DUK_HCOMPILEDFUNCTION_GET_FUNCS((heap), (h)))
  6511. #define DUK_HCOMPILEDFUNCTION_GET_FUNCS_END(heap,h) \
  6512. ((duk_hobject **) DUK_HCOMPILEDFUNCTION_GET_BYTECODE((heap), (h)))
  6513. /* XXX: double evaluation of DUK_HCOMPILEDFUNCTION_GET_DATA() */
  6514. #define DUK_HCOMPILEDFUNCTION_GET_CODE_END(heap,h) \
  6515. ((duk_instr_t *) (DUK_HBUFFER_FIXED_GET_DATA_PTR((heap), DUK_HCOMPILEDFUNCTION_GET_DATA((heap), (h))) + \
  6516. DUK_HBUFFER_GET_SIZE((duk_hbuffer *) DUK_HCOMPILEDFUNCTION_GET_DATA((heap), h))))
  6517. #define DUK_HCOMPILEDFUNCTION_GET_CONSTS_SIZE(heap,h) \
  6518. ( \
  6519. (duk_size_t) \
  6520. ( \
  6521. ((const duk_uint8_t *) DUK_HCOMPILEDFUNCTION_GET_CONSTS_END((heap), (h))) - \
  6522. ((const duk_uint8_t *) DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE((heap), (h))) \
  6523. ) \
  6524. )
  6525. #define DUK_HCOMPILEDFUNCTION_GET_FUNCS_SIZE(heap,h) \
  6526. ( \
  6527. (duk_size_t) \
  6528. ( \
  6529. ((const duk_uint8_t *) DUK_HCOMPILEDFUNCTION_GET_FUNCS_END((heap), (h))) - \
  6530. ((const duk_uint8_t *) DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE((heap), (h))) \
  6531. ) \
  6532. )
  6533. #define DUK_HCOMPILEDFUNCTION_GET_CODE_SIZE(heap,h) \
  6534. ( \
  6535. (duk_size_t) \
  6536. ( \
  6537. ((const duk_uint8_t *) DUK_HCOMPILEDFUNCTION_GET_CODE_END((heap),(h))) - \
  6538. ((const duk_uint8_t *) DUK_HCOMPILEDFUNCTION_GET_CODE_BASE((heap),(h))) \
  6539. ) \
  6540. )
  6541. #define DUK_HCOMPILEDFUNCTION_GET_CONSTS_COUNT(heap,h) \
  6542. ((duk_size_t) (DUK_HCOMPILEDFUNCTION_GET_CONSTS_SIZE((heap), (h)) / sizeof(duk_tval)))
  6543. #define DUK_HCOMPILEDFUNCTION_GET_FUNCS_COUNT(heap,h) \
  6544. ((duk_size_t) (DUK_HCOMPILEDFUNCTION_GET_FUNCS_SIZE((heap), (h)) / sizeof(duk_hobject *)))
  6545. #define DUK_HCOMPILEDFUNCTION_GET_CODE_COUNT(heap,h) \
  6546. ((duk_size_t) (DUK_HCOMPILEDFUNCTION_GET_CODE_SIZE((heap), (h)) / sizeof(duk_instr_t)))
  6547. /*
  6548. * Main struct
  6549. */
  6550. struct duk_hcompiledfunction {
  6551. /* shared object part */
  6552. duk_hobject obj;
  6553. /*
  6554. * Pointers to function data area for faster access. Function
  6555. * data is a buffer shared between all closures of the same
  6556. * "template" function. The data buffer is always fixed (non-
  6557. * dynamic, hence stable), with a layout as follows:
  6558. *
  6559. * constants (duk_tval)
  6560. * inner functions (duk_hobject *)
  6561. * bytecode (duk_instr_t)
  6562. *
  6563. * Note: bytecode end address can be computed from 'data' buffer
  6564. * size. It is not strictly necessary functionally, assuming
  6565. * bytecode never jumps outside its allocated area. However,
  6566. * it's a safety/robustness feature for avoiding the chance of
  6567. * executing random data as bytecode due to a compiler error.
  6568. *
  6569. * Note: values in the data buffer must be incref'd (they will
  6570. * be decref'd on release) for every compiledfunction referring
  6571. * to the 'data' element.
  6572. */
  6573. /* Data area, fixed allocation, stable data ptrs. */
  6574. #if defined(DUK_USE_HEAPPTR16)
  6575. duk_uint16_t data16;
  6576. #else
  6577. duk_hbuffer *data;
  6578. #endif
  6579. /* No need for constants pointer (= same as data).
  6580. *
  6581. * When using 16-bit packing alignment to 4 is nice. 'funcs' will be
  6582. * 4-byte aligned because 'constants' are duk_tvals. For now the
  6583. * inner function pointers are not compressed, so that 'bytecode' will
  6584. * also be 4-byte aligned.
  6585. */
  6586. #if defined(DUK_USE_HEAPPTR16)
  6587. duk_uint16_t funcs16;
  6588. duk_uint16_t bytecode16;
  6589. #else
  6590. duk_hobject **funcs;
  6591. duk_instr_t *bytecode;
  6592. #endif
  6593. /*
  6594. * 'nregs' registers are allocated on function entry, at most 'nargs'
  6595. * are initialized to arguments, and the rest to undefined. Arguments
  6596. * above 'nregs' are not mapped to registers. All registers in the
  6597. * active stack range must be initialized because they are GC reachable.
  6598. * 'nargs' is needed so that if the function is given more than 'nargs'
  6599. * arguments, the additional arguments do not 'clobber' registers
  6600. * beyond 'nregs' which must be consistently initialized to undefined.
  6601. *
  6602. * Usually there is no need to know which registers are mapped to
  6603. * local variables. Registers may be allocated to variable in any
  6604. * way (even including gaps). However, a register-variable mapping
  6605. * must be the same for the duration of the function execution and
  6606. * the register cannot be used for anything else.
  6607. *
  6608. * When looking up variables by name, the '_Varmap' map is used.
  6609. * When an activation closes, registers mapped to arguments are
  6610. * copied into the environment record based on the same map. The
  6611. * reverse map (from register to variable) is not currently needed
  6612. * at run time, except for debugging, so it is not maintained.
  6613. */
  6614. duk_uint16_t nregs; /* regs to allocate */
  6615. duk_uint16_t nargs; /* number of arguments allocated to regs */
  6616. /*
  6617. * Additional control information is placed into the object itself
  6618. * as internal properties to avoid unnecessary fields for the
  6619. * majority of functions. The compiler tries to omit internal
  6620. * control fields when possible.
  6621. *
  6622. * Function templates:
  6623. *
  6624. * {
  6625. * name: "func", // declaration, named function expressions
  6626. * fileName: <debug info for creating nice errors>
  6627. * _Varmap: { "arg1": 0, "arg2": 1, "varname": 2 },
  6628. * _Formals: [ "arg1", "arg2" ],
  6629. * _Source: "function func(arg1, arg2) { ... }",
  6630. * _Pc2line: <debug info for pc-to-line mapping>,
  6631. * }
  6632. *
  6633. * Function instances:
  6634. *
  6635. * {
  6636. * length: 2,
  6637. * prototype: { constructor: <func> },
  6638. * caller: <thrower>,
  6639. * arguments: <thrower>,
  6640. * name: "func", // declaration, named function expressions
  6641. * fileName: <debug info for creating nice errors>
  6642. * _Varmap: { "arg1": 0, "arg2": 1, "varname": 2 },
  6643. * _Formals: [ "arg1", "arg2" ],
  6644. * _Source: "function func(arg1, arg2) { ... }",
  6645. * _Pc2line: <debug info for pc-to-line mapping>,
  6646. * _Varenv: <variable environment of closure>,
  6647. * _Lexenv: <lexical environment of closure (if differs from _Varenv)>
  6648. * }
  6649. *
  6650. * More detailed description of these properties can be found
  6651. * in the documentation.
  6652. */
  6653. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  6654. /* Line number range for function. Needed during debugging to
  6655. * determine active breakpoints.
  6656. */
  6657. duk_uint32_t start_line;
  6658. duk_uint32_t end_line;
  6659. #endif
  6660. };
  6661. #endif /* DUK_HCOMPILEDFUNCTION_H_INCLUDED */
  6662. #line 1 "duk_hnativefunction.h"
  6663. /*
  6664. * Heap native function representation.
  6665. */
  6666. #ifndef DUK_HNATIVEFUNCTION_H_INCLUDED
  6667. #define DUK_HNATIVEFUNCTION_H_INCLUDED
  6668. #define DUK_HNATIVEFUNCTION_NARGS_VARARGS ((duk_int16_t) -1)
  6669. #define DUK_HNATIVEFUNCTION_NARGS_MAX ((duk_int16_t) 0x7fff)
  6670. struct duk_hnativefunction {
  6671. /* shared object part */
  6672. duk_hobject obj;
  6673. duk_c_function func;
  6674. duk_int16_t nargs;
  6675. duk_int16_t magic;
  6676. /* The 'magic' field allows an opaque 16-bit field to be accessed by the
  6677. * Duktape/C function. This allows, for instance, the same native function
  6678. * to be used for a set of very similar functions, with the 'magic' field
  6679. * providing the necessary non-argument flags / values to guide the behavior
  6680. * of the native function. The value is signed on purpose: it is easier to
  6681. * convert a signed value to unsigned (simply AND with 0xffff) than vice
  6682. * versa.
  6683. *
  6684. * Note: cannot place nargs/magic into the heaphdr flags, because
  6685. * duk_hobject takes almost all flags already (and needs the spare).
  6686. */
  6687. };
  6688. #endif /* DUK_HNATIVEFUNCTION_H_INCLUDED */
  6689. #line 1 "duk_hthread.h"
  6690. /*
  6691. * Heap thread object representation.
  6692. *
  6693. * duk_hthread is also the 'context' (duk_context) for exposed APIs
  6694. * which mostly operate on the topmost frame of the value stack.
  6695. */
  6696. #ifndef DUK_HTHREAD_H_INCLUDED
  6697. #define DUK_HTHREAD_H_INCLUDED
  6698. /*
  6699. * Stack constants
  6700. */
  6701. #define DUK_VALSTACK_GROW_STEP 128 /* roughly 1 kiB */
  6702. #define DUK_VALSTACK_SHRINK_THRESHOLD 256 /* roughly 2 kiB */
  6703. #define DUK_VALSTACK_SHRINK_SPARE 64 /* roughly 0.5 kiB */
  6704. #define DUK_VALSTACK_INITIAL_SIZE 128 /* roughly 1.0 kiB -> but rounds up to DUK_VALSTACK_GROW_STEP in practice */
  6705. #define DUK_VALSTACK_INTERNAL_EXTRA 64 /* internal extra elements assumed on function entry,
  6706. * always added to user-defined 'extra' for e.g. the
  6707. * duk_check_stack() call.
  6708. */
  6709. #define DUK_VALSTACK_API_ENTRY_MINIMUM DUK_API_ENTRY_STACK
  6710. /* number of elements guaranteed to be user accessible
  6711. * (in addition to call arguments) on Duktape/C function entry.
  6712. */
  6713. /* Note: DUK_VALSTACK_INITIAL_SIZE must be >= DUK_VALSTACK_API_ENTRY_MINIMUM
  6714. * + DUK_VALSTACK_INTERNAL_EXTRA so that the initial stack conforms to spare
  6715. * requirements.
  6716. */
  6717. #define DUK_VALSTACK_DEFAULT_MAX 1000000L
  6718. #define DUK_CALLSTACK_GROW_STEP 8 /* roughly 256 bytes */
  6719. #define DUK_CALLSTACK_SHRINK_THRESHOLD 16 /* roughly 512 bytes */
  6720. #define DUK_CALLSTACK_SHRINK_SPARE 8 /* roughly 256 bytes */
  6721. #define DUK_CALLSTACK_INITIAL_SIZE 8
  6722. #define DUK_CALLSTACK_DEFAULT_MAX 10000L
  6723. #define DUK_CATCHSTACK_GROW_STEP 4 /* roughly 64 bytes */
  6724. #define DUK_CATCHSTACK_SHRINK_THRESHOLD 8 /* roughly 128 bytes */
  6725. #define DUK_CATCHSTACK_SHRINK_SPARE 4 /* roughly 64 bytes */
  6726. #define DUK_CATCHSTACK_INITIAL_SIZE 4
  6727. #define DUK_CATCHSTACK_DEFAULT_MAX 10000L
  6728. /*
  6729. * Activation defines
  6730. */
  6731. #define DUK_ACT_FLAG_STRICT (1 << 0) /* function executes in strict mode */
  6732. #define DUK_ACT_FLAG_TAILCALLED (1 << 1) /* activation has tailcalled one or more times */
  6733. #define DUK_ACT_FLAG_CONSTRUCT (1 << 2) /* function executes as a constructor (called via "new") */
  6734. #define DUK_ACT_FLAG_PREVENT_YIELD (1 << 3) /* activation prevents yield (native call or "new") */
  6735. #define DUK_ACT_FLAG_DIRECT_EVAL (1 << 4) /* activation is a direct eval call */
  6736. #define DUK_ACT_FLAG_BREAKPOINT_ACTIVE (1 << 5) /* activation has active breakpoint(s) */
  6737. #define DUK_ACT_GET_FUNC(act) ((act)->func)
  6738. /*
  6739. * Flags for __FILE__ / __LINE__ registered into tracedata
  6740. */
  6741. #define DUK_TB_FLAG_NOBLAME_FILELINE (1 << 0) /* don't report __FILE__ / __LINE__ as fileName/lineNumber */
  6742. /*
  6743. * Catcher defines
  6744. */
  6745. /* flags field: LLLLLLFT, L = label (24 bits), F = flags (4 bits), T = type (4 bits) */
  6746. #define DUK_CAT_TYPE_MASK 0x0000000fUL
  6747. #define DUK_CAT_TYPE_BITS 4
  6748. #define DUK_CAT_LABEL_MASK 0xffffff00UL
  6749. #define DUK_CAT_LABEL_BITS 24
  6750. #define DUK_CAT_LABEL_SHIFT 8
  6751. #define DUK_CAT_FLAG_CATCH_ENABLED (1 << 4) /* catch part will catch */
  6752. #define DUK_CAT_FLAG_FINALLY_ENABLED (1 << 5) /* finally part will catch */
  6753. #define DUK_CAT_FLAG_CATCH_BINDING_ENABLED (1 << 6) /* request to create catch binding */
  6754. #define DUK_CAT_FLAG_LEXENV_ACTIVE (1 << 7) /* catch or with binding is currently active */
  6755. #define DUK_CAT_TYPE_UNKNOWN 0
  6756. #define DUK_CAT_TYPE_TCF 1
  6757. #define DUK_CAT_TYPE_LABEL 2
  6758. #define DUK_CAT_GET_TYPE(c) ((c)->flags & DUK_CAT_TYPE_MASK)
  6759. #define DUK_CAT_GET_LABEL(c) (((c)->flags & DUK_CAT_LABEL_MASK) >> DUK_CAT_LABEL_SHIFT)
  6760. #define DUK_CAT_HAS_CATCH_ENABLED(c) ((c)->flags & DUK_CAT_FLAG_CATCH_ENABLED)
  6761. #define DUK_CAT_HAS_FINALLY_ENABLED(c) ((c)->flags & DUK_CAT_FLAG_FINALLY_ENABLED)
  6762. #define DUK_CAT_HAS_CATCH_BINDING_ENABLED(c) ((c)->flags & DUK_CAT_FLAG_CATCH_BINDING_ENABLED)
  6763. #define DUK_CAT_HAS_LEXENV_ACTIVE(c) ((c)->flags & DUK_CAT_FLAG_LEXENV_ACTIVE)
  6764. #define DUK_CAT_SET_CATCH_ENABLED(c) do { \
  6765. (c)->flags |= DUK_CAT_FLAG_CATCH_ENABLED; \
  6766. } while (0)
  6767. #define DUK_CAT_SET_FINALLY_ENABLED(c) do { \
  6768. (c)->flags |= DUK_CAT_FLAG_FINALLY_ENABLED; \
  6769. } while (0)
  6770. #define DUK_CAT_SET_CATCH_BINDING_ENABLED(c) do { \
  6771. (c)->flags |= DUK_CAT_FLAG_CATCH_BINDING_ENABLED; \
  6772. } while (0)
  6773. #define DUK_CAT_SET_LEXENV_ACTIVE(c) do { \
  6774. (c)->flags |= DUK_CAT_FLAG_LEXENV_ACTIVE; \
  6775. } while (0)
  6776. #define DUK_CAT_CLEAR_CATCH_ENABLED(c) do { \
  6777. (c)->flags &= ~DUK_CAT_FLAG_CATCH_ENABLED; \
  6778. } while (0)
  6779. #define DUK_CAT_CLEAR_FINALLY_ENABLED(c) do { \
  6780. (c)->flags &= ~DUK_CAT_FLAG_FINALLY_ENABLED; \
  6781. } while (0)
  6782. #define DUK_CAT_CLEAR_CATCH_BINDING_ENABLED(c) do { \
  6783. (c)->flags &= ~DUK_CAT_FLAG_CATCH_BINDING_ENABLED; \
  6784. } while (0)
  6785. #define DUK_CAT_CLEAR_LEXENV_ACTIVE(c) do { \
  6786. (c)->flags &= ~DUK_CAT_FLAG_LEXENV_ACTIVE; \
  6787. } while (0)
  6788. /*
  6789. * Thread defines
  6790. */
  6791. #if defined(DUK_USE_HEAPPTR16)
  6792. #define DUK_HTHREAD_GET_STRING(thr,idx) \
  6793. ((duk_hstring *) DUK_USE_HEAPPTR_DEC16((thr)->heap->heap_udata, (thr)->strs16[(idx)]))
  6794. #else
  6795. #define DUK_HTHREAD_GET_STRING(thr,idx) \
  6796. ((thr)->strs[(idx)])
  6797. #endif
  6798. #define DUK_HTHREAD_GET_CURRENT_ACTIVATION(thr) (&(thr)->callstack[(thr)->callstack_top - 1])
  6799. /* values for the state field */
  6800. #define DUK_HTHREAD_STATE_INACTIVE 1 /* thread not currently running */
  6801. #define DUK_HTHREAD_STATE_RUNNING 2 /* thread currently running (only one at a time) */
  6802. #define DUK_HTHREAD_STATE_RESUMED 3 /* thread resumed another thread (active but not running) */
  6803. #define DUK_HTHREAD_STATE_YIELDED 4 /* thread has yielded */
  6804. #define DUK_HTHREAD_STATE_TERMINATED 5 /* thread has terminated */
  6805. /*
  6806. * Struct defines
  6807. */
  6808. /* XXX: for a memory-code tradeoff, remove 'func' and make it's access either a function
  6809. * or a macro. This would make the activation 32 bytes long on 32-bit platforms again.
  6810. */
  6811. /* Note: it's nice if size is 2^N (at least for 32-bit platforms). */
  6812. struct duk_activation {
  6813. duk_tval tv_func; /* borrowed: full duk_tval for function being executed; for lightfuncs */
  6814. duk_hobject *func; /* borrowed: function being executed; for bound function calls, this is the final, real function, NULL for lightfuncs */
  6815. duk_hobject *var_env; /* current variable environment (may be NULL if delayed) */
  6816. duk_hobject *lex_env; /* current lexical environment (may be NULL if delayed) */
  6817. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  6818. /* Previous value of 'func' caller, restored when unwound. Only in use
  6819. * when 'func' is non-strict.
  6820. */
  6821. duk_hobject *prev_caller;
  6822. #endif
  6823. duk_small_uint_t flags;
  6824. duk_uint32_t pc; /* next instruction to execute */
  6825. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  6826. duk_uint32_t prev_line; /* needed for stepping */
  6827. #endif
  6828. /* idx_bottom and idx_retval are only used for book-keeping of
  6829. * Ecmascript-initiated calls, to allow returning to an Ecmascript
  6830. * function properly. They are duk_size_t to match the convention
  6831. * that value stack sizes are duk_size_t and local frame indices
  6832. * are duk_idx_t.
  6833. */
  6834. /* Bottom of valstack for this activation, used to reset
  6835. * valstack_bottom on return; index is absolute. Note:
  6836. * idx_top not needed because top is set to 'nregs' always
  6837. * when returning to an Ecmascript activation.
  6838. */
  6839. duk_size_t idx_bottom;
  6840. /* Return value when returning to this activation (points to caller
  6841. * reg, not callee reg); index is absolute (only set if activation is
  6842. * not topmost).
  6843. *
  6844. * Note: idx_bottom is always set, while idx_retval is only applicable
  6845. * for activations below the topmost one. Currently idx_retval for
  6846. * the topmost activation is considered garbage (and it not initialized
  6847. * on entry or cleared on return; may contain previous or garbage
  6848. * values).
  6849. */
  6850. duk_size_t idx_retval;
  6851. /* Current 'this' binding is the value just below idx_bottom.
  6852. * Previously, 'this' binding was handled with an index to the
  6853. * (calling) valstack. This works for everything except tail
  6854. * calls, which must not "cumulate" valstack temps.
  6855. */
  6856. };
  6857. /* Note: it's nice if size is 2^N (not 4x4 = 16 bytes on 32 bit) */
  6858. struct duk_catcher {
  6859. duk_hstring *h_varname; /* borrowed reference to catch variable name (or NULL if none) */
  6860. /* (reference is valid as long activation exists) */
  6861. duk_size_t callstack_index; /* callstack index of related activation */
  6862. duk_size_t idx_base; /* idx_base and idx_base+1 get completion value and type */
  6863. duk_uint32_t pc_base; /* resume execution from pc_base or pc_base+1 */
  6864. duk_uint32_t flags; /* type and control flags, label number */
  6865. };
  6866. struct duk_hthread {
  6867. /* shared object part */
  6868. duk_hobject obj;
  6869. /* backpointers */
  6870. duk_heap *heap;
  6871. /* current strictness flag: affects API calls */
  6872. duk_uint8_t strict;
  6873. duk_uint8_t state;
  6874. duk_uint8_t unused1;
  6875. duk_uint8_t unused2;
  6876. /* sanity limits */
  6877. duk_size_t valstack_max;
  6878. duk_size_t callstack_max;
  6879. duk_size_t catchstack_max;
  6880. /* XXX: valstack, callstack, and catchstack are currently assumed
  6881. * to have non-NULL pointers. Relaxing this would not lead to big
  6882. * benefits (except perhaps for terminated threads).
  6883. */
  6884. /* value stack: these are expressed as pointers for faster stack manipulation */
  6885. duk_tval *valstack; /* start of valstack allocation */
  6886. duk_tval *valstack_end; /* end of valstack allocation (exclusive) */
  6887. duk_tval *valstack_bottom; /* bottom of current frame */
  6888. duk_tval *valstack_top; /* top of current frame (exclusive) */
  6889. /* call stack */
  6890. duk_activation *callstack;
  6891. duk_size_t callstack_size; /* allocation size */
  6892. duk_size_t callstack_top; /* next to use, highest used is top - 1 */
  6893. duk_size_t callstack_preventcount; /* number of activation records in callstack preventing a yield */
  6894. /* catch stack */
  6895. duk_catcher *catchstack;
  6896. duk_size_t catchstack_size; /* allocation size */
  6897. duk_size_t catchstack_top; /* next to use, highest used is top - 1 */
  6898. /* yield/resume book-keeping */
  6899. duk_hthread *resumer; /* who resumed us (if any) */
  6900. /* current compiler state (if any), used for augmenting SyntaxErrors */
  6901. duk_compiler_ctx *compile_ctx;
  6902. #ifdef DUK_USE_INTERRUPT_COUNTER
  6903. /* Interrupt counter for triggering a slow path check for execution
  6904. * timeout, debugger interaction such as breakpoints, etc. This is
  6905. * actually a value copied from the heap structure into the current
  6906. * thread to be more convenient for the bytecode executor inner loop.
  6907. * The final value is copied back to the heap structure on a thread
  6908. * switch by DUK_HEAP_SWITCH_THREAD().
  6909. */
  6910. duk_int_t interrupt_counter;
  6911. #endif
  6912. /* Builtin-objects; may or may not be shared with other threads,
  6913. * threads existing in different "compartments" will have different
  6914. * built-ins. Must be stored on a per-thread basis because there
  6915. * is no intermediate structure for a thread group / compartment.
  6916. * This takes quite a lot of space, currently 43x4 = 172 bytes on
  6917. * 32-bit platforms.
  6918. */
  6919. duk_hobject *builtins[DUK_NUM_BUILTINS];
  6920. /* convenience copies from heap/vm for faster access */
  6921. #if defined(DUK_USE_HEAPPTR16)
  6922. duk_uint16_t *strs16;
  6923. #else
  6924. duk_hstring **strs;
  6925. #endif
  6926. };
  6927. /*
  6928. * Prototypes
  6929. */
  6930. DUK_INTERNAL_DECL void duk_hthread_copy_builtin_objects(duk_hthread *thr_from, duk_hthread *thr_to);
  6931. DUK_INTERNAL_DECL void duk_hthread_create_builtin_objects(duk_hthread *thr);
  6932. DUK_INTERNAL_DECL duk_bool_t duk_hthread_init_stacks(duk_heap *heap, duk_hthread *thr);
  6933. DUK_INTERNAL_DECL void duk_hthread_terminate(duk_hthread *thr);
  6934. DUK_INTERNAL_DECL void duk_hthread_callstack_grow(duk_hthread *thr);
  6935. DUK_INTERNAL_DECL void duk_hthread_callstack_shrink_check(duk_hthread *thr);
  6936. DUK_INTERNAL_DECL void duk_hthread_callstack_unwind(duk_hthread *thr, duk_size_t new_top);
  6937. DUK_INTERNAL_DECL void duk_hthread_catchstack_grow(duk_hthread *thr);
  6938. DUK_INTERNAL_DECL void duk_hthread_catchstack_shrink_check(duk_hthread *thr);
  6939. DUK_INTERNAL_DECL void duk_hthread_catchstack_unwind(duk_hthread *thr, duk_size_t new_top);
  6940. DUK_INTERNAL_DECL duk_activation *duk_hthread_get_current_activation(duk_hthread *thr);
  6941. DUK_INTERNAL_DECL void *duk_hthread_get_valstack_ptr(duk_heap *heap, void *ud); /* indirect allocs */
  6942. DUK_INTERNAL_DECL void *duk_hthread_get_callstack_ptr(duk_heap *heap, void *ud); /* indirect allocs */
  6943. DUK_INTERNAL_DECL void *duk_hthread_get_catchstack_ptr(duk_heap *heap, void *ud); /* indirect allocs */
  6944. #endif /* DUK_HTHREAD_H_INCLUDED */
  6945. #line 1 "duk_hbuffer.h"
  6946. /*
  6947. * Heap buffer representation.
  6948. *
  6949. * Heap allocated user data buffer which is either:
  6950. *
  6951. * 1. A fixed size buffer (data follows header statically)
  6952. * 2. A dynamic size buffer (data pointer follows header)
  6953. *
  6954. * The data pointer for a variable size buffer of zero size may be NULL.
  6955. */
  6956. #ifndef DUK_HBUFFER_H_INCLUDED
  6957. #define DUK_HBUFFER_H_INCLUDED
  6958. /*
  6959. * Flags
  6960. */
  6961. #define DUK_HBUFFER_FLAG_DYNAMIC DUK_HEAPHDR_USER_FLAG(0) /* buffer is resizable */
  6962. #define DUK_HBUFFER_HAS_DYNAMIC(x) DUK_HEAPHDR_CHECK_FLAG_BITS(&(x)->hdr, DUK_HBUFFER_FLAG_DYNAMIC)
  6963. #define DUK_HBUFFER_SET_DYNAMIC(x) DUK_HEAPHDR_SET_FLAG_BITS(&(x)->hdr, DUK_HBUFFER_FLAG_DYNAMIC)
  6964. #define DUK_HBUFFER_CLEAR_DYNAMIC(x) DUK_HEAPHDR_CLEAR_FLAG_BITS(&(x)->hdr, DUK_HBUFFER_FLAG_DYNAMIC)
  6965. #define DUK_HBUFFER_FIXED_GET_DATA_PTR(heap,x) ((duk_uint8_t *) (((duk_hbuffer_fixed *) (x)) + 1))
  6966. /*
  6967. * Misc defines
  6968. */
  6969. /* Impose a maximum buffer length for now. Restricted artificially to
  6970. * ensure resize computations or adding a heap header length won't
  6971. * overflow size_t. The limit should be synchronized with
  6972. * DUK_HSTRING_MAX_BYTELEN.
  6973. */
  6974. #if defined(DUK_USE_BUFLEN16)
  6975. #define DUK_HBUFFER_MAX_BYTELEN (0x0000ffffUL)
  6976. #else
  6977. #define DUK_HBUFFER_MAX_BYTELEN (0x7fffffffUL)
  6978. #endif
  6979. /*
  6980. * Field access
  6981. */
  6982. /* Get/set the current user visible size, without accounting for a dynamic
  6983. * buffer's "spare" (= usable size).
  6984. */
  6985. #if defined(DUK_USE_BUFLEN16)
  6986. /* size stored in duk_heaphdr unused flag bits */
  6987. #define DUK_HBUFFER_GET_SIZE(x) ((x)->hdr.h_flags >> 16)
  6988. #define DUK_HBUFFER_SET_SIZE(x,v) do { \
  6989. (x)->hdr.h_flags = ((x)->hdr.h_flags & 0x0000ffffUL) | ((v) << 16); \
  6990. } while (0)
  6991. #define DUK_HBUFFER_ADD_SIZE(x,dv) do { \
  6992. (x)->hdr.h_flags += ((dv) << 16); \
  6993. } while (0)
  6994. #define DUK_HBUFFER_SUB_SIZE(x,dv) do { \
  6995. (x)->hdr.h_flags -= ((dv) << 16); \
  6996. } while (0)
  6997. #else
  6998. #define DUK_HBUFFER_GET_SIZE(x) (((duk_hbuffer *) (x))->size)
  6999. #define DUK_HBUFFER_SET_SIZE(x,v) do { \
  7000. ((duk_hbuffer *) (x))->size = (v); \
  7001. } while (0)
  7002. #define DUK_HBUFFER_ADD_SIZE(x,dv) do { \
  7003. (x)->size += (dv); \
  7004. } while (0)
  7005. #define DUK_HBUFFER_SUB_SIZE(x,dv) do { \
  7006. (x)->size -= (dv); \
  7007. } while (0)
  7008. #endif
  7009. #define DUK_HBUFFER_FIXED_GET_SIZE(x) DUK_HBUFFER_GET_SIZE((duk_hbuffer *) (x))
  7010. #define DUK_HBUFFER_FIXED_SET_SIZE(x,v) DUK_HBUFFER_SET_SIZE((duk_hbuffer *) (x))
  7011. #define DUK_HBUFFER_DYNAMIC_GET_SIZE(x) DUK_HBUFFER_GET_SIZE((duk_hbuffer *) (x))
  7012. #define DUK_HBUFFER_DYNAMIC_SET_SIZE(x,v) DUK_HBUFFER_SET_SIZE((duk_hbuffer *) (x), (v))
  7013. #define DUK_HBUFFER_DYNAMIC_ADD_SIZE(x,dv) DUK_HBUFFER_ADD_SIZE((duk_hbuffer *) (x), (dv))
  7014. #define DUK_HBUFFER_DYNAMIC_SUB_SIZE(x,dv) DUK_HBUFFER_SUB_SIZE((duk_hbuffer *) (x), (dv))
  7015. #if defined(DUK_USE_BUFLEN16) && defined(DUK_USE_HEAPPTR16)
  7016. /* alloc_size16 stored in duk_heaphdr h_extra16, available with pointer compression. */
  7017. #define DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(x) ((duk_size_t) ((x)->hdr.h_extra16))
  7018. #define DUK_HBUFFER_DYNAMIC_SET_ALLOC_SIZE(x,v) do { \
  7019. (x)->hdr.h_extra16 = (duk_uint16_t) (v); \
  7020. } while (0)
  7021. #elif defined(DUK_USE_BUFLEN16)
  7022. /* alloc_size16 stored in an explicit 16-bit fields. */
  7023. #define DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(x) ((duk_size_t) ((x)->alloc_size16))
  7024. #define DUK_HBUFFER_DYNAMIC_SET_ALLOC_SIZE(x,v) do { \
  7025. (x)->alloc_size16 = (duk_uint16_t) (v); \
  7026. } while (0)
  7027. #else
  7028. /* normal case */
  7029. #define DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(x) ((x)->alloc_size)
  7030. #define DUK_HBUFFER_DYNAMIC_SET_ALLOC_SIZE(x,v) do { \
  7031. (x)->alloc_size = (v); \
  7032. } while (0)
  7033. #endif
  7034. #define DUK_HBUFFER_DYNAMIC_GET_SPARE_SIZE(x) \
  7035. (duk_size_t) (DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE((x)) - DUK_HBUFFER_DYNAMIC_GET_SIZE((x)))
  7036. #if defined(DUK_USE_HEAPPTR16)
  7037. #define DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(heap,x) \
  7038. ((void *) DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (x)->curr_alloc16))
  7039. #define DUK_HBUFFER_DYNAMIC_SET_DATA_PTR(heap,x,v) do { \
  7040. (x)->curr_alloc16 = DUK_USE_HEAPPTR_ENC16((heap)->heap_udata, (void *) (v)); \
  7041. } while (0)
  7042. #define DUK_HBUFFER_DYNAMIC_SET_DATA_PTR_NULL(heap,x) do { \
  7043. (x)->curr_alloc16 = 0; /* assume 0 <=> NULL */ \
  7044. } while (0)
  7045. #else
  7046. #define DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(heap,x) ((x)->curr_alloc)
  7047. #define DUK_HBUFFER_DYNAMIC_SET_DATA_PTR(heap,x,v) do { \
  7048. (x)->curr_alloc = (void *) (v); \
  7049. } while (0)
  7050. #define DUK_HBUFFER_DYNAMIC_SET_DATA_PTR_NULL(heap,x) do { \
  7051. (x)->curr_alloc = (void *) NULL; \
  7052. } while (0)
  7053. #endif
  7054. /* Gets the actual buffer contents which matches the current allocation size
  7055. * (may be NULL for zero size dynamic buffer).
  7056. */
  7057. #define DUK_HBUFFER_GET_DATA_PTR(heap,x) ( \
  7058. DUK_HBUFFER_HAS_DYNAMIC((x)) ? \
  7059. DUK_HBUFFER_DYNAMIC_GET_DATA_PTR((heap), (duk_hbuffer_dynamic *) (x)) : \
  7060. DUK_HBUFFER_FIXED_GET_DATA_PTR((heap), (duk_hbuffer_fixed *) (x)) \
  7061. )
  7062. /* Growth parameters for dynamic buffers. */
  7063. #define DUK_HBUFFER_SPARE_ADD 16
  7064. #define DUK_HBUFFER_SPARE_DIVISOR 16 /* 2^4 -> 1/16 = 6.25% spare */
  7065. /*
  7066. * Structs
  7067. */
  7068. struct duk_hbuffer {
  7069. duk_heaphdr hdr;
  7070. /* It's not strictly necessary to track the current size, but
  7071. * it is useful for writing robust native code.
  7072. */
  7073. /* Current size (not counting a dynamic buffer's "spare"). */
  7074. #if defined(DUK_USE_BUFLEN16)
  7075. /* Stored in duk_heaphdr unused flags. */
  7076. #else
  7077. duk_size_t size;
  7078. #endif
  7079. /*
  7080. * Data following the header depends on the DUK_HBUFFER_FLAG_DYNAMIC
  7081. * flag.
  7082. *
  7083. * If the flag is clear (the buffer is a fixed size one), the buffer
  7084. * data follows the header directly, consisting of 'size' bytes.
  7085. *
  7086. * If the flag is set, the actual buffer is allocated separately, and
  7087. * a few control fields follow the header. Specifically:
  7088. *
  7089. * - a "void *" pointing to the current allocation
  7090. * - a duk_size_t indicating the full allocated size (always >= 'size')
  7091. *
  7092. * Unlike strings, no terminator byte (NUL) is guaranteed after the
  7093. * data. This would be convenient, but would pad aligned user buffers
  7094. * unnecessarily upwards in size. For instance, if user code requested
  7095. * a 64-byte dynamic buffer, 65 bytes would actually be allocated which
  7096. * would then potentially round upwards to perhaps 68 or 72 bytes.
  7097. */
  7098. };
  7099. #if defined(DUK_USE_ALIGN_8) && defined(DUK_USE_PACK_MSVC_PRAGMA)
  7100. #pragma pack(push, 8)
  7101. #endif
  7102. struct duk_hbuffer_fixed {
  7103. /* A union is used here as a portable struct size / alignment trick:
  7104. * by adding a 32-bit or a 64-bit (unused) union member, the size of
  7105. * the struct is effectively forced to be a multiple of 4 or 8 bytes
  7106. * (respectively) without increasing the size of the struct unless
  7107. * necessary.
  7108. */
  7109. union {
  7110. struct {
  7111. duk_heaphdr hdr;
  7112. #if defined(DUK_USE_BUFLEN16)
  7113. /* Stored in duk_heaphdr unused flags. */
  7114. #else
  7115. duk_size_t size;
  7116. #endif
  7117. } s;
  7118. #if defined(DUK_USE_ALIGN_4)
  7119. duk_uint32_t dummy_for_align4;
  7120. #elif defined(DUK_USE_ALIGN_8)
  7121. duk_double_t dummy_for_align8;
  7122. #else
  7123. /* no extra padding */
  7124. #endif
  7125. } u;
  7126. /*
  7127. * Data follows the struct header. The struct size is padded by the
  7128. * compiler based on the struct members. This guarantees that the
  7129. * buffer data will be aligned-by-4 but not necessarily aligned-by-8.
  7130. *
  7131. * On platforms where alignment does not matter, the struct padding
  7132. * could be removed (if there is any). On platforms where alignment
  7133. * by 8 is required, the struct size must be forced to be a multiple
  7134. * of 8 by some means. Without it, some user code may break, and also
  7135. * Duktape itself breaks (e.g. the compiler stores duk_tvals in a
  7136. * dynamic buffer).
  7137. */
  7138. }
  7139. #if defined(DUK_USE_ALIGN_8) && defined(DUK_USE_PACK_GCC_ATTR)
  7140. __attribute__ ((aligned (8)))
  7141. #elif defined(DUK_USE_ALIGN_8) && defined(DUK_USE_PACK_CLANG_ATTR)
  7142. __attribute__ ((aligned (8)))
  7143. #endif
  7144. ;
  7145. #if defined(DUK_USE_ALIGN_8) && defined(DUK_USE_PACK_MSVC_PRAGMA)
  7146. #pragma pack(pop)
  7147. #endif
  7148. struct duk_hbuffer_dynamic {
  7149. duk_heaphdr hdr;
  7150. #if defined(DUK_USE_BUFLEN16)
  7151. /* Stored in duk_heaphdr unused flags. */
  7152. #else
  7153. duk_size_t size;
  7154. #endif
  7155. #if defined(DUK_USE_BUFLEN16) && defined(DUK_USE_HEAPPTR16)
  7156. /* Stored in duk_heaphdr h_extra16. */
  7157. #elif defined(DUK_USE_BUFLEN16)
  7158. duk_uint16_t alloc_size16;
  7159. #else
  7160. duk_size_t alloc_size;
  7161. #endif
  7162. #if defined(DUK_USE_HEAPPTR16)
  7163. duk_uint16_t curr_alloc16;
  7164. #else
  7165. void *curr_alloc; /* may be NULL if alloc_size == 0 */
  7166. #endif
  7167. /*
  7168. * Allocation size for 'curr_alloc' is alloc_size. There is no
  7169. * automatic NUL terminator for buffers (see above for rationale).
  7170. *
  7171. * 'curr_alloc' is explicitly allocated with heap allocation
  7172. * primitives and will thus always have alignment suitable for
  7173. * e.g. duk_tval and an IEEE double.
  7174. */
  7175. };
  7176. /*
  7177. * Prototypes
  7178. */
  7179. DUK_INTERNAL_DECL duk_hbuffer *duk_hbuffer_alloc(duk_heap *heap, duk_size_t size, duk_small_uint_t flags);
  7180. DUK_INTERNAL_DECL void *duk_hbuffer_get_dynalloc_ptr(duk_heap *heap, void *ud); /* indirect allocs */
  7181. /* dynamic buffer ops */
  7182. DUK_INTERNAL_DECL void duk_hbuffer_resize(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t new_size, duk_size_t new_alloc_size);
  7183. DUK_INTERNAL_DECL void duk_hbuffer_reset(duk_hthread *thr, duk_hbuffer_dynamic *buf);
  7184. #if 0 /*unused*/
  7185. DUK_INTERNAL_DECL void duk_hbuffer_compact(duk_hthread *thr, duk_hbuffer_dynamic *buf);
  7186. #endif
  7187. DUK_INTERNAL_DECL void duk_hbuffer_append_bytes(duk_hthread *thr, duk_hbuffer_dynamic *buf, const duk_uint8_t *data, duk_size_t length);
  7188. DUK_INTERNAL_DECL void duk_hbuffer_append_byte(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_uint8_t byte);
  7189. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_append_cstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, const char *str);
  7190. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_append_hstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_hstring *str);
  7191. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_append_xutf8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_ucodepoint_t codepoint);
  7192. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_append_cesu8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_ucodepoint_t codepoint);
  7193. #if 0
  7194. DUK_INTERNAL_DECL void duk_hbuffer_append_native_u32(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_uint32_t val);
  7195. #endif
  7196. DUK_INTERNAL_DECL void duk_hbuffer_insert_bytes(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, const duk_uint8_t *data, duk_size_t length);
  7197. #if 0 /*unused*/
  7198. DUK_INTERNAL_DECL void duk_hbuffer_insert_byte(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_uint8_t byte);
  7199. #endif
  7200. #if 0 /*unused*/
  7201. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_insert_cstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, const char *str);
  7202. #endif
  7203. #if 0 /*unused*/
  7204. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_insert_hstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_hstring *str);
  7205. #endif
  7206. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_insert_xutf8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_ucodepoint_t codepoint);
  7207. #if 0 /*unused*/
  7208. DUK_INTERNAL_DECL duk_size_t duk_hbuffer_insert_cesu8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_ucodepoint_t codepoint);
  7209. #endif
  7210. DUK_INTERNAL_DECL void duk_hbuffer_remove_slice(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_size_t length);
  7211. DUK_INTERNAL_DECL void duk_hbuffer_insert_slice(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t dst_offset, duk_size_t src_offset, duk_size_t length);
  7212. DUK_INTERNAL_DECL void duk_hbuffer_append_slice(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t src_offset, duk_size_t length);
  7213. #endif /* DUK_HBUFFER_H_INCLUDED */
  7214. #line 1 "duk_heap.h"
  7215. /*
  7216. * Heap structure.
  7217. *
  7218. * Heap contains allocated heap objects, interned strings, and built-in
  7219. * strings for one or more threads.
  7220. */
  7221. #ifndef DUK_HEAP_H_INCLUDED
  7222. #define DUK_HEAP_H_INCLUDED
  7223. /* alloc function typedefs in duktape.h */
  7224. /*
  7225. * Heap flags
  7226. */
  7227. #define DUK_HEAP_FLAG_MARKANDSWEEP_RUNNING (1 << 0) /* mark-and-sweep is currently running */
  7228. #define DUK_HEAP_FLAG_MARKANDSWEEP_RECLIMIT_REACHED (1 << 1) /* mark-and-sweep marking reached a recursion limit and must use multi-pass marking */
  7229. #define DUK_HEAP_FLAG_REFZERO_FREE_RUNNING (1 << 2) /* refcount code is processing refzero list */
  7230. #define DUK_HEAP_FLAG_ERRHANDLER_RUNNING (1 << 3) /* an error handler (user callback to augment/replace error) is running */
  7231. #define DUK_HEAP_FLAG_INTERRUPT_RUNNING (1 << 4) /* executor interrupt running (used to avoid nested interrupts) */
  7232. #define DUK__HEAP_HAS_FLAGS(heap,bits) ((heap)->flags & (bits))
  7233. #define DUK__HEAP_SET_FLAGS(heap,bits) do { \
  7234. (heap)->flags |= (bits); \
  7235. } while (0)
  7236. #define DUK__HEAP_CLEAR_FLAGS(heap,bits) do { \
  7237. (heap)->flags &= ~(bits); \
  7238. } while (0)
  7239. #define DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap) DUK__HEAP_HAS_FLAGS((heap), DUK_HEAP_FLAG_MARKANDSWEEP_RUNNING)
  7240. #define DUK_HEAP_HAS_MARKANDSWEEP_RECLIMIT_REACHED(heap) DUK__HEAP_HAS_FLAGS((heap), DUK_HEAP_FLAG_MARKANDSWEEP_RECLIMIT_REACHED)
  7241. #define DUK_HEAP_HAS_REFZERO_FREE_RUNNING(heap) DUK__HEAP_HAS_FLAGS((heap), DUK_HEAP_FLAG_REFZERO_FREE_RUNNING)
  7242. #define DUK_HEAP_HAS_ERRHANDLER_RUNNING(heap) DUK__HEAP_HAS_FLAGS((heap), DUK_HEAP_FLAG_ERRHANDLER_RUNNING)
  7243. #define DUK_HEAP_HAS_INTERRUPT_RUNNING(heap) DUK__HEAP_HAS_FLAGS((heap), DUK_HEAP_FLAG_INTERRUPT_RUNNING)
  7244. #define DUK_HEAP_SET_MARKANDSWEEP_RUNNING(heap) DUK__HEAP_SET_FLAGS((heap), DUK_HEAP_FLAG_MARKANDSWEEP_RUNNING)
  7245. #define DUK_HEAP_SET_MARKANDSWEEP_RECLIMIT_REACHED(heap) DUK__HEAP_SET_FLAGS((heap), DUK_HEAP_FLAG_MARKANDSWEEP_RECLIMIT_REACHED)
  7246. #define DUK_HEAP_SET_REFZERO_FREE_RUNNING(heap) DUK__HEAP_SET_FLAGS((heap), DUK_HEAP_FLAG_REFZERO_FREE_RUNNING)
  7247. #define DUK_HEAP_SET_ERRHANDLER_RUNNING(heap) DUK__HEAP_SET_FLAGS((heap), DUK_HEAP_FLAG_ERRHANDLER_RUNNING)
  7248. #define DUK_HEAP_SET_INTERRUPT_RUNNING(heap) DUK__HEAP_SET_FLAGS((heap), DUK_HEAP_FLAG_INTERRUPT_RUNNING)
  7249. #define DUK_HEAP_CLEAR_MARKANDSWEEP_RUNNING(heap) DUK__HEAP_CLEAR_FLAGS((heap), DUK_HEAP_FLAG_MARKANDSWEEP_RUNNING)
  7250. #define DUK_HEAP_CLEAR_MARKANDSWEEP_RECLIMIT_REACHED(heap) DUK__HEAP_CLEAR_FLAGS((heap), DUK_HEAP_FLAG_MARKANDSWEEP_RECLIMIT_REACHED)
  7251. #define DUK_HEAP_CLEAR_REFZERO_FREE_RUNNING(heap) DUK__HEAP_CLEAR_FLAGS((heap), DUK_HEAP_FLAG_REFZERO_FREE_RUNNING)
  7252. #define DUK_HEAP_CLEAR_ERRHANDLER_RUNNING(heap) DUK__HEAP_CLEAR_FLAGS((heap), DUK_HEAP_FLAG_ERRHANDLER_RUNNING)
  7253. #define DUK_HEAP_CLEAR_INTERRUPT_RUNNING(heap) DUK__HEAP_CLEAR_FLAGS((heap), DUK_HEAP_FLAG_INTERRUPT_RUNNING)
  7254. /*
  7255. * Longjmp types, also double as identifying continuation type for a rethrow (in 'finally')
  7256. */
  7257. #define DUK_LJ_TYPE_UNKNOWN 0 /* unused */
  7258. #define DUK_LJ_TYPE_RETURN 1 /* value1 -> return value */
  7259. #define DUK_LJ_TYPE_THROW 2 /* value1 -> error object */
  7260. #define DUK_LJ_TYPE_BREAK 3 /* value1 -> label number */
  7261. #define DUK_LJ_TYPE_CONTINUE 4 /* value1 -> label number */
  7262. #define DUK_LJ_TYPE_YIELD 5 /* value1 -> yield value, iserror -> error / normal */
  7263. #define DUK_LJ_TYPE_RESUME 6 /* value1 -> resume value, value2 -> resumee thread, iserror -> error/normal */
  7264. #define DUK_LJ_TYPE_NORMAL 7 /* pseudo-type to indicate a normal continuation (for 'finally' rethrowing) */
  7265. /*
  7266. * Mark-and-sweep flags
  7267. *
  7268. * These are separate from heap level flags now but could be merged.
  7269. * The heap structure only contains a 'base mark-and-sweep flags'
  7270. * field and the GC caller can impose further flags.
  7271. */
  7272. #define DUK_MS_FLAG_EMERGENCY (1 << 0) /* emergency mode: try extra hard */
  7273. #define DUK_MS_FLAG_NO_STRINGTABLE_RESIZE (1 << 1) /* don't resize stringtable (but may sweep it); needed during stringtable resize */
  7274. #define DUK_MS_FLAG_NO_FINALIZERS (1 << 2) /* don't run finalizers (which may have arbitrary side effects) */
  7275. #define DUK_MS_FLAG_NO_OBJECT_COMPACTION (1 << 3) /* don't compact objects; needed during object property allocation resize */
  7276. /*
  7277. * Thread switching
  7278. *
  7279. * To switch heap->curr_thread, use the macro below so that interrupt counters
  7280. * get updated correctly. The macro allows a NULL target thread because that
  7281. * happens e.g. in call handling.
  7282. */
  7283. #if defined(DUK_USE_INTERRUPT_COUNTER)
  7284. #define DUK_HEAP_SWITCH_THREAD(heap,newthr) duk_heap_switch_thread((heap), (newthr))
  7285. #else
  7286. #define DUK_HEAP_SWITCH_THREAD(heap,newthr) do { \
  7287. (heap)->curr_thread = (newthr); \
  7288. } while (0)
  7289. #endif
  7290. /*
  7291. * Other heap related defines
  7292. */
  7293. /* Maximum duk_handle_call / duk_handle_safe_call depth. Note that this
  7294. * does not limit bytecode executor internal call depth at all (e.g.
  7295. * for Ecmascript-to-Ecmascript calls, thread yields/resumes, etc).
  7296. * There is a separate callstack depth limit for threads.
  7297. */
  7298. #if defined(DUK_USE_DEEP_C_STACK)
  7299. #define DUK_HEAP_DEFAULT_CALL_RECURSION_LIMIT 1000 /* assuming 0.5 kB between calls, about 500kB of stack */
  7300. #else
  7301. #define DUK_HEAP_DEFAULT_CALL_RECURSION_LIMIT 60 /* assuming 0.5 kB between calls, about 30kB of stack */
  7302. #endif
  7303. /* Mark-and-sweep C recursion depth for marking phase; if reached,
  7304. * mark object as a TEMPROOT and use multi-pass marking.
  7305. */
  7306. #if defined(DUK_USE_MARK_AND_SWEEP)
  7307. #if defined(DUK_USE_GC_TORTURE)
  7308. #define DUK_HEAP_MARK_AND_SWEEP_RECURSION_LIMIT 3
  7309. #elif defined(DUK_USE_DEEP_C_STACK)
  7310. #define DUK_HEAP_MARK_AND_SWEEP_RECURSION_LIMIT 256
  7311. #else
  7312. #define DUK_HEAP_MARK_AND_SWEEP_RECURSION_LIMIT 32
  7313. #endif
  7314. #endif
  7315. /* Mark-and-sweep interval is relative to combined count of objects and
  7316. * strings kept in the heap during the latest mark-and-sweep pass.
  7317. * Fixed point .8 multiplier and .0 adder. Trigger count (interval) is
  7318. * decreased by each (re)allocation attempt (regardless of size), and each
  7319. * refzero processed object.
  7320. *
  7321. * 'SKIP' indicates how many (re)allocations to wait until a retry if
  7322. * GC is skipped because there is no thread do it with yet (happens
  7323. * only during init phases).
  7324. */
  7325. #if defined(DUK_USE_MARK_AND_SWEEP)
  7326. #if defined(DUK_USE_REFERENCE_COUNTING)
  7327. #define DUK_HEAP_MARK_AND_SWEEP_TRIGGER_MULT 12800L /* 50x heap size */
  7328. #define DUK_HEAP_MARK_AND_SWEEP_TRIGGER_ADD 1024L
  7329. #define DUK_HEAP_MARK_AND_SWEEP_TRIGGER_SKIP 256L
  7330. #else
  7331. #define DUK_HEAP_MARK_AND_SWEEP_TRIGGER_MULT 256L /* 1x heap size */
  7332. #define DUK_HEAP_MARK_AND_SWEEP_TRIGGER_ADD 1024L
  7333. #define DUK_HEAP_MARK_AND_SWEEP_TRIGGER_SKIP 256L
  7334. #endif
  7335. #endif
  7336. /* Stringcache is used for speeding up char-offset-to-byte-offset
  7337. * translations for non-ASCII strings.
  7338. */
  7339. #define DUK_HEAP_STRCACHE_SIZE 4
  7340. #define DUK_HEAP_STRINGCACHE_NOCACHE_LIMIT 16 /* strings up to the this length are not cached */
  7341. /* helper to insert a (non-string) heap object into heap allocated list */
  7342. #define DUK_HEAP_INSERT_INTO_HEAP_ALLOCATED(heap,hdr) duk_heap_insert_into_heap_allocated((heap),(hdr))
  7343. /* Executor interrupt default interval when nothing else requires a
  7344. * smaller value. The default interval must be small enough to allow
  7345. * for reasonable execution timeout checking.
  7346. */
  7347. #if defined(DUK_USE_INTERRUPT_COUNTER)
  7348. #define DUK_HEAP_INTCTR_DEFAULT (256L * 1024L)
  7349. #endif
  7350. /*
  7351. * Stringtable
  7352. */
  7353. /* initial stringtable size, must be prime and higher than DUK_UTIL_MIN_HASH_PRIME */
  7354. #define DUK_STRTAB_INITIAL_SIZE 17
  7355. /* indicates a deleted string; any fixed non-NULL, non-hstring pointer works */
  7356. #define DUK_STRTAB_DELETED_MARKER(heap) ((duk_hstring *) heap)
  7357. /* resizing parameters */
  7358. #define DUK_STRTAB_MIN_FREE_DIVISOR 4 /* load factor max 75% */
  7359. #define DUK_STRTAB_MIN_USED_DIVISOR 4 /* load factor min 25% */
  7360. #define DUK_STRTAB_GROW_ST_SIZE(n) ((n) + (n)) /* used entries + approx 100% -> reset load to 50% */
  7361. #define DUK_STRTAB_U32_MAX_STRLEN 10 /* 4'294'967'295 */
  7362. #define DUK_STRTAB_HIGHEST_32BIT_PRIME 0xfffffffbUL
  7363. /* probe sequence (open addressing) */
  7364. #define DUK_STRTAB_HASH_INITIAL(hash,h_size) ((hash) % (h_size))
  7365. #define DUK_STRTAB_HASH_PROBE_STEP(hash) DUK_UTIL_GET_HASH_PROBE_STEP((hash))
  7366. /* fixed top level hashtable size (separate chaining) */
  7367. #define DUK_STRTAB_CHAIN_SIZE DUK_USE_STRTAB_CHAIN_SIZE
  7368. /*
  7369. * Built-in strings
  7370. */
  7371. /* heap string indices are autogenerated in duk_strings.h */
  7372. #if defined(DUK_USE_HEAPPTR16)
  7373. #define DUK_HEAP_GET_STRING(heap,idx) \
  7374. ((duk_hstring *) DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, (heap)->strs16[(idx)]))
  7375. #else
  7376. #define DUK_HEAP_GET_STRING(heap,idx) \
  7377. ((heap)->strs[(idx)])
  7378. #endif
  7379. /*
  7380. * Raw memory calls: relative to heap, but no GC interaction
  7381. */
  7382. #define DUK_ALLOC_RAW(heap,size) \
  7383. ((heap)->alloc_func((heap)->heap_udata, (size)))
  7384. #define DUK_REALLOC_RAW(heap,ptr,newsize) \
  7385. ((heap)->realloc_func((heap)->heap_udata, (void *) (ptr), (newsize)))
  7386. #define DUK_FREE_RAW(heap,ptr) \
  7387. ((heap)->free_func((heap)->heap_udata, (void *) (ptr)))
  7388. /*
  7389. * Memory calls: relative to heap, GC interaction, but no error throwing.
  7390. *
  7391. * XXX: Currently a mark-and-sweep triggered by memory allocation will run
  7392. * using the heap->heap_thread. This thread is also used for running
  7393. * mark-and-sweep finalization; this is not ideal because it breaks the
  7394. * isolation between multiple global environments.
  7395. *
  7396. * Notes:
  7397. *
  7398. * - DUK_FREE() is required to ignore NULL and any other possible return
  7399. * value of a zero-sized alloc/realloc (same as ANSI C free()).
  7400. *
  7401. * - There is no DUK_REALLOC_ZEROED because we don't assume to know the
  7402. * old size. Caller must zero the reallocated memory.
  7403. *
  7404. * - DUK_REALLOC_INDIRECT() must be used when a mark-and-sweep triggered
  7405. * by an allocation failure might invalidate the original 'ptr', thus
  7406. * causing a realloc retry to use an invalid pointer. Example: we're
  7407. * reallocating the value stack and a finalizer resizes the same value
  7408. * stack during mark-and-sweep. The indirect variant requests for the
  7409. * current location of the pointer being reallocated using a callback
  7410. * right before every realloc attempt; this circuitous approach is used
  7411. * to avoid strict aliasing issues in a more straightforward indirect
  7412. * pointer (void **) approach. Note: the pointer in the storage
  7413. * location is read but is NOT updated; the caller must do that.
  7414. */
  7415. /* callback for indirect reallocs, request for current pointer */
  7416. typedef void *(*duk_mem_getptr)(duk_heap *heap, void *ud);
  7417. #define DUK_ALLOC(heap,size) duk_heap_mem_alloc((heap), (size))
  7418. #define DUK_ALLOC_ZEROED(heap,size) duk_heap_mem_alloc_zeroed((heap), (size))
  7419. #define DUK_REALLOC(heap,ptr,newsize) duk_heap_mem_realloc((heap), (ptr), (newsize))
  7420. #define DUK_REALLOC_INDIRECT(heap,cb,ud,newsize) duk_heap_mem_realloc_indirect((heap), (cb), (ud), (newsize))
  7421. #define DUK_FREE(heap,ptr) duk_heap_mem_free((heap), (ptr))
  7422. /*
  7423. * Memory constants
  7424. */
  7425. #define DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_LIMIT 5 /* Retry allocation after mark-and-sweep for this
  7426. * many times. A single mark-and-sweep round is
  7427. * not guaranteed to free all unreferenced memory
  7428. * because of finalization (in fact, ANY number of
  7429. * rounds is strictly not enough).
  7430. */
  7431. #define DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_EMERGENCY_LIMIT 3 /* Starting from this round, use emergency mode
  7432. * for mark-and-sweep.
  7433. */
  7434. /*
  7435. * Debugger support
  7436. */
  7437. /* Maximum number of breakpoints. Only breakpoints that are set are
  7438. * consulted so increasing this has no performance impact.
  7439. */
  7440. #define DUK_HEAP_MAX_BREAKPOINTS 16
  7441. /* Opcode interval for a Date-based status/peek rate limit check. Only
  7442. * relevant when debugger is attached. Requesting a timestamp may be a
  7443. * slow operation on some platforms so this shouldn't be too low. On the
  7444. * other hand a high value makes Duktape react to a pause request slowly.
  7445. */
  7446. #define DUK_HEAP_DBG_RATELIMIT_OPCODES 4000
  7447. /* Milliseconds between status notify and transport peeks. */
  7448. #define DUK_HEAP_DBG_RATELIMIT_MILLISECS 200
  7449. /* Step types */
  7450. #define DUK_STEP_TYPE_NONE 0
  7451. #define DUK_STEP_TYPE_INTO 1
  7452. #define DUK_STEP_TYPE_OVER 2
  7453. #define DUK_STEP_TYPE_OUT 3
  7454. struct duk_breakpoint {
  7455. duk_hstring *filename;
  7456. duk_uint32_t line;
  7457. };
  7458. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  7459. #define DUK_HEAP_IS_DEBUGGER_ATTACHED(heap) ((heap)->dbg_read_cb != NULL)
  7460. #define DUK_HEAP_CLEAR_STEP_STATE(heap) do { \
  7461. (heap)->dbg_step_type = DUK_STEP_TYPE_NONE; \
  7462. (heap)->dbg_step_thread = NULL; \
  7463. (heap)->dbg_step_csindex = 0; \
  7464. (heap)->dbg_step_startline = 0; \
  7465. } while (0)
  7466. #define DUK_HEAP_SET_PAUSED(heap) do { \
  7467. (heap)->dbg_paused = 1; \
  7468. (heap)->dbg_state_dirty = 1; \
  7469. DUK_HEAP_CLEAR_STEP_STATE((heap)); \
  7470. } while (0)
  7471. #define DUK_HEAP_CLEAR_PAUSED(heap) do { \
  7472. (heap)->dbg_paused = 0; \
  7473. (heap)->dbg_state_dirty = 1; \
  7474. DUK_HEAP_CLEAR_STEP_STATE((heap)); \
  7475. } while (0)
  7476. #endif /* DUK_USE_DEBUGGER_SUPPORT */
  7477. /*
  7478. * String cache should ideally be at duk_hthread level, but that would
  7479. * cause string finalization to slow down relative to the number of
  7480. * threads; string finalization must check the string cache for "weak"
  7481. * references to the string being finalized to avoid dead pointers.
  7482. *
  7483. * Thus, string caches are now at the heap level now.
  7484. */
  7485. struct duk_strcache {
  7486. duk_hstring *h;
  7487. duk_uint32_t bidx;
  7488. duk_uint32_t cidx;
  7489. };
  7490. /*
  7491. * Longjmp state, contains the information needed to perform a longjmp.
  7492. * Longjmp related values are written to value1, value2, and iserror.
  7493. */
  7494. struct duk_ljstate {
  7495. duk_jmpbuf *jmpbuf_ptr; /* current setjmp() catchpoint */
  7496. duk_small_uint_t type; /* longjmp type */
  7497. duk_bool_t iserror; /* isError flag for yield */
  7498. duk_tval value1; /* 1st related value (type specific) */
  7499. duk_tval value2; /* 2nd related value (type specific) */
  7500. };
  7501. /*
  7502. * Stringtable entry for fixed size stringtable
  7503. */
  7504. struct duk_strtab_entry {
  7505. #if defined(DUK_USE_HEAPPTR16)
  7506. /* A 16-bit listlen makes sense with 16-bit heap pointers: there
  7507. * won't be space for 64k strings anyway.
  7508. */
  7509. duk_uint16_t listlen; /* if 0, 'str16' used, if > 0, 'strlist16' used */
  7510. union {
  7511. duk_uint16_t strlist16;
  7512. duk_uint16_t str16;
  7513. } u;
  7514. #else
  7515. duk_size_t listlen; /* if 0, 'str' used, if > 0, 'strlist' used */
  7516. union {
  7517. duk_hstring **strlist;
  7518. duk_hstring *str;
  7519. } u;
  7520. #endif
  7521. };
  7522. /*
  7523. * Main heap structure
  7524. */
  7525. struct duk_heap {
  7526. duk_small_uint_t flags;
  7527. /* Allocator functions. */
  7528. duk_alloc_function alloc_func;
  7529. duk_realloc_function realloc_func;
  7530. duk_free_function free_func;
  7531. /* Heap udata, used for allocator functions but also for other heap
  7532. * level callbacks like pointer compression, etc.
  7533. */
  7534. void *heap_udata;
  7535. /* Precomputed pointers when using 16-bit heap pointer packing. */
  7536. #if defined(DUK_USE_HEAPPTR16)
  7537. duk_uint16_t heapptr_null16;
  7538. duk_uint16_t heapptr_deleted16;
  7539. #endif
  7540. /* Fatal error handling, called e.g. when a longjmp() is needed but
  7541. * lj.jmpbuf_ptr is NULL. fatal_func must never return; it's not
  7542. * declared as "noreturn" because doing that for typedefs is a bit
  7543. * challenging portability-wise.
  7544. */
  7545. duk_fatal_function fatal_func;
  7546. /* allocated heap objects */
  7547. duk_heaphdr *heap_allocated;
  7548. /* work list for objects whose refcounts are zero but which have not been
  7549. * "finalized"; avoids recursive C calls when refcounts go to zero in a
  7550. * chain of objects.
  7551. */
  7552. #if defined(DUK_USE_REFERENCE_COUNTING)
  7553. duk_heaphdr *refzero_list;
  7554. duk_heaphdr *refzero_list_tail;
  7555. #endif
  7556. #if defined(DUK_USE_MARK_AND_SWEEP)
  7557. /* mark-and-sweep control */
  7558. #if defined(DUK_USE_VOLUNTARY_GC)
  7559. duk_int_t mark_and_sweep_trigger_counter;
  7560. #endif
  7561. duk_int_t mark_and_sweep_recursion_depth;
  7562. /* mark-and-sweep flags automatically active (used for critical sections) */
  7563. duk_small_uint_t mark_and_sweep_base_flags;
  7564. /* work list for objects to be finalized (by mark-and-sweep) */
  7565. duk_heaphdr *finalize_list;
  7566. #endif
  7567. /* longjmp state */
  7568. duk_ljstate lj;
  7569. /* marker for detecting internal "double faults", see duk_error_throw.c */
  7570. duk_bool_t handling_error;
  7571. /* heap thread, used internally and for finalization */
  7572. duk_hthread *heap_thread;
  7573. /* current thread */
  7574. duk_hthread *curr_thread; /* currently running thread */
  7575. /* heap level "stash" object (e.g., various reachability roots) */
  7576. duk_hobject *heap_object;
  7577. /* heap level temporary log formatting buffer */
  7578. duk_hbuffer_dynamic *log_buffer;
  7579. /* duk_handle_call / duk_handle_safe_call recursion depth limiting */
  7580. duk_int_t call_recursion_depth;
  7581. duk_int_t call_recursion_limit;
  7582. /* mix-in value for computing string hashes; should be reasonably unpredictable */
  7583. duk_uint32_t hash_seed;
  7584. /* rnd_state for duk_util_tinyrandom.c */
  7585. duk_uint32_t rnd_state;
  7586. /* interrupt counter */
  7587. #if defined(DUK_USE_INTERRUPT_COUNTER)
  7588. duk_int_t interrupt_init; /* start value for current countdown */
  7589. duk_int_t interrupt_counter; /* countdown state (mirrored in current thread state) */
  7590. #endif
  7591. /* debugger */
  7592. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  7593. /* callbacks and udata; dbg_read_cb != NULL is used to indicate attached state */
  7594. duk_debug_read_function dbg_read_cb; /* required, NULL implies detached */
  7595. duk_debug_write_function dbg_write_cb; /* required */
  7596. duk_debug_peek_function dbg_peek_cb;
  7597. duk_debug_read_flush_function dbg_read_flush_cb;
  7598. duk_debug_write_flush_function dbg_write_flush_cb;
  7599. duk_debug_detached_function dbg_detached_cb;
  7600. void *dbg_udata;
  7601. /* debugger state, only relevant when attached */
  7602. duk_bool_t dbg_processing; /* currently processing messages or breakpoints: don't enter message processing recursively (e.g. no breakpoints when processing debugger eval) */
  7603. duk_bool_t dbg_paused; /* currently paused: talk with debug client until step/resume */
  7604. duk_bool_t dbg_state_dirty; /* resend state next time executor is about to run */
  7605. duk_small_uint_t dbg_step_type; /* step type: none, step into, step over, step out */
  7606. duk_hthread *dbg_step_thread; /* borrowed; NULL if no step state (NULLed in unwind) */
  7607. duk_size_t dbg_step_csindex; /* callstack index */
  7608. duk_uint32_t dbg_step_startline; /* starting line number */
  7609. duk_breakpoint dbg_breakpoints[DUK_HEAP_MAX_BREAKPOINTS]; /* breakpoints: [0,breakpoint_count[ gc reachable */
  7610. duk_small_uint_t dbg_breakpoint_count;
  7611. duk_breakpoint *dbg_breakpoints_active[DUK_HEAP_MAX_BREAKPOINTS + 1]; /* currently active breakpoints: NULL term, borrowed pointers */
  7612. /* XXX: make active breakpoints actual copies instead of pointers? */
  7613. /* These are for rate limiting Status notifications and transport peeking. */
  7614. duk_uint32_t dbg_exec_counter; /* cumulative opcode execution count (overflows are OK) */
  7615. duk_uint32_t dbg_last_counter; /* value of dbg_exec_counter when we last did a Date-based check */
  7616. duk_double_t dbg_last_time; /* time when status/peek was last done (Date-based rate limit) */
  7617. #endif
  7618. /* string intern table (weak refs) */
  7619. #if defined(DUK_USE_STRTAB_PROBE)
  7620. #if defined(DUK_USE_HEAPPTR16)
  7621. duk_uint16_t *strtable16;
  7622. #else
  7623. duk_hstring **strtable;
  7624. #endif
  7625. duk_uint32_t st_size; /* alloc size in elements */
  7626. duk_uint32_t st_used; /* used elements (includes DELETED) */
  7627. #endif
  7628. /* XXX: static alloc is OK until separate chaining stringtable
  7629. * resizing is implemented.
  7630. */
  7631. #if defined(DUK_USE_STRTAB_CHAIN)
  7632. duk_strtab_entry strtable[DUK_STRTAB_CHAIN_SIZE];
  7633. #endif
  7634. /* string access cache (codepoint offset -> byte offset) for fast string
  7635. * character looping; 'weak' reference which needs special handling in GC.
  7636. */
  7637. duk_strcache strcache[DUK_HEAP_STRCACHE_SIZE];
  7638. /* built-in strings */
  7639. #if defined(DUK_USE_HEAPPTR16)
  7640. duk_uint16_t strs16[DUK_HEAP_NUM_STRINGS];
  7641. #else
  7642. duk_hstring *strs[DUK_HEAP_NUM_STRINGS];
  7643. #endif
  7644. };
  7645. /*
  7646. * Prototypes
  7647. */
  7648. DUK_INTERNAL_DECL
  7649. duk_heap *duk_heap_alloc(duk_alloc_function alloc_func,
  7650. duk_realloc_function realloc_func,
  7651. duk_free_function free_func,
  7652. void *heap_udata,
  7653. duk_fatal_function fatal_func);
  7654. DUK_INTERNAL_DECL void duk_heap_free(duk_heap *heap);
  7655. DUK_INTERNAL_DECL void duk_free_hobject_inner(duk_heap *heap, duk_hobject *h);
  7656. DUK_INTERNAL_DECL void duk_free_hbuffer_inner(duk_heap *heap, duk_hbuffer *h);
  7657. DUK_INTERNAL_DECL void duk_free_hstring_inner(duk_heap *heap, duk_hstring *h);
  7658. DUK_INTERNAL_DECL void duk_heap_free_heaphdr_raw(duk_heap *heap, duk_heaphdr *hdr);
  7659. DUK_INTERNAL_DECL void duk_heap_insert_into_heap_allocated(duk_heap *heap, duk_heaphdr *hdr);
  7660. #if defined(DUK_USE_DOUBLE_LINKED_HEAP) && defined(DUK_USE_REFERENCE_COUNTING)
  7661. DUK_INTERNAL_DECL void duk_heap_remove_any_from_heap_allocated(duk_heap *heap, duk_heaphdr *hdr);
  7662. #endif
  7663. #if defined(DUK_USE_INTERRUPT_COUNTER)
  7664. DUK_INTERNAL_DECL void duk_heap_switch_thread(duk_heap *heap, duk_hthread *new_thr);
  7665. #endif
  7666. #if 0 /*unused*/
  7667. DUK_INTERNAL_DECL duk_hstring *duk_heap_string_lookup(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen);
  7668. #endif
  7669. DUK_INTERNAL_DECL duk_hstring *duk_heap_string_intern(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen);
  7670. DUK_INTERNAL_DECL duk_hstring *duk_heap_string_intern_checked(duk_hthread *thr, const duk_uint8_t *str, duk_uint32_t len);
  7671. #if 0 /*unused*/
  7672. DUK_INTERNAL_DECL duk_hstring *duk_heap_string_lookup_u32(duk_heap *heap, duk_uint32_t val);
  7673. #endif
  7674. DUK_INTERNAL_DECL duk_hstring *duk_heap_string_intern_u32(duk_heap *heap, duk_uint32_t val);
  7675. DUK_INTERNAL_DECL duk_hstring *duk_heap_string_intern_u32_checked(duk_hthread *thr, duk_uint32_t val);
  7676. DUK_INTERNAL_DECL void duk_heap_string_remove(duk_heap *heap, duk_hstring *h);
  7677. #if defined(DUK_USE_MARK_AND_SWEEP) && defined(DUK_USE_MS_STRINGTABLE_RESIZE)
  7678. DUK_INTERNAL_DECL void duk_heap_force_strtab_resize(duk_heap *heap);
  7679. #endif
  7680. DUK_INTERNAL void duk_heap_free_strtab(duk_heap *heap);
  7681. #if defined(DUK_USE_DEBUG)
  7682. DUK_INTERNAL void duk_heap_dump_strtab(duk_heap *heap);
  7683. #endif
  7684. DUK_INTERNAL_DECL void duk_heap_strcache_string_remove(duk_heap *heap, duk_hstring *h);
  7685. DUK_INTERNAL_DECL duk_uint_fast32_t duk_heap_strcache_offset_char2byte(duk_hthread *thr, duk_hstring *h, duk_uint_fast32_t char_offset);
  7686. #if defined(DUK_USE_PROVIDE_DEFAULT_ALLOC_FUNCTIONS)
  7687. DUK_INTERNAL_DECL void *duk_default_alloc_function(void *udata, duk_size_t size);
  7688. DUK_INTERNAL_DECL void *duk_default_realloc_function(void *udata, void *ptr, duk_size_t newsize);
  7689. DUK_INTERNAL_DECL void duk_default_free_function(void *udata, void *ptr);
  7690. #endif
  7691. DUK_INTERNAL_DECL void *duk_heap_mem_alloc(duk_heap *heap, duk_size_t size);
  7692. DUK_INTERNAL_DECL void *duk_heap_mem_alloc_zeroed(duk_heap *heap, duk_size_t size);
  7693. DUK_INTERNAL_DECL void *duk_heap_mem_realloc(duk_heap *heap, void *ptr, duk_size_t newsize);
  7694. DUK_INTERNAL_DECL void *duk_heap_mem_realloc_indirect(duk_heap *heap, duk_mem_getptr cb, void *ud, duk_size_t newsize);
  7695. DUK_INTERNAL_DECL void duk_heap_mem_free(duk_heap *heap, void *ptr);
  7696. #ifdef DUK_USE_REFERENCE_COUNTING
  7697. #if !defined(DUK_USE_FAST_REFCOUNT_DEFAULT)
  7698. DUK_INTERNAL_DECL void duk_tval_incref(duk_tval *tv);
  7699. #endif
  7700. #if 0 /* unused */
  7701. DUK_INTERNAL_DECL void duk_tval_incref_allownull(duk_tval *tv);
  7702. #endif
  7703. DUK_INTERNAL_DECL void duk_tval_decref(duk_hthread *thr, duk_tval *tv);
  7704. #if 0 /* unused */
  7705. DUK_INTERNAL_DECL void duk_tval_decref_allownull(duk_hthread *thr, duk_tval *tv);
  7706. #endif
  7707. #if !defined(DUK_USE_FAST_REFCOUNT_DEFAULT)
  7708. DUK_INTERNAL_DECL void duk_heaphdr_incref(duk_heaphdr *h);
  7709. #endif
  7710. #if 0 /* unused */
  7711. DUK_INTERNAL_DECL void duk_heaphdr_incref_allownull(duk_heaphdr *h);
  7712. #endif
  7713. DUK_INTERNAL_DECL void duk_heaphdr_decref(duk_hthread *thr, duk_heaphdr *h);
  7714. DUK_INTERNAL_DECL void duk_heaphdr_decref_allownull(duk_hthread *thr, duk_heaphdr *h);
  7715. DUK_INTERNAL_DECL void duk_heaphdr_refzero(duk_hthread *thr, duk_heaphdr *h);
  7716. DUK_INTERNAL_DECL void duk_heaphdr_refcount_finalize(duk_hthread *thr, duk_heaphdr *hdr);
  7717. #else
  7718. /* no refcounting */
  7719. #endif
  7720. #if defined(DUK_USE_MARK_AND_SWEEP)
  7721. DUK_INTERNAL_DECL duk_bool_t duk_heap_mark_and_sweep(duk_heap *heap, duk_small_uint_t flags);
  7722. #endif
  7723. DUK_INTERNAL_DECL duk_uint32_t duk_heap_hashstring(duk_heap *heap, const duk_uint8_t *str, duk_size_t len);
  7724. #endif /* DUK_HEAP_H_INCLUDED */
  7725. #line 1 "duk_debugger.h"
  7726. #ifndef DUK_DEBUGGER_H_INCLUDED
  7727. #define DUK_DEBUGGER_H_INCLUDED
  7728. /* Debugger protocol version is defined in the public API header. */
  7729. #define DUK_DBG_MARKER_EOM 0x00
  7730. #define DUK_DBG_MARKER_REQUEST 0x01
  7731. #define DUK_DBG_MARKER_REPLY 0x02
  7732. #define DUK_DBG_MARKER_ERROR 0x03
  7733. #define DUK_DBG_MARKER_NOTIFY 0x04
  7734. #define DUK_DBG_ERR_UNKNOWN 0x00
  7735. #define DUK_DBG_ERR_UNSUPPORTED 0x01
  7736. #define DUK_DBG_ERR_TOOMANY 0x02
  7737. #define DUK_DBG_ERR_NOTFOUND 0x03
  7738. /* Initiated by Duktape */
  7739. #define DUK_DBG_CMD_STATUS 0x01
  7740. #define DUK_DBG_CMD_PRINT 0x02
  7741. #define DUK_DBG_CMD_ALERT 0x03
  7742. #define DUK_DBG_CMD_LOG 0x04
  7743. /* Initiated by debug client */
  7744. #define DUK_DBG_CMD_BASICINFO 0x10
  7745. #define DUK_DBG_CMD_TRIGGERSTATUS 0x11
  7746. #define DUK_DBG_CMD_PAUSE 0x12
  7747. #define DUK_DBG_CMD_RESUME 0x13
  7748. #define DUK_DBG_CMD_STEPINTO 0x14
  7749. #define DUK_DBG_CMD_STEPOVER 0x15
  7750. #define DUK_DBG_CMD_STEPOUT 0x16
  7751. #define DUK_DBG_CMD_LISTBREAK 0x17
  7752. #define DUK_DBG_CMD_ADDBREAK 0x18
  7753. #define DUK_DBG_CMD_DELBREAK 0x19
  7754. #define DUK_DBG_CMD_GETVAR 0x1a
  7755. #define DUK_DBG_CMD_PUTVAR 0x1b
  7756. #define DUK_DBG_CMD_GETCALLSTACK 0x1c
  7757. #define DUK_DBG_CMD_GETLOCALS 0x1d
  7758. #define DUK_DBG_CMD_EVAL 0x1e
  7759. #define DUK_DBG_CMD_DETACH 0x1f
  7760. #define DUK_DBG_CMD_DUMPHEAP 0x20
  7761. #define DUK_DBG_CMD_GETBYTECODE 0x21
  7762. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  7763. DUK_INTERNAL_DECL void duk_debug_do_detach(duk_heap *heap);
  7764. DUK_INTERNAL_DECL duk_bool_t duk_debug_read_peek(duk_hthread *thr);
  7765. DUK_INTERNAL_DECL void duk_debug_write_flush(duk_hthread *thr);
  7766. DUK_INTERNAL_DECL void duk_debug_skip_bytes(duk_hthread *thr, duk_size_t length);
  7767. DUK_INTERNAL_DECL void duk_debug_skip_byte(duk_hthread *thr);
  7768. DUK_INTERNAL_DECL void duk_debug_read_bytes(duk_hthread *thr, duk_uint8_t *data, duk_size_t length);
  7769. DUK_INTERNAL_DECL duk_uint8_t duk_debug_read_byte(duk_hthread *thr);
  7770. DUK_INTERNAL_DECL duk_int32_t duk_debug_read_int(duk_hthread *thr);
  7771. DUK_INTERNAL_DECL duk_hstring *duk_debug_read_hstring(duk_hthread *thr);
  7772. /* XXX: exposed duk_debug_read_pointer */
  7773. /* XXX: exposed duk_debug_read_buffer */
  7774. /* XXX: exposed duk_debug_read_hbuffer */
  7775. DUK_INTERNAL_DECL void duk_debug_read_tval(duk_hthread *thr);
  7776. DUK_INTERNAL_DECL void duk_debug_write_bytes(duk_hthread *thr, const duk_uint8_t *data, duk_size_t length);
  7777. DUK_INTERNAL_DECL void duk_debug_write_byte(duk_hthread *thr, duk_uint8_t x);
  7778. DUK_INTERNAL_DECL void duk_debug_write_unused(duk_hthread *thr);
  7779. DUK_INTERNAL_DECL void duk_debug_write_undefined(duk_hthread *thr);
  7780. DUK_INTERNAL_DECL void duk_debug_write_int(duk_hthread *thr, duk_int32_t x);
  7781. DUK_INTERNAL_DECL void duk_debug_write_uint(duk_hthread *thr, duk_uint32_t x);
  7782. DUK_INTERNAL_DECL void duk_debug_write_string(duk_hthread *thr, const char *data, duk_size_t length);
  7783. DUK_INTERNAL_DECL void duk_debug_write_cstring(duk_hthread *thr, const char *data);
  7784. DUK_INTERNAL_DECL void duk_debug_write_hstring(duk_hthread *thr, duk_hstring *h);
  7785. DUK_INTERNAL_DECL void duk_debug_write_buffer(duk_hthread *thr, const char *data, duk_size_t length);
  7786. DUK_INTERNAL_DECL void duk_debug_write_hbuffer(duk_hthread *thr, duk_hbuffer *h);
  7787. DUK_INTERNAL_DECL void duk_debug_write_pointer(duk_hthread *thr, const void *ptr);
  7788. #if defined(DUK_USE_DEBUGGER_DUMPHEAP)
  7789. DUK_INTERNAL_DECL void duk_debug_write_heapptr(duk_hthread *thr, duk_heaphdr *h);
  7790. #endif
  7791. DUK_INTERNAL_DECL void duk_debug_write_hobject(duk_hthread *thr, duk_hobject *obj);
  7792. DUK_INTERNAL_DECL void duk_debug_write_tval(duk_hthread *thr, duk_tval *tv);
  7793. #if 0 /* unused */
  7794. DUK_INTERNAL_DECL void duk_debug_write_request(duk_hthread *thr, duk_small_uint_t command);
  7795. #endif
  7796. DUK_INTERNAL_DECL void duk_debug_write_reply(duk_hthread *thr);
  7797. DUK_INTERNAL_DECL void duk_debug_write_error_eom(duk_hthread *thr, duk_small_uint_t err_code, const char *msg);
  7798. DUK_INTERNAL_DECL void duk_debug_write_notify(duk_hthread *thr, duk_small_uint_t command);
  7799. DUK_INTERNAL_DECL void duk_debug_write_eom(duk_hthread *thr);
  7800. DUK_INTERNAL duk_uint_fast32_t duk_debug_curr_line(duk_hthread *thr);
  7801. DUK_INTERNAL void duk_debug_send_status(duk_hthread *thr);
  7802. DUK_INTERNAL_DECL duk_bool_t duk_debug_process_messages(duk_hthread *thr, duk_bool_t no_block);
  7803. DUK_INTERNAL_DECL duk_small_int_t duk_debug_add_breakpoint(duk_hthread *thr, duk_hstring *filename, duk_uint32_t line);
  7804. DUK_INTERNAL_DECL duk_bool_t duk_debug_remove_breakpoint(duk_hthread *thr, duk_small_uint_t breakpoint_index);
  7805. #endif
  7806. #endif /* DUK_DEBUGGER_H_INCLUDED */
  7807. #line 1 "duk_debug.h"
  7808. /*
  7809. * Debugging macros, DUK_DPRINT() and its variants in particular.
  7810. *
  7811. * DUK_DPRINT() allows formatted debug prints, and supports standard
  7812. * and Duktape specific formatters. See duk_debug_vsnprintf.c for details.
  7813. *
  7814. * DUK_D(x), DUK_DD(x), and DUK_DDD(x) are used together with log macros
  7815. * for technical reasons. They are concretely used to hide 'x' from the
  7816. * compiler when the corresponding log level is disabled. This allows
  7817. * clean builds on non-C99 compilers, at the cost of more verbose code.
  7818. * Examples:
  7819. *
  7820. * DUK_D(DUK_DPRINT("foo"));
  7821. * DUK_DD(DUK_DDPRINT("foo"));
  7822. * DUK_DDD(DUK_DDDPRINT("foo"));
  7823. *
  7824. * This approach is preferable to the old "double parentheses" hack because
  7825. * double parentheses make the C99 solution worse: __FILE__ and __LINE__ can
  7826. * no longer be added transparently without going through globals, which
  7827. * works poorly with threading.
  7828. */
  7829. #ifndef DUK_DEBUG_H_INCLUDED
  7830. #define DUK_DEBUG_H_INCLUDED
  7831. #ifdef DUK_USE_DEBUG
  7832. #if defined(DUK_USE_DPRINT)
  7833. #define DUK_D(x) x
  7834. #else
  7835. #define DUK_D(x) do { } while (0) /* omit */
  7836. #endif
  7837. #if defined(DUK_USE_DDPRINT)
  7838. #define DUK_DD(x) x
  7839. #else
  7840. #define DUK_DD(x) do { } while (0) /* omit */
  7841. #endif
  7842. #if defined(DUK_USE_DDDPRINT)
  7843. #define DUK_DDD(x) x
  7844. #else
  7845. #define DUK_DDD(x) do { } while (0) /* omit */
  7846. #endif
  7847. /*
  7848. * Exposed debug macros: debugging enabled
  7849. */
  7850. #define DUK_LEVEL_DEBUG 1
  7851. #define DUK_LEVEL_DDEBUG 2
  7852. #define DUK_LEVEL_DDDEBUG 3
  7853. #ifdef DUK_USE_VARIADIC_MACROS
  7854. /* Note: combining __FILE__, __LINE__, and __func__ into fmt would be
  7855. * possible compile time, but waste some space with shared function names.
  7856. */
  7857. #define DUK__DEBUG_LOG(lev,...) duk_debug_log((duk_small_int_t) (lev), DUK_FILE_MACRO, (duk_int_t) DUK_LINE_MACRO, DUK_FUNC_MACRO, __VA_ARGS__);
  7858. #define DUK_DPRINT(...) DUK__DEBUG_LOG(DUK_LEVEL_DEBUG, __VA_ARGS__)
  7859. #ifdef DUK_USE_DDPRINT
  7860. #define DUK_DDPRINT(...) DUK__DEBUG_LOG(DUK_LEVEL_DDEBUG, __VA_ARGS__)
  7861. #else
  7862. #define DUK_DDPRINT(...)
  7863. #endif
  7864. #ifdef DUK_USE_DDDPRINT
  7865. #define DUK_DDDPRINT(...) DUK__DEBUG_LOG(DUK_LEVEL_DDDEBUG, __VA_ARGS__)
  7866. #else
  7867. #define DUK_DDDPRINT(...)
  7868. #endif
  7869. #else /* DUK_USE_VARIADIC_MACROS */
  7870. #define DUK__DEBUG_STASH(lev) \
  7871. (void) DUK_SNPRINTF(duk_debug_file_stash, DUK_DEBUG_STASH_SIZE, "%s", (const char *) DUK_FILE_MACRO), \
  7872. duk_debug_file_stash[DUK_DEBUG_STASH_SIZE - 1] = (char) 0; \
  7873. (void) DUK_SNPRINTF(duk_debug_line_stash, DUK_DEBUG_STASH_SIZE, "%ld", (long) DUK_LINE_MACRO), \
  7874. duk_debug_line_stash[DUK_DEBUG_STASH_SIZE - 1] = (char) 0; \
  7875. (void) DUK_SNPRINTF(duk_debug_func_stash, DUK_DEBUG_STASH_SIZE, "%s", (const char *) DUK_FUNC_MACRO), \
  7876. duk_debug_func_stash[DUK_DEBUG_STASH_SIZE - 1] = (char) 0; \
  7877. (void) (duk_debug_level_stash = (lev))
  7878. /* Without variadic macros resort to comma expression trickery to handle debug
  7879. * prints. This generates a lot of harmless warnings. These hacks are not
  7880. * needed normally because DUK_D() and friends will hide the entire debug log
  7881. * statement from the compiler.
  7882. */
  7883. #ifdef DUK_USE_DPRINT
  7884. #define DUK_DPRINT DUK__DEBUG_STASH(DUK_LEVEL_DEBUG), (void) duk_debug_log /* args go here in parens */
  7885. #else
  7886. #define DUK_DPRINT 0 && /* args go here as a comma expression in parens */
  7887. #endif
  7888. #ifdef DUK_USE_DDPRINT
  7889. #define DUK_DDPRINT DUK__DEBUG_STASH(DUK_LEVEL_DDEBUG), (void) duk_debug_log /* args go here in parens */
  7890. #else
  7891. #define DUK_DDPRINT 0 && /* args */
  7892. #endif
  7893. #ifdef DUK_USE_DDDPRINT
  7894. #define DUK_DDDPRINT DUK__DEBUG_STASH(DUK_LEVEL_DDDEBUG), (void) duk_debug_log /* args go here in parens */
  7895. #else
  7896. #define DUK_DDDPRINT 0 && /* args */
  7897. #endif
  7898. #endif /* DUK_USE_VARIADIC_MACROS */
  7899. #else /* DUK_USE_DEBUG */
  7900. /*
  7901. * Exposed debug macros: debugging disabled
  7902. */
  7903. #define DUK_D(x) do { } while (0) /* omit */
  7904. #define DUK_DD(x) do { } while (0) /* omit */
  7905. #define DUK_DDD(x) do { } while (0) /* omit */
  7906. #ifdef DUK_USE_VARIADIC_MACROS
  7907. #define DUK_DPRINT(...)
  7908. #define DUK_DDPRINT(...)
  7909. #define DUK_DDDPRINT(...)
  7910. #else /* DUK_USE_VARIADIC_MACROS */
  7911. #define DUK_DPRINT 0 && /* args go here as a comma expression in parens */
  7912. #define DUK_DDPRINT 0 && /* args */
  7913. #define DUK_DDDPRINT 0 && /* args */
  7914. #endif /* DUK_USE_VARIADIC_MACROS */
  7915. #endif /* DUK_USE_DEBUG */
  7916. /*
  7917. * Structs
  7918. */
  7919. #ifdef DUK_USE_DEBUG
  7920. struct duk_fixedbuffer {
  7921. duk_uint8_t *buffer;
  7922. duk_size_t length;
  7923. duk_size_t offset;
  7924. duk_bool_t truncated;
  7925. };
  7926. #endif
  7927. /*
  7928. * Prototypes
  7929. */
  7930. #ifdef DUK_USE_DEBUG
  7931. DUK_INTERNAL_DECL duk_int_t duk_debug_vsnprintf(char *str, duk_size_t size, const char *format, va_list ap);
  7932. #if 0 /*unused*/
  7933. DUK_INTERNAL_DECL duk_int_t duk_debug_snprintf(char *str, duk_size_t size, const char *format, ...);
  7934. #endif
  7935. DUK_INTERNAL_DECL void duk_debug_format_funcptr(char *buf, duk_size_t buf_size, duk_uint8_t *fptr, duk_size_t fptr_size);
  7936. #ifdef DUK_USE_VARIADIC_MACROS
  7937. DUK_INTERNAL_DECL void duk_debug_log(duk_small_int_t level, const char *file, duk_int_t line, const char *func, const char *fmt, ...);
  7938. #else /* DUK_USE_VARIADIC_MACROS */
  7939. /* parameter passing, not thread safe */
  7940. #define DUK_DEBUG_STASH_SIZE 128
  7941. #if !defined(DUK_SINGLE_FILE)
  7942. DUK_INTERNAL_DECL char duk_debug_file_stash[DUK_DEBUG_STASH_SIZE];
  7943. DUK_INTERNAL_DECL char duk_debug_line_stash[DUK_DEBUG_STASH_SIZE];
  7944. DUK_INTERNAL_DECL char duk_debug_func_stash[DUK_DEBUG_STASH_SIZE];
  7945. DUK_INTERNAL_DECL duk_small_int_t duk_debug_level_stash;
  7946. #endif
  7947. DUK_INTERNAL_DECL void duk_debug_log(const char *fmt, ...);
  7948. #endif /* DUK_USE_VARIADIC_MACROS */
  7949. DUK_INTERNAL_DECL void duk_fb_put_bytes(duk_fixedbuffer *fb, duk_uint8_t *buffer, duk_size_t length);
  7950. DUK_INTERNAL_DECL void duk_fb_put_byte(duk_fixedbuffer *fb, duk_uint8_t x);
  7951. DUK_INTERNAL_DECL void duk_fb_put_cstring(duk_fixedbuffer *fb, const char *x);
  7952. DUK_INTERNAL_DECL void duk_fb_sprintf(duk_fixedbuffer *fb, const char *fmt, ...);
  7953. DUK_INTERNAL_DECL void duk_fb_put_funcptr(duk_fixedbuffer *fb, duk_uint8_t *fptr, duk_size_t fptr_size);
  7954. DUK_INTERNAL_DECL duk_bool_t duk_fb_is_full(duk_fixedbuffer *fb);
  7955. #endif /* DUK_USE_DEBUG */
  7956. #endif /* DUK_DEBUG_H_INCLUDED */
  7957. #line 1 "duk_error.h"
  7958. /*
  7959. * Error handling macros, assertion macro, error codes.
  7960. *
  7961. * There are three level of 'errors':
  7962. *
  7963. * 1. Ordinary errors, relative to a thread, cause a longjmp, catchable.
  7964. * 2. Fatal errors, relative to a heap, cause fatal handler to be called.
  7965. * 3. Panic errors, unrelated to a heap and cause a process exit.
  7966. *
  7967. * Panics are used by the default fatal error handler and by debug code
  7968. * such as assertions. By providing a proper fatal error handler, user
  7969. * code can avoid panics in non-debug builds.
  7970. */
  7971. #ifndef DUK_ERROR_H_INCLUDED
  7972. #define DUK_ERROR_H_INCLUDED
  7973. /*
  7974. * Error codes: defined in duktape.h
  7975. *
  7976. * Error codes are used as a shorthand to throw exceptions from inside
  7977. * the implementation. The appropriate Ecmascript object is constructed
  7978. * based on the code. Ecmascript code throws objects directly. The error
  7979. * codes are defined in the public API header because they are also used
  7980. * by calling code.
  7981. */
  7982. /*
  7983. * Normal error
  7984. *
  7985. * Normal error is thrown with a longjmp() through the current setjmp()
  7986. * catchpoint record in the duk_heap. The 'curr_thread' of the duk_heap
  7987. * identifies the throwing thread.
  7988. *
  7989. * Error formatting is not always necessary but there are no separate calls
  7990. * (to minimize code size). Error object creation will consume a considerable
  7991. * amount of time, compared to which formatting is probably trivial. Note
  7992. * that special formatting (provided by DUK_DEBUG macros) is NOT available.
  7993. *
  7994. * The _RAW variants allow the caller to specify file and line. This makes
  7995. * it easier to write checked calls which want to use the call site of the
  7996. * checked function, not the error macro call inside the checked function.
  7997. *
  7998. * We prefer the standard variadic macros; if they are not available, we
  7999. * fall back to awkward hacks.
  8000. */
  8001. #ifdef DUK_USE_VERBOSE_ERRORS
  8002. #ifdef DUK_USE_VARIADIC_MACROS
  8003. /* __VA_ARGS__ has comma issues for empty lists, so we mandate at least 1 argument for '...' (format string) */
  8004. #define DUK_ERROR(thr,err,...) duk_err_handle_error(DUK_FILE_MACRO, (duk_int_t) DUK_LINE_MACRO, (thr), (err), __VA_ARGS__)
  8005. #define DUK_ERROR_RAW(file,line,thr,err,...) duk_err_handle_error((file), (line), (thr), (err), __VA_ARGS__)
  8006. #else /* DUK_USE_VARIADIC_MACROS */
  8007. /* Parameter passing here is not thread safe. We rely on the __FILE__
  8008. * pointer being a constant which can be passed through a global.
  8009. */
  8010. #define DUK_ERROR \
  8011. (void) (duk_err_file_stash = (const char *) DUK_FILE_MACRO, \
  8012. duk_err_line_stash = (duk_int_t) DUK_LINE_MACRO, \
  8013. duk_err_handle_error_stash) /* arguments follow */
  8014. #define DUK_ERROR_RAW duk_err_handle_error
  8015. #endif /* DUK_USE_VARIADIC_MACROS */
  8016. #else /* DUK_USE_VERBOSE_ERRORS */
  8017. #ifdef DUK_USE_VARIADIC_MACROS
  8018. #define DUK_ERROR(thr,err,...) duk_err_handle_error((thr), (err))
  8019. #define DUK_ERROR_RAW(file,line,thr,err,...) duk_err_handle_error((thr), (err))
  8020. #else /* DUK_USE_VARIADIC_MACROS */
  8021. /* This is sub-optimal because arguments will be passed but ignored, and the strings
  8022. * will go into the object file. Can't think of how to do this portably and still
  8023. * relatively conveniently.
  8024. */
  8025. #define DUK_ERROR duk_err_handle_error_nonverbose1
  8026. #define DUK_ERROR_RAW duk_err_handle_error_nonverbose2
  8027. #endif /* DUK_USE_VARIADIC_MACROS */
  8028. #endif /* DUK_USE_VERBOSE_ERRORS */
  8029. /*
  8030. * Fatal error
  8031. *
  8032. * There are no fatal error macros at the moment. There are so few call
  8033. * sites that the fatal error handler is called directly.
  8034. */
  8035. /*
  8036. * Panic error
  8037. *
  8038. * Panic errors are not relative to either a heap or a thread, and cause
  8039. * DUK_PANIC() macro to be invoked. Unlesa a user provides DUK_OPT_PANIC_HANDLER,
  8040. * DUK_PANIC() calls a helper which prints out the error and causes a process
  8041. * exit.
  8042. *
  8043. * The user can override the macro to provide custom handling. A macro is
  8044. * used to allow the user to have inline panic handling if desired (without
  8045. * causing a potentially risky function call).
  8046. *
  8047. * Panics are only used in debug code such as assertions, and by the default
  8048. * fatal error handler.
  8049. */
  8050. #if defined(DUK_USE_PANIC_HANDLER)
  8051. /* already defined, good */
  8052. #define DUK_PANIC(code,msg) DUK_USE_PANIC_HANDLER((code),(msg))
  8053. #else
  8054. #define DUK_PANIC(code,msg) duk_default_panic_handler((code),(msg))
  8055. #endif /* DUK_USE_PANIC_HANDLER */
  8056. /*
  8057. * Assert macro: failure causes panic.
  8058. */
  8059. #ifdef DUK_USE_ASSERTIONS
  8060. /* the message should be a compile time constant without formatting (less risk);
  8061. * we don't care about assertion text size because they're not used in production
  8062. * builds.
  8063. */
  8064. #define DUK_ASSERT(x) do { \
  8065. if (!(x)) { \
  8066. DUK_PANIC(DUK_ERR_ASSERTION_ERROR, \
  8067. "assertion failed: " #x \
  8068. " (" DUK_FILE_MACRO ":" DUK_MACRO_STRINGIFY(DUK_LINE_MACRO) ")"); \
  8069. } \
  8070. } while (0)
  8071. #else /* DUK_USE_ASSERTIONS */
  8072. #define DUK_ASSERT(x) do { /* assertion omitted */ } while(0)
  8073. #endif /* DUK_USE_ASSERTIONS */
  8074. /* this variant is used when an assert would generate a compile warning by
  8075. * being always true (e.g. >= 0 comparison for an unsigned value
  8076. */
  8077. #define DUK_ASSERT_DISABLE(x) do { /* assertion disabled */ } while(0)
  8078. /*
  8079. * Assertion helpers
  8080. */
  8081. #if defined(DUK_USE_ASSERTIONS) && defined(DUK_USE_REFERENCE_COUNTING)
  8082. #define DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(h) do { \
  8083. DUK_ASSERT((h) == NULL || DUK_HEAPHDR_GET_REFCOUNT((duk_heaphdr *) (h)) > 0); \
  8084. } while (0)
  8085. #define DUK_ASSERT_REFCOUNT_NONZERO_TVAL(tv) do { \
  8086. if ((tv) != NULL && DUK_TVAL_IS_HEAP_ALLOCATED((tv))) { \
  8087. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(DUK_TVAL_GET_HEAPHDR((tv))) > 0); \
  8088. } \
  8089. } while (0)
  8090. #else
  8091. #define DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(h) /* no refcount check */
  8092. #define DUK_ASSERT_REFCOUNT_NONZERO_TVAL(tv) /* no refcount check */
  8093. #endif
  8094. #define DUK_ASSERT_TOP(ctx,n) DUK_ASSERT((duk_idx_t) duk_get_top((ctx)) == (duk_idx_t) (n))
  8095. #if defined(DUK_USE_ASSERTIONS) && defined(DUK_USE_PACKED_TVAL)
  8096. #define DUK_ASSERT_DOUBLE_IS_NORMALIZED(dval) do { \
  8097. duk_double_union assert_tmp_du; \
  8098. assert_tmp_du.d = (dval); \
  8099. DUK_ASSERT(DUK_DBLUNION_IS_NORMALIZED(&assert_tmp_du)); \
  8100. } while (0)
  8101. #else
  8102. #define DUK_ASSERT_DOUBLE_IS_NORMALIZED(dval) /* nop */
  8103. #endif
  8104. /*
  8105. * Helper for valstack space
  8106. *
  8107. * Caller of DUK_ASSERT_VALSTACK_SPACE() estimates the number of free stack entries
  8108. * required for its own use, and any child calls which are not (a) Duktape API calls
  8109. * or (b) Duktape calls which involve extending the valstack (e.g. getter call).
  8110. */
  8111. #define DUK_VALSTACK_ASSERT_EXTRA 5 /* this is added to checks to allow for Duktape
  8112. * API calls in addition to function's own use
  8113. */
  8114. #if defined(DUK_USE_ASSERTIONS)
  8115. #define DUK_ASSERT_VALSTACK_SPACE(thr,n) do { \
  8116. DUK_ASSERT((thr) != NULL); \
  8117. DUK_ASSERT((thr)->valstack_end - (thr)->valstack_top >= (n) + DUK_VALSTACK_ASSERT_EXTRA); \
  8118. } while (0)
  8119. #else
  8120. #define DUK_ASSERT_VALSTACK_SPACE(thr,n) /* no valstack space check */
  8121. #endif
  8122. /*
  8123. * Prototypes
  8124. */
  8125. #ifdef DUK_USE_VERBOSE_ERRORS
  8126. #ifdef DUK_USE_VARIADIC_MACROS
  8127. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_handle_error(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, ...));
  8128. #else /* DUK_USE_VARIADIC_MACROS */
  8129. #if !defined(DUK_SINGLE_FILE)
  8130. DUK_INTERNAL_DECL const char *duk_err_file_stash;
  8131. DUK_INTERNAL_DECL duk_int_t duk_err_line_stash;
  8132. #endif /* !DUK_SINGLE_FILE */
  8133. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_handle_error(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, ...));
  8134. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_handle_error_stash(duk_hthread *thr, duk_errcode_t code, const char *fmt, ...));
  8135. #endif /* DUK_USE_VARIADIC_MACROS */
  8136. #else /* DUK_USE_VERBOSE_ERRORS */
  8137. #ifdef DUK_USE_VARIADIC_MACROS
  8138. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_handle_error(duk_hthread *thr, duk_errcode_t code));
  8139. #else /* DUK_USE_VARIADIC_MACROS */
  8140. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_handle_error_nonverbose1(duk_hthread *thr, duk_errcode_t code, const char *fmt, ...));
  8141. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_handle_error_nonverbose2(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, ...));
  8142. #endif /* DUK_USE_VARIADIC_MACROS */
  8143. #endif /* DUK_USE_VERBOSE_ERRORS */
  8144. #ifdef DUK_USE_VERBOSE_ERRORS
  8145. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_create_and_throw(duk_hthread *thr, duk_errcode_t code, const char *msg, const char *filename, duk_int_t line));
  8146. #else
  8147. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_create_and_throw(duk_hthread *thr, duk_errcode_t code));
  8148. #endif
  8149. DUK_NORETURN(DUK_INTERNAL_DECL void duk_error_throw_from_negative_rc(duk_hthread *thr, duk_ret_t rc));
  8150. #if defined(DUK_USE_AUGMENT_ERROR_CREATE)
  8151. DUK_INTERNAL_DECL void duk_err_augment_error_create(duk_hthread *thr, duk_hthread *thr_callstack, const char *filename, duk_int_t line, duk_bool_t noblame_fileline);
  8152. #endif
  8153. #if defined(DUK_USE_AUGMENT_ERROR_THROW)
  8154. DUK_INTERNAL_DECL void duk_err_augment_error_throw(duk_hthread *thr);
  8155. #endif
  8156. DUK_NORETURN(DUK_INTERNAL_DECL void duk_err_longjmp(duk_hthread *thr));
  8157. DUK_NORETURN(DUK_INTERNAL_DECL void duk_default_fatal_handler(duk_context *ctx, duk_errcode_t code, const char *msg));
  8158. #if !defined(DUK_USE_PANIC_HANDLER)
  8159. DUK_NORETURN(DUK_INTERNAL_DECL void duk_default_panic_handler(duk_errcode_t code, const char *msg));
  8160. #endif
  8161. DUK_INTERNAL_DECL void duk_err_setup_heap_ljstate(duk_hthread *thr, duk_small_int_t lj_type);
  8162. DUK_INTERNAL_DECL duk_hobject *duk_error_prototype_from_code(duk_hthread *thr, duk_errcode_t err_code);
  8163. #endif /* DUK_ERROR_H_INCLUDED */
  8164. #line 1 "duk_util.h"
  8165. /*
  8166. * Utilities
  8167. */
  8168. #ifndef DUK_UTIL_H_INCLUDED
  8169. #define DUK_UTIL_H_INCLUDED
  8170. #define DUK_UTIL_MIN_HASH_PRIME 17 /* must match genhashsizes.py */
  8171. #define DUK_UTIL_GET_HASH_PROBE_STEP(hash) (duk_util_probe_steps[(hash) & 0x1f])
  8172. /*
  8173. * Bitstream decoder
  8174. */
  8175. struct duk_bitdecoder_ctx {
  8176. const duk_uint8_t *data;
  8177. duk_size_t offset;
  8178. duk_size_t length;
  8179. duk_uint32_t currval;
  8180. duk_small_int_t currbits;
  8181. };
  8182. /*
  8183. * Bitstream encoder
  8184. */
  8185. struct duk_bitencoder_ctx {
  8186. duk_uint8_t *data;
  8187. duk_size_t offset;
  8188. duk_size_t length;
  8189. duk_uint32_t currval;
  8190. duk_small_int_t currbits;
  8191. duk_small_int_t truncated;
  8192. };
  8193. /*
  8194. * Externs and prototypes
  8195. */
  8196. #if !defined(DUK_SINGLE_FILE)
  8197. DUK_INTERNAL_DECL duk_uint8_t duk_lc_digits[36];
  8198. DUK_INTERNAL_DECL duk_uint8_t duk_uc_nybbles[16];
  8199. DUK_INTERNAL_DECL duk_int8_t duk_hex_dectab[256];
  8200. #endif /* !DUK_SINGLE_FILE */
  8201. /* Note: assumes that duk_util_probe_steps size is 32 */
  8202. #if defined(DUK_USE_HOBJECT_HASH_PART) || defined(DUK_USE_STRTAB_PROBE)
  8203. #if !defined(DUK_SINGLE_FILE)
  8204. DUK_INTERNAL_DECL duk_uint8_t duk_util_probe_steps[32];
  8205. #endif /* !DUK_SINGLE_FILE */
  8206. #endif
  8207. DUK_INTERNAL_DECL duk_uint32_t duk_util_hashbytes(const duk_uint8_t *data, duk_size_t len, duk_uint32_t seed);
  8208. #if defined(DUK_USE_HOBJECT_HASH_PART) || defined(DUK_USE_STRTAB_PROBE)
  8209. DUK_INTERNAL_DECL duk_uint32_t duk_util_get_hash_prime(duk_uint32_t size);
  8210. #endif
  8211. DUK_INTERNAL_DECL duk_int32_t duk_bd_decode(duk_bitdecoder_ctx *ctx, duk_small_int_t bits);
  8212. DUK_INTERNAL_DECL duk_small_int_t duk_bd_decode_flag(duk_bitdecoder_ctx *ctx);
  8213. DUK_INTERNAL_DECL duk_int32_t duk_bd_decode_flagged(duk_bitdecoder_ctx *ctx, duk_small_int_t bits, duk_int32_t def_value);
  8214. DUK_INTERNAL_DECL void duk_be_encode(duk_bitencoder_ctx *ctx, duk_uint32_t data, duk_small_int_t bits);
  8215. DUK_INTERNAL_DECL void duk_be_finish(duk_bitencoder_ctx *ctx);
  8216. DUK_INTERNAL_DECL duk_uint32_t duk_util_tinyrandom_get_bits(duk_hthread *thr, duk_small_int_t n);
  8217. DUK_INTERNAL_DECL duk_double_t duk_util_tinyrandom_get_double(duk_hthread *thr);
  8218. #if defined(DUK_USE_DEBUGGER_SUPPORT) /* For now only needed by the debugger. */
  8219. DUK_INTERNAL void duk_byteswap_bytes(duk_uint8_t *p, duk_small_uint_t len);
  8220. #endif
  8221. #endif /* DUK_UTIL_H_INCLUDED */
  8222. #line 1 "duk_unicode.h"
  8223. /*
  8224. * Unicode helpers
  8225. */
  8226. #ifndef DUK_UNICODE_H_INCLUDED
  8227. #define DUK_UNICODE_H_INCLUDED
  8228. /*
  8229. * UTF-8 / XUTF-8 / CESU-8 constants
  8230. */
  8231. #define DUK_UNICODE_MAX_XUTF8_LENGTH 7 /* up to 36 bit codepoints */
  8232. #define DUK_UNICODE_MAX_CESU8_LENGTH 6 /* all codepoints up to U+10FFFF */
  8233. /*
  8234. * Useful Unicode codepoints
  8235. *
  8236. * Integer constants must be signed to avoid unexpected coercions
  8237. * in comparisons.
  8238. */
  8239. #define DUK_UNICODE_CP_ZWNJ 0x200cL /* zero-width non-joiner */
  8240. #define DUK_UNICODE_CP_ZWJ 0x200dL /* zero-width joiner */
  8241. #define DUK_UNICODE_CP_REPLACEMENT_CHARACTER 0xfffdL /* http://en.wikipedia.org/wiki/Replacement_character#Replacement_character */
  8242. /*
  8243. * ASCII character constants
  8244. *
  8245. * C character literals like 'x' have a platform specific value and do
  8246. * not match ASCII (UTF-8) values on e.g. EBCDIC platforms. So, use
  8247. * these (admittedly awkward) constants instead. These constants must
  8248. * also have signed values to avoid unexpected coercions in comparisons.
  8249. *
  8250. * http://en.wikipedia.org/wiki/ASCII
  8251. */
  8252. #define DUK_ASC_NUL 0x00
  8253. #define DUK_ASC_SOH 0x01
  8254. #define DUK_ASC_STX 0x02
  8255. #define DUK_ASC_ETX 0x03
  8256. #define DUK_ASC_EOT 0x04
  8257. #define DUK_ASC_ENQ 0x05
  8258. #define DUK_ASC_ACK 0x06
  8259. #define DUK_ASC_BEL 0x07
  8260. #define DUK_ASC_BS 0x08
  8261. #define DUK_ASC_HT 0x09
  8262. #define DUK_ASC_LF 0x0a
  8263. #define DUK_ASC_VT 0x0b
  8264. #define DUK_ASC_FF 0x0c
  8265. #define DUK_ASC_CR 0x0d
  8266. #define DUK_ASC_SO 0x0e
  8267. #define DUK_ASC_SI 0x0f
  8268. #define DUK_ASC_DLE 0x10
  8269. #define DUK_ASC_DC1 0x11
  8270. #define DUK_ASC_DC2 0x12
  8271. #define DUK_ASC_DC3 0x13
  8272. #define DUK_ASC_DC4 0x14
  8273. #define DUK_ASC_NAK 0x15
  8274. #define DUK_ASC_SYN 0x16
  8275. #define DUK_ASC_ETB 0x17
  8276. #define DUK_ASC_CAN 0x18
  8277. #define DUK_ASC_EM 0x19
  8278. #define DUK_ASC_SUB 0x1a
  8279. #define DUK_ASC_ESC 0x1b
  8280. #define DUK_ASC_FS 0x1c
  8281. #define DUK_ASC_GS 0x1d
  8282. #define DUK_ASC_RS 0x1e
  8283. #define DUK_ASC_US 0x1f
  8284. #define DUK_ASC_SPACE 0x20
  8285. #define DUK_ASC_EXCLAMATION 0x21
  8286. #define DUK_ASC_DOUBLEQUOTE 0x22
  8287. #define DUK_ASC_HASH 0x23
  8288. #define DUK_ASC_DOLLAR 0x24
  8289. #define DUK_ASC_PERCENT 0x25
  8290. #define DUK_ASC_AMP 0x26
  8291. #define DUK_ASC_SINGLEQUOTE 0x27
  8292. #define DUK_ASC_LPAREN 0x28
  8293. #define DUK_ASC_RPAREN 0x29
  8294. #define DUK_ASC_STAR 0x2a
  8295. #define DUK_ASC_PLUS 0x2b
  8296. #define DUK_ASC_COMMA 0x2c
  8297. #define DUK_ASC_MINUS 0x2d
  8298. #define DUK_ASC_PERIOD 0x2e
  8299. #define DUK_ASC_SLASH 0x2f
  8300. #define DUK_ASC_0 0x30
  8301. #define DUK_ASC_1 0x31
  8302. #define DUK_ASC_2 0x32
  8303. #define DUK_ASC_3 0x33
  8304. #define DUK_ASC_4 0x34
  8305. #define DUK_ASC_5 0x35
  8306. #define DUK_ASC_6 0x36
  8307. #define DUK_ASC_7 0x37
  8308. #define DUK_ASC_8 0x38
  8309. #define DUK_ASC_9 0x39
  8310. #define DUK_ASC_COLON 0x3a
  8311. #define DUK_ASC_SEMICOLON 0x3b
  8312. #define DUK_ASC_LANGLE 0x3c
  8313. #define DUK_ASC_EQUALS 0x3d
  8314. #define DUK_ASC_RANGLE 0x3e
  8315. #define DUK_ASC_QUESTION 0x3f
  8316. #define DUK_ASC_ATSIGN 0x40
  8317. #define DUK_ASC_UC_A 0x41
  8318. #define DUK_ASC_UC_B 0x42
  8319. #define DUK_ASC_UC_C 0x43
  8320. #define DUK_ASC_UC_D 0x44
  8321. #define DUK_ASC_UC_E 0x45
  8322. #define DUK_ASC_UC_F 0x46
  8323. #define DUK_ASC_UC_G 0x47
  8324. #define DUK_ASC_UC_H 0x48
  8325. #define DUK_ASC_UC_I 0x49
  8326. #define DUK_ASC_UC_J 0x4a
  8327. #define DUK_ASC_UC_K 0x4b
  8328. #define DUK_ASC_UC_L 0x4c
  8329. #define DUK_ASC_UC_M 0x4d
  8330. #define DUK_ASC_UC_N 0x4e
  8331. #define DUK_ASC_UC_O 0x4f
  8332. #define DUK_ASC_UC_P 0x50
  8333. #define DUK_ASC_UC_Q 0x51
  8334. #define DUK_ASC_UC_R 0x52
  8335. #define DUK_ASC_UC_S 0x53
  8336. #define DUK_ASC_UC_T 0x54
  8337. #define DUK_ASC_UC_U 0x55
  8338. #define DUK_ASC_UC_V 0x56
  8339. #define DUK_ASC_UC_W 0x57
  8340. #define DUK_ASC_UC_X 0x58
  8341. #define DUK_ASC_UC_Y 0x59
  8342. #define DUK_ASC_UC_Z 0x5a
  8343. #define DUK_ASC_LBRACKET 0x5b
  8344. #define DUK_ASC_BACKSLASH 0x5c
  8345. #define DUK_ASC_RBRACKET 0x5d
  8346. #define DUK_ASC_CARET 0x5e
  8347. #define DUK_ASC_UNDERSCORE 0x5f
  8348. #define DUK_ASC_GRAVE 0x60
  8349. #define DUK_ASC_LC_A 0x61
  8350. #define DUK_ASC_LC_B 0x62
  8351. #define DUK_ASC_LC_C 0x63
  8352. #define DUK_ASC_LC_D 0x64
  8353. #define DUK_ASC_LC_E 0x65
  8354. #define DUK_ASC_LC_F 0x66
  8355. #define DUK_ASC_LC_G 0x67
  8356. #define DUK_ASC_LC_H 0x68
  8357. #define DUK_ASC_LC_I 0x69
  8358. #define DUK_ASC_LC_J 0x6a
  8359. #define DUK_ASC_LC_K 0x6b
  8360. #define DUK_ASC_LC_L 0x6c
  8361. #define DUK_ASC_LC_M 0x6d
  8362. #define DUK_ASC_LC_N 0x6e
  8363. #define DUK_ASC_LC_O 0x6f
  8364. #define DUK_ASC_LC_P 0x70
  8365. #define DUK_ASC_LC_Q 0x71
  8366. #define DUK_ASC_LC_R 0x72
  8367. #define DUK_ASC_LC_S 0x73
  8368. #define DUK_ASC_LC_T 0x74
  8369. #define DUK_ASC_LC_U 0x75
  8370. #define DUK_ASC_LC_V 0x76
  8371. #define DUK_ASC_LC_W 0x77
  8372. #define DUK_ASC_LC_X 0x78
  8373. #define DUK_ASC_LC_Y 0x79
  8374. #define DUK_ASC_LC_Z 0x7a
  8375. #define DUK_ASC_LCURLY 0x7b
  8376. #define DUK_ASC_PIPE 0x7c
  8377. #define DUK_ASC_RCURLY 0x7d
  8378. #define DUK_ASC_TILDE 0x7e
  8379. #define DUK_ASC_DEL 0x7f
  8380. /*
  8381. * Unicode tables
  8382. */
  8383. #ifdef DUK_USE_SOURCE_NONBMP
  8384. /*
  8385. * Automatically generated by extract_chars.py, do not edit!
  8386. */
  8387. extern const duk_uint8_t duk_unicode_ids_noa[791];
  8388. #else
  8389. /*
  8390. * Automatically generated by extract_chars.py, do not edit!
  8391. */
  8392. extern const duk_uint8_t duk_unicode_ids_noabmp[611];
  8393. #endif
  8394. #ifdef DUK_USE_SOURCE_NONBMP
  8395. /*
  8396. * Automatically generated by extract_chars.py, do not edit!
  8397. */
  8398. extern const duk_uint8_t duk_unicode_ids_m_let_noa[42];
  8399. #else
  8400. /*
  8401. * Automatically generated by extract_chars.py, do not edit!
  8402. */
  8403. extern const duk_uint8_t duk_unicode_ids_m_let_noabmp[24];
  8404. #endif
  8405. #ifdef DUK_USE_SOURCE_NONBMP
  8406. /*
  8407. * Automatically generated by extract_chars.py, do not edit!
  8408. */
  8409. extern const duk_uint8_t duk_unicode_idp_m_ids_noa[397];
  8410. #else
  8411. /*
  8412. * Automatically generated by extract_chars.py, do not edit!
  8413. */
  8414. extern const duk_uint8_t duk_unicode_idp_m_ids_noabmp[348];
  8415. #endif
  8416. /*
  8417. * Automatically generated by extract_caseconv.py, do not edit!
  8418. */
  8419. extern const duk_uint8_t duk_unicode_caseconv_uc[1288];
  8420. extern const duk_uint8_t duk_unicode_caseconv_lc[616];
  8421. /*
  8422. * Extern
  8423. */
  8424. /* duk_unicode_support.c */
  8425. #if !defined(DUK_SINGLE_FILE)
  8426. DUK_INTERNAL_DECL duk_uint8_t duk_unicode_xutf8_markers[7];
  8427. DUK_INTERNAL_DECL duk_uint16_t duk_unicode_re_ranges_digit[2];
  8428. DUK_INTERNAL_DECL duk_uint16_t duk_unicode_re_ranges_white[22];
  8429. DUK_INTERNAL_DECL duk_uint16_t duk_unicode_re_ranges_wordchar[8];
  8430. DUK_INTERNAL_DECL duk_uint16_t duk_unicode_re_ranges_not_digit[4];
  8431. DUK_INTERNAL_DECL duk_uint16_t duk_unicode_re_ranges_not_white[24];
  8432. DUK_INTERNAL_DECL duk_uint16_t duk_unicode_re_ranges_not_wordchar[10];
  8433. #endif /* !DUK_SINGLE_FILE */
  8434. /*
  8435. * Prototypes
  8436. */
  8437. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_get_xutf8_length(duk_ucodepoint_t cp);
  8438. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_encode_xutf8(duk_ucodepoint_t cp, duk_uint8_t *out);
  8439. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_encode_cesu8(duk_ucodepoint_t cp, duk_uint8_t *out);
  8440. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_decode_xutf8(duk_hthread *thr, const duk_uint8_t **ptr, const duk_uint8_t *ptr_start, const duk_uint8_t *ptr_end, duk_ucodepoint_t *out_cp);
  8441. DUK_INTERNAL_DECL duk_ucodepoint_t duk_unicode_decode_xutf8_checked(duk_hthread *thr, const duk_uint8_t **ptr, const duk_uint8_t *ptr_start, const duk_uint8_t *ptr_end);
  8442. DUK_INTERNAL_DECL duk_size_t duk_unicode_unvalidated_utf8_length(const duk_uint8_t *data, duk_size_t blen);
  8443. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_is_whitespace(duk_codepoint_t cp);
  8444. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_is_line_terminator(duk_codepoint_t cp);
  8445. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_is_identifier_start(duk_codepoint_t cp);
  8446. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_is_identifier_part(duk_codepoint_t cp);
  8447. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_is_letter(duk_codepoint_t cp);
  8448. DUK_INTERNAL_DECL void duk_unicode_case_convert_string(duk_hthread *thr, duk_bool_t uppercase);
  8449. DUK_INTERNAL_DECL duk_codepoint_t duk_unicode_re_canonicalize_char(duk_hthread *thr, duk_codepoint_t cp);
  8450. DUK_INTERNAL_DECL duk_small_int_t duk_unicode_re_is_wordchar(duk_codepoint_t cp);
  8451. #endif /* DUK_UNICODE_H_INCLUDED */
  8452. #line 1 "duk_json.h"
  8453. /*
  8454. * Defines for JSON, especially duk_bi_json.c.
  8455. */
  8456. #ifndef DUK_JSON_H_INCLUDED
  8457. #define DUK_JSON_H_INCLUDED
  8458. /* Object/array recursion limit (to protect C stack) */
  8459. #if defined(DUK_USE_DEEP_C_STACK)
  8460. #define DUK_JSON_ENC_RECURSION_LIMIT 1000
  8461. #define DUK_JSON_DEC_RECURSION_LIMIT 1000
  8462. #else
  8463. #define DUK_JSON_ENC_RECURSION_LIMIT 100
  8464. #define DUK_JSON_DEC_RECURSION_LIMIT 100
  8465. #endif
  8466. /* Encoding/decoding flags */
  8467. #define DUK_JSON_FLAG_ASCII_ONLY (1 << 0) /* escape any non-ASCII characters */
  8468. #define DUK_JSON_FLAG_AVOID_KEY_QUOTES (1 << 1) /* avoid key quotes when key is an ASCII Identifier */
  8469. #define DUK_JSON_FLAG_EXT_CUSTOM (1 << 2) /* extended types: custom encoding */
  8470. #define DUK_JSON_FLAG_EXT_COMPATIBLE (1 << 3) /* extended types: compatible encoding */
  8471. /* How much stack to require on entry to object/array encode */
  8472. #define DUK_JSON_ENC_REQSTACK 32
  8473. /* How much stack to require on entry to object/array decode */
  8474. #define DUK_JSON_DEC_REQSTACK 32
  8475. /* Encoding state. Heap object references are all borrowed. */
  8476. typedef struct {
  8477. duk_hthread *thr;
  8478. duk_hbuffer_dynamic *h_buf;
  8479. duk_hobject *h_replacer; /* replacer function */
  8480. duk_hstring *h_gap; /* gap (if empty string, NULL) */
  8481. duk_hstring *h_indent; /* current indent (if gap is NULL, this is NULL) */
  8482. duk_idx_t idx_proplist; /* explicit PropertyList */
  8483. duk_idx_t idx_loop; /* valstack index of loop detection object */
  8484. duk_small_uint_t flags;
  8485. duk_small_uint_t flag_ascii_only;
  8486. duk_small_uint_t flag_avoid_key_quotes;
  8487. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  8488. duk_small_uint_t flag_ext_custom;
  8489. duk_small_uint_t flag_ext_compatible;
  8490. #endif
  8491. duk_int_t recursion_depth;
  8492. duk_int_t recursion_limit;
  8493. duk_uint_t mask_for_undefined; /* type bit mask: types which certainly produce 'undefined' */
  8494. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  8495. duk_small_uint_t stridx_custom_undefined;
  8496. duk_small_uint_t stridx_custom_nan;
  8497. duk_small_uint_t stridx_custom_neginf;
  8498. duk_small_uint_t stridx_custom_posinf;
  8499. duk_small_uint_t stridx_custom_function;
  8500. #endif
  8501. } duk_json_enc_ctx;
  8502. typedef struct {
  8503. duk_hthread *thr;
  8504. const duk_uint8_t *p;
  8505. const duk_uint8_t *p_start;
  8506. const duk_uint8_t *p_end;
  8507. duk_idx_t idx_reviver;
  8508. duk_small_uint_t flags;
  8509. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  8510. duk_small_uint_t flag_ext_custom;
  8511. duk_small_uint_t flag_ext_compatible;
  8512. #endif
  8513. duk_int_t recursion_depth;
  8514. duk_int_t recursion_limit;
  8515. } duk_json_dec_ctx;
  8516. #endif /* DUK_JSON_H_INCLUDED */
  8517. #line 1 "duk_js.h"
  8518. /*
  8519. * Ecmascript execution, support primitives.
  8520. */
  8521. #ifndef DUK_JS_H_INCLUDED
  8522. #define DUK_JS_H_INCLUDED
  8523. /* Flags for call handling. */
  8524. #define DUK_CALL_FLAG_PROTECTED (1 << 0) /* duk_handle_call: call is protected */
  8525. #define DUK_CALL_FLAG_IGNORE_RECLIMIT (1 << 1) /* duk_handle_call: call ignores C recursion limit (for errhandler calls) */
  8526. #define DUK_CALL_FLAG_CONSTRUCTOR_CALL (1 << 2) /* duk_handle_call: constructor call (i.e. called as 'new Foo()') */
  8527. #define DUK_CALL_FLAG_IS_RESUME (1 << 3) /* duk_handle_ecma_call_setup: setup for a resume() */
  8528. #define DUK_CALL_FLAG_IS_TAILCALL (1 << 4) /* duk_handle_ecma_call_setup: setup for a tailcall */
  8529. #define DUK_CALL_FLAG_DIRECT_EVAL (1 << 5) /* call is a direct eval call */
  8530. /* Flags for duk_js_equals_helper(). */
  8531. #define DUK_EQUALS_FLAG_SAMEVALUE (1 << 0) /* use SameValue instead of non-strict equality */
  8532. #define DUK_EQUALS_FLAG_STRICT (1 << 1) /* use strict equality instead of non-strict equality */
  8533. /* Flags for duk_js_compare_helper(). */
  8534. #define DUK_COMPARE_FLAG_EVAL_LEFT_FIRST (1 << 0) /* eval left argument first */
  8535. #define DUK_COMPARE_FLAG_NEGATE (1 << 1) /* negate result */
  8536. /* conversions, coercions, comparison, etc */
  8537. DUK_INTERNAL_DECL duk_bool_t duk_js_toboolean(duk_tval *tv);
  8538. DUK_INTERNAL_DECL duk_double_t duk_js_tonumber(duk_hthread *thr, duk_tval *tv);
  8539. DUK_INTERNAL_DECL duk_double_t duk_js_tointeger_number(duk_double_t x);
  8540. DUK_INTERNAL_DECL duk_double_t duk_js_tointeger(duk_hthread *thr, duk_tval *tv);
  8541. DUK_INTERNAL_DECL duk_uint32_t duk_js_touint32(duk_hthread *thr, duk_tval *tv);
  8542. DUK_INTERNAL_DECL duk_int32_t duk_js_toint32(duk_hthread *thr, duk_tval *tv);
  8543. DUK_INTERNAL_DECL duk_uint16_t duk_js_touint16(duk_hthread *thr, duk_tval *tv);
  8544. DUK_INTERNAL_DECL duk_small_int_t duk_js_to_arrayindex_raw_string(const duk_uint8_t *str, duk_uint32_t blen, duk_uarridx_t *out_idx);
  8545. DUK_INTERNAL_DECL duk_uarridx_t duk_js_to_arrayindex_string_helper(duk_hstring *h);
  8546. DUK_INTERNAL_DECL duk_bool_t duk_js_equals_helper(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y, duk_small_int_t flags);
  8547. DUK_INTERNAL_DECL duk_small_int_t duk_js_string_compare(duk_hstring *h1, duk_hstring *h2);
  8548. DUK_INTERNAL_DECL duk_bool_t duk_js_compare_helper(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y, duk_small_int_t flags);
  8549. DUK_INTERNAL_DECL duk_bool_t duk_js_instanceof(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y);
  8550. DUK_INTERNAL_DECL duk_bool_t duk_js_in(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y);
  8551. DUK_INTERNAL_DECL duk_hstring *duk_js_typeof(duk_hthread *thr, duk_tval *tv_x);
  8552. #define duk_js_equals(thr,tv_x,tv_y) \
  8553. duk_js_equals_helper((thr), (tv_x), (tv_y), 0)
  8554. #define duk_js_strict_equals(tv_x,tv_y) \
  8555. duk_js_equals_helper(NULL, (tv_x), (tv_y), DUK_EQUALS_FLAG_STRICT)
  8556. #define duk_js_samevalue(tv_x,tv_y) \
  8557. duk_js_equals_helper(NULL, (tv_x), (tv_y), DUK_EQUALS_FLAG_SAMEVALUE)
  8558. /* E5 Sections 11.8.1, 11.8.5; x < y */
  8559. #define duk_js_lessthan(thr,tv_x,tv_y) \
  8560. duk_js_compare_helper((thr), (tv_x), (tv_Y), DUK_COMPARE_FLAG_EVAL_LEFT_FIRST)
  8561. /* E5 Sections 11.8.2, 11.8.5; x > y --> y < x */
  8562. #define duk_js_greaterthan(thr,tv_x,tv_y) \
  8563. duk_js_compare_helper((thr), (tv_y), (tv_x), 0)
  8564. /* E5 Sections 11.8.3, 11.8.5; x <= y --> not (x > y) --> not (y < x) */
  8565. #define duk_js_lessthanorequal(thr,tv_x,tv_y) \
  8566. duk_js_compare_helper((thr), (tv_y), (tv_x), DUK_COMPARE_FLAG_NEGATE)
  8567. /* E5 Sections 11.8.4, 11.8.5; x >= y --> not (x < y) */
  8568. #define duk_js_greaterthanorequal(thr,tv_x,tv_y) \
  8569. duk_js_compare_helper((thr), (tv_x), (tv_y), DUK_COMPARE_FLAG_EVAL_LEFT_FIRST | DUK_COMPARE_FLAG_NEGATE)
  8570. /* identifiers and environment handling */
  8571. #if 0 /*unused*/
  8572. DUK_INTERNAL duk_bool_t duk_js_hasvar_envrec(duk_hthread *thr, duk_hobject *env, duk_hstring *name);
  8573. #endif
  8574. DUK_INTERNAL_DECL duk_bool_t duk_js_getvar_envrec(duk_hthread *thr, duk_hobject *env, duk_hstring *name, duk_bool_t throw_flag);
  8575. DUK_INTERNAL_DECL duk_bool_t duk_js_getvar_activation(duk_hthread *thr, duk_activation *act, duk_hstring *name, duk_bool_t throw_flag);
  8576. DUK_INTERNAL_DECL void duk_js_putvar_envrec(duk_hthread *thr, duk_hobject *env, duk_hstring *name, duk_tval *val, duk_bool_t strict);
  8577. DUK_INTERNAL_DECL void duk_js_putvar_activation(duk_hthread *thr, duk_activation *act, duk_hstring *name, duk_tval *val, duk_bool_t strict);
  8578. #if 0 /*unused*/
  8579. DUK_INTERNAL_DECL duk_bool_t duk_js_delvar_envrec(duk_hthread *thr, duk_hobject *env, duk_hstring *name);
  8580. #endif
  8581. DUK_INTERNAL_DECL duk_bool_t duk_js_delvar_activation(duk_hthread *thr, duk_activation *act, duk_hstring *name);
  8582. DUK_INTERNAL_DECL duk_bool_t duk_js_declvar_activation(duk_hthread *thr, duk_activation *act, duk_hstring *name, duk_tval *val, duk_small_int_t prop_flags, duk_bool_t is_func_decl);
  8583. DUK_INTERNAL_DECL void duk_js_init_activation_environment_records_delayed(duk_hthread *thr, duk_activation *act);
  8584. DUK_INTERNAL_DECL void duk_js_close_environment_record(duk_hthread *thr, duk_hobject *env, duk_hobject *func, duk_size_t regbase);
  8585. DUK_INTERNAL_DECL duk_hobject *duk_create_activation_environment_record(duk_hthread *thr, duk_hobject *func, duk_size_t idx_bottom);
  8586. DUK_INTERNAL_DECL
  8587. void duk_js_push_closure(duk_hthread *thr,
  8588. duk_hcompiledfunction *fun_temp,
  8589. duk_hobject *outer_var_env,
  8590. duk_hobject *outer_lex_env);
  8591. /* call handling */
  8592. DUK_INTERNAL_DECL duk_int_t duk_handle_call(duk_hthread *thr, duk_idx_t num_stack_args, duk_small_uint_t call_flags);
  8593. DUK_INTERNAL_DECL duk_int_t duk_handle_safe_call(duk_hthread *thr, duk_safe_call_function func, duk_idx_t num_stack_args, duk_idx_t num_stack_res);
  8594. DUK_INTERNAL_DECL duk_bool_t duk_handle_ecma_call_setup(duk_hthread *thr, duk_idx_t num_stack_args, duk_small_uint_t call_flags);
  8595. /* bytecode execution */
  8596. DUK_INTERNAL_DECL void duk_js_execute_bytecode(duk_hthread *exec_thr);
  8597. #endif /* DUK_JS_H_INCLUDED */
  8598. #line 1 "duk_numconv.h"
  8599. #ifndef DUK_NUMCONV_H_INCLUDED
  8600. #define DUK_NUMCONV_H_INCLUDED
  8601. /*
  8602. * Number-to-string conversion. The semantics of these is very tightly
  8603. * bound with the Ecmascript semantics required for call sites.
  8604. */
  8605. /* Output a specified number of digits instead of using the shortest
  8606. * form. Used for toPrecision() and toFixed().
  8607. */
  8608. #define DUK_N2S_FLAG_FIXED_FORMAT (1 << 0)
  8609. /* Force exponential format. Used for toExponential(). */
  8610. #define DUK_N2S_FLAG_FORCE_EXP (1 << 1)
  8611. /* If number would need zero padding (for whole number part), use
  8612. * exponential format instead. E.g. if input number is 12300, 3
  8613. * digits are generated ("123"), output "1.23e+4" instead of "12300".
  8614. * Used for toPrecision().
  8615. */
  8616. #define DUK_N2S_FLAG_NO_ZERO_PAD (1 << 2)
  8617. /* Digit count indicates number of fractions (i.e. an absolute
  8618. * digit index instead of a relative one). Used together with
  8619. * DUK_N2S_FLAG_FIXED_FORMAT for toFixed().
  8620. */
  8621. #define DUK_N2S_FLAG_FRACTION_DIGITS (1 << 3)
  8622. /*
  8623. * String-to-number conversion
  8624. */
  8625. /* Maximum exponent value when parsing numbers. This is not strictly
  8626. * compliant as there should be no upper limit, but as we parse the
  8627. * exponent without a bigint, impose some limit.
  8628. */
  8629. #define DUK_S2N_MAX_EXPONENT 1000000000
  8630. /* Trim white space (= allow leading and trailing whitespace) */
  8631. #define DUK_S2N_FLAG_TRIM_WHITE (1 << 0)
  8632. /* Allow exponent */
  8633. #define DUK_S2N_FLAG_ALLOW_EXP (1 << 1)
  8634. /* Allow trailing garbage (e.g. treat "123foo" as "123) */
  8635. #define DUK_S2N_FLAG_ALLOW_GARBAGE (1 << 2)
  8636. /* Allow leading plus sign */
  8637. #define DUK_S2N_FLAG_ALLOW_PLUS (1 << 3)
  8638. /* Allow leading minus sign */
  8639. #define DUK_S2N_FLAG_ALLOW_MINUS (1 << 4)
  8640. /* Allow 'Infinity' */
  8641. #define DUK_S2N_FLAG_ALLOW_INF (1 << 5)
  8642. /* Allow fraction part */
  8643. #define DUK_S2N_FLAG_ALLOW_FRAC (1 << 6)
  8644. /* Allow naked fraction (e.g. ".123") */
  8645. #define DUK_S2N_FLAG_ALLOW_NAKED_FRAC (1 << 7)
  8646. /* Allow empty fraction (e.g. "123.") */
  8647. #define DUK_S2N_FLAG_ALLOW_EMPTY_FRAC (1 << 8)
  8648. /* Allow empty string to be interpreted as 0 */
  8649. #define DUK_S2N_FLAG_ALLOW_EMPTY_AS_ZERO (1 << 9)
  8650. /* Allow leading zeroes (e.g. "0123" -> "123") */
  8651. #define DUK_S2N_FLAG_ALLOW_LEADING_ZERO (1 << 10)
  8652. /* Allow automatic detection of hex base ("0x" or "0X" prefix),
  8653. * overrides radix argument and forces integer mode.
  8654. */
  8655. #define DUK_S2N_FLAG_ALLOW_AUTO_HEX_INT (1 << 11)
  8656. /* Allow automatic detection of octal base, overrides radix
  8657. * argument and forces integer mode.
  8658. */
  8659. #define DUK_S2N_FLAG_ALLOW_AUTO_OCT_INT (1 << 12)
  8660. /*
  8661. * Prototypes
  8662. */
  8663. DUK_INTERNAL_DECL void duk_numconv_stringify(duk_context *ctx, duk_small_int_t radix, duk_small_int_t digits, duk_small_uint_t flags);
  8664. DUK_INTERNAL_DECL void duk_numconv_parse(duk_context *ctx, duk_small_int_t radix, duk_small_uint_t flags);
  8665. #endif /* DUK_NUMCONV_H_INCLUDED */
  8666. #line 1 "duk_bi_protos.h"
  8667. /*
  8668. * Prototypes for all built-in functions.
  8669. */
  8670. #ifndef DUK_BUILTIN_PROTOS_H_INCLUDED
  8671. #define DUK_BUILTIN_PROTOS_H_INCLUDED
  8672. /* Buffer size needed for duk_bi_date_format_timeval().
  8673. * Accurate value is 32 + 1 for NUL termination:
  8674. * >>> len('+123456-01-23T12:34:56.123+12:34')
  8675. * 32
  8676. * Include additional space to be safe.
  8677. */
  8678. #define DUK_BI_DATE_ISO8601_BUFSIZE 48
  8679. /* Buffer size for "short log message" which use a heap-level pre-allocated
  8680. * dynamic buffer to reduce memory churn.
  8681. */
  8682. #define DUK_BI_LOGGER_SHORT_MSG_LIMIT 256
  8683. /* Maximum length of CommonJS module identifier to resolve. Length includes
  8684. * both current module ID, requested (possibly relative) module ID, and a
  8685. * slash in between.
  8686. */
  8687. #define DUK_BI_COMMONJS_MODULE_ID_LIMIT 256
  8688. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_constructor(duk_context *ctx);
  8689. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_constructor_is_array(duk_context *ctx);
  8690. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_to_string(duk_context *ctx);
  8691. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_concat(duk_context *ctx);
  8692. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_join_shared(duk_context *ctx);
  8693. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_pop(duk_context *ctx);
  8694. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_push(duk_context *ctx);
  8695. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_reverse(duk_context *ctx);
  8696. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_shift(duk_context *ctx);
  8697. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_slice(duk_context *ctx);
  8698. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_sort(duk_context *ctx);
  8699. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_splice(duk_context *ctx);
  8700. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_unshift(duk_context *ctx);
  8701. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_indexof_shared(duk_context *ctx);
  8702. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_iter_shared(duk_context *ctx);
  8703. DUK_INTERNAL_DECL duk_ret_t duk_bi_array_prototype_reduce_shared(duk_context *ctx);
  8704. DUK_INTERNAL_DECL duk_ret_t duk_bi_boolean_constructor(duk_context *ctx);
  8705. DUK_INTERNAL_DECL duk_ret_t duk_bi_boolean_prototype_tostring_shared(duk_context *ctx);
  8706. DUK_INTERNAL_DECL duk_ret_t duk_bi_buffer_constructor(duk_context *ctx);
  8707. DUK_INTERNAL_DECL duk_ret_t duk_bi_buffer_prototype_tostring_shared(duk_context *ctx);
  8708. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_constructor(duk_context *ctx);
  8709. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_constructor_parse(duk_context *ctx);
  8710. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_constructor_utc(duk_context *ctx);
  8711. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_constructor_now(duk_context *ctx);
  8712. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_prototype_tostring_shared(duk_context *ctx);
  8713. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_prototype_value_of(duk_context *ctx);
  8714. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_prototype_to_json(duk_context *ctx);
  8715. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_prototype_get_shared(duk_context *ctx);
  8716. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_prototype_get_timezone_offset(duk_context *ctx);
  8717. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_prototype_set_shared(duk_context *ctx);
  8718. DUK_INTERNAL_DECL duk_ret_t duk_bi_date_prototype_set_time(duk_context *ctx);
  8719. /* Helpers exposed for internal use */
  8720. DUK_INTERNAL_DECL duk_double_t duk_bi_date_get_now(duk_context *ctx);
  8721. DUK_INTERNAL_DECL void duk_bi_date_format_timeval(duk_double_t timeval, duk_uint8_t *out_buf);
  8722. DUK_INTERNAL_DECL duk_ret_t duk_bi_duktape_object_info(duk_context *ctx);
  8723. DUK_INTERNAL_DECL duk_ret_t duk_bi_duktape_object_act(duk_context *ctx);
  8724. DUK_INTERNAL_DECL duk_ret_t duk_bi_duktape_object_gc(duk_context *ctx);
  8725. DUK_INTERNAL_DECL duk_ret_t duk_bi_duktape_object_fin(duk_context *ctx);
  8726. DUK_INTERNAL_DECL duk_ret_t duk_bi_duktape_object_enc(duk_context *ctx);
  8727. DUK_INTERNAL_DECL duk_ret_t duk_bi_duktape_object_dec(duk_context *ctx);
  8728. DUK_INTERNAL_DECL duk_ret_t duk_bi_duktape_object_compact(duk_context *ctx);
  8729. DUK_INTERNAL_DECL duk_ret_t duk_bi_error_constructor_shared(duk_context *ctx);
  8730. DUK_INTERNAL_DECL duk_ret_t duk_bi_error_prototype_to_string(duk_context *ctx);
  8731. DUK_INTERNAL_DECL duk_ret_t duk_bi_error_prototype_stack_getter(duk_context *ctx);
  8732. DUK_INTERNAL_DECL duk_ret_t duk_bi_error_prototype_filename_getter(duk_context *ctx);
  8733. DUK_INTERNAL_DECL duk_ret_t duk_bi_error_prototype_linenumber_getter(duk_context *ctx);
  8734. DUK_INTERNAL_DECL duk_ret_t duk_bi_error_prototype_nop_setter(duk_context *ctx);
  8735. DUK_INTERNAL_DECL duk_ret_t duk_bi_function_constructor(duk_context *ctx);
  8736. DUK_INTERNAL_DECL duk_ret_t duk_bi_function_prototype(duk_context *ctx);
  8737. DUK_INTERNAL_DECL duk_ret_t duk_bi_function_prototype_to_string(duk_context *ctx);
  8738. DUK_INTERNAL_DECL duk_ret_t duk_bi_function_prototype_apply(duk_context *ctx);
  8739. DUK_INTERNAL_DECL duk_ret_t duk_bi_function_prototype_call(duk_context *ctx);
  8740. DUK_INTERNAL_DECL duk_ret_t duk_bi_function_prototype_bind(duk_context *ctx);
  8741. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_eval(duk_context *ctx);
  8742. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_parse_int(duk_context *ctx);
  8743. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_parse_float(duk_context *ctx);
  8744. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_is_nan(duk_context *ctx);
  8745. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_is_finite(duk_context *ctx);
  8746. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_decode_uri(duk_context *ctx);
  8747. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_decode_uri_component(duk_context *ctx);
  8748. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_encode_uri(duk_context *ctx);
  8749. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_encode_uri_component(duk_context *ctx);
  8750. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_escape(duk_context *ctx);
  8751. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_unescape(duk_context *ctx);
  8752. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_print_helper(duk_context *ctx);
  8753. DUK_INTERNAL_DECL duk_ret_t duk_bi_global_object_require(duk_context *ctx);
  8754. DUK_INTERNAL_DECL
  8755. void duk_bi_json_parse_helper(duk_context *ctx,
  8756. duk_idx_t idx_value,
  8757. duk_idx_t idx_reviver,
  8758. duk_small_uint_t flags);
  8759. DUK_INTERNAL_DECL
  8760. void duk_bi_json_stringify_helper(duk_context *ctx,
  8761. duk_idx_t idx_value,
  8762. duk_idx_t idx_replacer,
  8763. duk_idx_t idx_space,
  8764. duk_small_uint_t flags);
  8765. DUK_INTERNAL_DECL duk_ret_t duk_bi_json_object_parse(duk_context *ctx);
  8766. DUK_INTERNAL_DECL duk_ret_t duk_bi_json_object_stringify(duk_context *ctx);
  8767. DUK_INTERNAL_DECL duk_ret_t duk_bi_math_object_onearg_shared(duk_context *ctx);
  8768. DUK_INTERNAL_DECL duk_ret_t duk_bi_math_object_twoarg_shared(duk_context *ctx);
  8769. DUK_INTERNAL_DECL duk_ret_t duk_bi_math_object_max(duk_context *ctx);
  8770. DUK_INTERNAL_DECL duk_ret_t duk_bi_math_object_min(duk_context *ctx);
  8771. DUK_INTERNAL_DECL duk_ret_t duk_bi_math_object_random(duk_context *ctx);
  8772. DUK_INTERNAL_DECL duk_ret_t duk_bi_number_constructor(duk_context *ctx);
  8773. DUK_INTERNAL_DECL duk_ret_t duk_bi_number_prototype_to_string(duk_context *ctx);
  8774. DUK_INTERNAL_DECL duk_ret_t duk_bi_number_prototype_to_locale_string(duk_context *ctx);
  8775. DUK_INTERNAL_DECL duk_ret_t duk_bi_number_prototype_value_of(duk_context *ctx);
  8776. DUK_INTERNAL_DECL duk_ret_t duk_bi_number_prototype_to_fixed(duk_context *ctx);
  8777. DUK_INTERNAL_DECL duk_ret_t duk_bi_number_prototype_to_exponential(duk_context *ctx);
  8778. DUK_INTERNAL_DECL duk_ret_t duk_bi_number_prototype_to_precision(duk_context *ctx);
  8779. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_getprototype_shared(duk_context *ctx);
  8780. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_setprototype_shared(duk_context *ctx);
  8781. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor(duk_context *ctx);
  8782. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_get_own_property_descriptor(duk_context *ctx);
  8783. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_create(duk_context *ctx);
  8784. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_define_property(duk_context *ctx);
  8785. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_define_properties(duk_context *ctx);
  8786. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_seal_freeze_shared(duk_context *ctx);
  8787. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_prevent_extensions(duk_context *ctx);
  8788. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_is_sealed_frozen_shared(duk_context *ctx);
  8789. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_is_extensible(duk_context *ctx);
  8790. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_constructor_keys_shared(duk_context *ctx);
  8791. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_prototype_to_string(duk_context *ctx);
  8792. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_prototype_to_locale_string(duk_context *ctx);
  8793. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_prototype_value_of(duk_context *ctx);
  8794. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_prototype_has_own_property(duk_context *ctx);
  8795. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_prototype_is_prototype_of(duk_context *ctx);
  8796. DUK_INTERNAL_DECL duk_ret_t duk_bi_object_prototype_property_is_enumerable(duk_context *ctx);
  8797. DUK_INTERNAL_DECL duk_ret_t duk_bi_pointer_constructor(duk_context *ctx);
  8798. DUK_INTERNAL_DECL duk_ret_t duk_bi_pointer_prototype_tostring_shared(duk_context *ctx);
  8799. DUK_INTERNAL_DECL duk_ret_t duk_bi_regexp_constructor(duk_context *ctx);
  8800. DUK_INTERNAL_DECL duk_ret_t duk_bi_regexp_prototype_exec(duk_context *ctx);
  8801. DUK_INTERNAL_DECL duk_ret_t duk_bi_regexp_prototype_test(duk_context *ctx);
  8802. DUK_INTERNAL_DECL duk_ret_t duk_bi_regexp_prototype_to_string(duk_context *ctx);
  8803. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_constructor(duk_context *ctx);
  8804. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_constructor_from_char_code(duk_context *ctx);
  8805. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_to_string(duk_context *ctx);
  8806. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_char_at(duk_context *ctx);
  8807. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_char_code_at(duk_context *ctx);
  8808. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_concat(duk_context *ctx);
  8809. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_indexof_shared(duk_context *ctx);
  8810. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_locale_compare(duk_context *ctx);
  8811. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_match(duk_context *ctx);
  8812. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_replace(duk_context *ctx);
  8813. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_search(duk_context *ctx);
  8814. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_slice(duk_context *ctx);
  8815. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_split(duk_context *ctx);
  8816. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_substring(duk_context *ctx);
  8817. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_caseconv_shared(duk_context *ctx);
  8818. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_trim(duk_context *ctx);
  8819. /* Note: present even if DUK_OPT_NO_SECTION_B given because genbuiltins.py
  8820. * will point to it.
  8821. */
  8822. DUK_INTERNAL_DECL duk_ret_t duk_bi_string_prototype_substr(duk_context *ctx);
  8823. DUK_INTERNAL_DECL duk_ret_t duk_bi_proxy_constructor(duk_context *ctx);
  8824. #if 0 /* unimplemented now */
  8825. DUK_INTERNAL_DECL duk_ret_t duk_bi_proxy_constructor_revocable(duk_context *ctx);
  8826. #endif
  8827. DUK_INTERNAL_DECL duk_ret_t duk_bi_thread_constructor(duk_context *ctx);
  8828. DUK_INTERNAL_DECL duk_ret_t duk_bi_thread_resume(duk_context *ctx);
  8829. DUK_INTERNAL_DECL duk_ret_t duk_bi_thread_yield(duk_context *ctx);
  8830. DUK_INTERNAL_DECL duk_ret_t duk_bi_thread_current(duk_context *ctx);
  8831. DUK_INTERNAL_DECL duk_ret_t duk_bi_logger_constructor(duk_context *ctx);
  8832. DUK_INTERNAL_DECL duk_ret_t duk_bi_logger_prototype_fmt(duk_context *ctx);
  8833. DUK_INTERNAL_DECL duk_ret_t duk_bi_logger_prototype_raw(duk_context *ctx);
  8834. DUK_INTERNAL_DECL duk_ret_t duk_bi_logger_prototype_log_shared(duk_context *ctx);
  8835. DUK_INTERNAL_DECL duk_ret_t duk_bi_type_error_thrower(duk_context *ctx);
  8836. #endif /* DUK_BUILTIN_PROTOS_H_INCLUDED */
  8837. #line 1 "duk_selftest.h"
  8838. /*
  8839. * Selftest code
  8840. */
  8841. #ifndef DUK_SELFTEST_H_INCLUDED
  8842. #define DUK_SELFTEST_H_INCLUDED
  8843. #if defined(DUK_USE_SELF_TESTS)
  8844. DUK_INTERNAL_DECL void duk_selftest_run_tests(void);
  8845. #endif
  8846. #endif /* DUK_SELFTEST_H_INCLUDED */
  8847. #line 76 "duk_internal.h"
  8848. #endif /* DUK_INTERNAL_H_INCLUDED */
  8849. #line 1 "duk_strings.c"
  8850. /*
  8851. * Shared error message strings
  8852. *
  8853. * To minimize code footprint, try to share error messages inside Duktape
  8854. * code.
  8855. */
  8856. /* include removed: duk_internal.h */
  8857. /* Mostly API and built-in method related */
  8858. DUK_INTERNAL const char *duk_str_internal_error = "internal error";
  8859. DUK_INTERNAL const char *duk_str_invalid_count = "invalid count";
  8860. DUK_INTERNAL const char *duk_str_invalid_call_args = "invalid call args";
  8861. DUK_INTERNAL const char *duk_str_not_constructable = "not constructable";
  8862. DUK_INTERNAL const char *duk_str_not_callable = "not callable";
  8863. DUK_INTERNAL const char *duk_str_not_extensible = "not extensible";
  8864. DUK_INTERNAL const char *duk_str_not_writable = "not writable";
  8865. DUK_INTERNAL const char *duk_str_not_configurable = "not configurable";
  8866. DUK_INTERNAL const char *duk_str_invalid_context = "invalid context";
  8867. DUK_INTERNAL const char *duk_str_invalid_index = "invalid index";
  8868. DUK_INTERNAL const char *duk_str_push_beyond_alloc_stack = "attempt to push beyond currently allocated stack";
  8869. DUK_INTERNAL const char *duk_str_not_undefined = "not undefined";
  8870. DUK_INTERNAL const char *duk_str_not_null = "not null";
  8871. DUK_INTERNAL const char *duk_str_not_boolean = "not boolean";
  8872. DUK_INTERNAL const char *duk_str_not_number = "not number";
  8873. DUK_INTERNAL const char *duk_str_not_string = "not string";
  8874. DUK_INTERNAL const char *duk_str_not_pointer = "not pointer";
  8875. DUK_INTERNAL const char *duk_str_not_buffer = "not buffer";
  8876. DUK_INTERNAL const char *duk_str_unexpected_type = "unexpected type";
  8877. DUK_INTERNAL const char *duk_str_not_thread = "not thread";
  8878. #if 0 /*unused*/
  8879. DUK_INTERNAL const char *duk_str_not_compiledfunction = "not compiledfunction";
  8880. #endif
  8881. DUK_INTERNAL const char *duk_str_not_nativefunction = "not nativefunction";
  8882. DUK_INTERNAL const char *duk_str_not_c_function = "not c function";
  8883. DUK_INTERNAL const char *duk_str_defaultvalue_coerce_failed = "[[DefaultValue]] coerce failed";
  8884. DUK_INTERNAL const char *duk_str_number_outside_range = "number outside range";
  8885. DUK_INTERNAL const char *duk_str_not_object_coercible = "not object coercible";
  8886. DUK_INTERNAL const char *duk_str_string_too_long = "string too long";
  8887. DUK_INTERNAL const char *duk_str_buffer_too_long = "buffer too long";
  8888. DUK_INTERNAL const char *duk_str_sprintf_too_long = "sprintf message too long";
  8889. DUK_INTERNAL const char *duk_str_object_alloc_failed = "object alloc failed";
  8890. DUK_INTERNAL const char *duk_str_thread_alloc_failed = "thread alloc failed";
  8891. DUK_INTERNAL const char *duk_str_func_alloc_failed = "func alloc failed";
  8892. DUK_INTERNAL const char *duk_str_buffer_alloc_failed = "buffer alloc failed";
  8893. DUK_INTERNAL const char *duk_str_pop_too_many = "attempt to pop too many entries";
  8894. DUK_INTERNAL const char *duk_str_buffer_not_dynamic = "buffer is not dynamic";
  8895. DUK_INTERNAL const char *duk_str_failed_to_extend_valstack = "failed to extend valstack";
  8896. DUK_INTERNAL const char *duk_str_base64_encode_failed = "base64 encode failed";
  8897. DUK_INTERNAL const char *duk_str_base64_decode_failed = "base64 decode failed";
  8898. DUK_INTERNAL const char *duk_str_hex_decode_failed = "hex decode failed";
  8899. DUK_INTERNAL const char *duk_str_no_sourcecode = "no sourcecode";
  8900. DUK_INTERNAL const char *duk_str_concat_result_too_long = "concat result too long";
  8901. DUK_INTERNAL const char *duk_str_unimplemented = "unimplemented";
  8902. DUK_INTERNAL const char *duk_str_array_length_over_2g = "array length over 2G";
  8903. /* JSON */
  8904. DUK_INTERNAL const char *duk_str_fmt_ptr = "%p";
  8905. DUK_INTERNAL const char *duk_str_fmt_invalid_json = "invalid json (at offset %ld)";
  8906. DUK_INTERNAL const char *duk_str_jsondec_reclimit = "json decode recursion limit";
  8907. DUK_INTERNAL const char *duk_str_jsonenc_reclimit = "json encode recursion limit";
  8908. DUK_INTERNAL const char *duk_str_cyclic_input = "cyclic input";
  8909. /* Object property access */
  8910. DUK_INTERNAL const char *duk_str_proxy_revoked = "proxy revoked";
  8911. DUK_INTERNAL const char *duk_str_object_resize_failed = "object resize failed";
  8912. DUK_INTERNAL const char *duk_str_invalid_base = "invalid base value";
  8913. DUK_INTERNAL const char *duk_str_strict_caller_read = "attempt to read strict 'caller'";
  8914. DUK_INTERNAL const char *duk_str_proxy_rejected = "proxy rejected";
  8915. DUK_INTERNAL const char *duk_str_invalid_array_length = "invalid array length";
  8916. DUK_INTERNAL const char *duk_str_array_length_write_failed = "array length write failed";
  8917. DUK_INTERNAL const char *duk_str_array_length_not_writable = "array length non-writable";
  8918. DUK_INTERNAL const char *duk_str_setter_undefined = "setter undefined";
  8919. DUK_INTERNAL const char *duk_str_redefine_virt_prop = "attempt to redefine virtual property";
  8920. DUK_INTERNAL const char *duk_str_invalid_descriptor = "invalid descriptor";
  8921. DUK_INTERNAL const char *duk_str_property_is_virtual = "property is virtual";
  8922. /* Compiler */
  8923. DUK_INTERNAL const char *duk_str_parse_error = "parse error";
  8924. DUK_INTERNAL const char *duk_str_duplicate_label = "duplicate label";
  8925. DUK_INTERNAL const char *duk_str_invalid_label = "invalid label";
  8926. DUK_INTERNAL const char *duk_str_invalid_array_literal = "invalid array literal";
  8927. DUK_INTERNAL const char *duk_str_invalid_object_literal = "invalid object literal";
  8928. DUK_INTERNAL const char *duk_str_invalid_var_declaration = "invalid variable declaration";
  8929. DUK_INTERNAL const char *duk_str_cannot_delete_identifier = "cannot delete identifier";
  8930. DUK_INTERNAL const char *duk_str_invalid_expression = "invalid expression";
  8931. DUK_INTERNAL const char *duk_str_invalid_lvalue = "invalid lvalue";
  8932. DUK_INTERNAL const char *duk_str_expected_identifier = "expected identifier";
  8933. DUK_INTERNAL const char *duk_str_empty_expr_not_allowed = "empty expression not allowed";
  8934. DUK_INTERNAL const char *duk_str_invalid_for = "invalid for statement";
  8935. DUK_INTERNAL const char *duk_str_invalid_switch = "invalid switch statement";
  8936. DUK_INTERNAL const char *duk_str_invalid_break_cont_label = "invalid break/continue label";
  8937. DUK_INTERNAL const char *duk_str_invalid_return = "invalid return";
  8938. DUK_INTERNAL const char *duk_str_invalid_try = "invalid try";
  8939. DUK_INTERNAL const char *duk_str_invalid_throw = "invalid throw";
  8940. DUK_INTERNAL const char *duk_str_with_in_strict_mode = "with in strict mode";
  8941. DUK_INTERNAL const char *duk_str_func_stmt_not_allowed = "function statement not allowed";
  8942. DUK_INTERNAL const char *duk_str_unterminated_stmt = "unterminated statement";
  8943. DUK_INTERNAL const char *duk_str_invalid_arg_name = "invalid argument name";
  8944. DUK_INTERNAL const char *duk_str_invalid_func_name = "invalid function name";
  8945. DUK_INTERNAL const char *duk_str_invalid_getset_name = "invalid getter/setter name";
  8946. DUK_INTERNAL const char *duk_str_func_name_required = "function name required";
  8947. /* Executor */
  8948. DUK_INTERNAL const char *duk_str_internal_error_exec_longjmp = "internal error in bytecode executor longjmp handler";
  8949. /* Regexp */
  8950. DUK_INTERNAL const char *duk_str_invalid_quantifier_no_atom = "quantifier without preceding atom";
  8951. DUK_INTERNAL const char *duk_str_invalid_quantifier_values = "quantifier values invalid (qmin > qmax)";
  8952. DUK_INTERNAL const char *duk_str_quantifier_too_many_copies = "quantifier expansion requires too many atom copies";
  8953. DUK_INTERNAL const char *duk_str_unexpected_closing_paren = "unexpected closing parenthesis";
  8954. DUK_INTERNAL const char *duk_str_unexpected_end_of_pattern = "unexpected end of pattern";
  8955. DUK_INTERNAL const char *duk_str_unexpected_regexp_token = "unexpected token in regexp";
  8956. DUK_INTERNAL const char *duk_str_invalid_regexp_flags = "invalid regexp flags";
  8957. DUK_INTERNAL const char *duk_str_invalid_backrefs = "invalid backreference(s)";
  8958. DUK_INTERNAL const char *duk_str_regexp_backtrack_failed = "regexp backtrack failed";
  8959. DUK_INTERNAL const char *duk_str_regexp_advance_failed = "regexp advance failed";
  8960. DUK_INTERNAL const char *duk_str_regexp_internal_error = "regexp internal error";
  8961. /* Limits */
  8962. DUK_INTERNAL const char *duk_str_valstack_limit = "valstack limit";
  8963. DUK_INTERNAL const char *duk_str_callstack_limit = "callstack limit";
  8964. DUK_INTERNAL const char *duk_str_catchstack_limit = "catchstack limit";
  8965. DUK_INTERNAL const char *duk_str_object_property_limit = "object property limit";
  8966. DUK_INTERNAL const char *duk_str_prototype_chain_limit = "prototype chain limit";
  8967. DUK_INTERNAL const char *duk_str_bound_chain_limit = "function call bound chain limit";
  8968. DUK_INTERNAL const char *duk_str_c_callstack_limit = "C call stack depth limit";
  8969. DUK_INTERNAL const char *duk_str_compiler_recursion_limit = "compiler recursion limit";
  8970. DUK_INTERNAL const char *duk_str_bytecode_limit = "bytecode limit";
  8971. DUK_INTERNAL const char *duk_str_reg_limit = "register limit";
  8972. DUK_INTERNAL const char *duk_str_temp_limit = "temp limit";
  8973. DUK_INTERNAL const char *duk_str_const_limit = "const limit";
  8974. DUK_INTERNAL const char *duk_str_func_limit = "function limit";
  8975. DUK_INTERNAL const char *duk_str_regexp_compiler_recursion_limit = "regexp compiler recursion limit";
  8976. DUK_INTERNAL const char *duk_str_regexp_executor_recursion_limit = "regexp executor recursion limit";
  8977. DUK_INTERNAL const char *duk_str_regexp_executor_step_limit = "regexp step limit";
  8978. /* Misc */
  8979. DUK_INTERNAL const char *duk_str_anon = "anon";
  8980. DUK_INTERNAL const char *duk_str_realloc_failed = "realloc failed";
  8981. #line 1 "duk_debug_macros.c"
  8982. /*
  8983. * Debugging macro calls.
  8984. */
  8985. /* include removed: duk_internal.h */
  8986. #ifdef DUK_USE_DEBUG
  8987. /*
  8988. * Debugging enabled
  8989. */
  8990. #include <stdio.h>
  8991. #include <stdlib.h>
  8992. #include <stdarg.h>
  8993. #define DUK__DEBUG_BUFSIZE DUK_USE_DEBUG_BUFSIZE
  8994. DUK_LOCAL char duk__debug_buf[DUK__DEBUG_BUFSIZE];
  8995. DUK_LOCAL const char *duk__get_level_string(duk_small_int_t level) {
  8996. switch ((int) level) {
  8997. case DUK_LEVEL_DEBUG:
  8998. return "D";
  8999. case DUK_LEVEL_DDEBUG:
  9000. return "DD";
  9001. case DUK_LEVEL_DDDEBUG:
  9002. return "DDD";
  9003. }
  9004. return "???";
  9005. }
  9006. #ifdef DUK_USE_DPRINT_COLORS
  9007. /* http://en.wikipedia.org/wiki/ANSI_escape_code */
  9008. #define DUK__TERM_REVERSE "\x1b[7m"
  9009. #define DUK__TERM_BRIGHT "\x1b[1m"
  9010. #define DUK__TERM_RESET "\x1b[0m"
  9011. #define DUK__TERM_BLUE "\x1b[34m"
  9012. #define DUK__TERM_RED "\x1b[31m"
  9013. DUK_LOCAL const char *duk__get_term_1(duk_small_int_t level) {
  9014. DUK_UNREF(level);
  9015. return (const char *) DUK__TERM_RED;
  9016. }
  9017. DUK_LOCAL const char *duk__get_term_2(duk_small_int_t level) {
  9018. switch ((int) level) {
  9019. case DUK_LEVEL_DEBUG:
  9020. return (const char *) (DUK__TERM_RESET DUK__TERM_BRIGHT);
  9021. case DUK_LEVEL_DDEBUG:
  9022. return (const char *) (DUK__TERM_RESET);
  9023. case DUK_LEVEL_DDDEBUG:
  9024. return (const char *) (DUK__TERM_RESET DUK__TERM_BLUE);
  9025. }
  9026. return (const char *) DUK__TERM_RESET;
  9027. }
  9028. DUK_LOCAL const char *duk__get_term_3(duk_small_int_t level) {
  9029. DUK_UNREF(level);
  9030. return (const char *) DUK__TERM_RESET;
  9031. }
  9032. #else
  9033. DUK_LOCAL const char *duk__get_term_1(duk_small_int_t level) {
  9034. DUK_UNREF(level);
  9035. return (const char *) "";
  9036. }
  9037. DUK_LOCAL const char *duk__get_term_2(duk_small_int_t level) {
  9038. DUK_UNREF(level);
  9039. return (const char *) "";
  9040. }
  9041. DUK_LOCAL const char *duk__get_term_3(duk_small_int_t level) {
  9042. DUK_UNREF(level);
  9043. return (const char *) "";
  9044. }
  9045. #endif /* DUK_USE_DPRINT_COLORS */
  9046. #ifdef DUK_USE_VARIADIC_MACROS
  9047. DUK_INTERNAL void duk_debug_log(duk_small_int_t level, const char *file, duk_int_t line, const char *func, const char *fmt, ...) {
  9048. va_list ap;
  9049. va_start(ap, fmt);
  9050. DUK_MEMZERO((void *) duk__debug_buf, (size_t) DUK__DEBUG_BUFSIZE);
  9051. duk_debug_vsnprintf(duk__debug_buf, DUK__DEBUG_BUFSIZE - 1, fmt, ap);
  9052. #ifdef DUK_USE_DPRINT_RDTSC
  9053. DUK_FPRINTF(DUK_STDERR, "%s[%s] <%llu> %s:%ld (%s):%s %s%s\n",
  9054. (const char *) duk__get_term_1(level),
  9055. (const char *) duk__get_level_string(level),
  9056. (unsigned long long) duk_rdtsc(), /* match the inline asm in duk_features.h */
  9057. (const char *) file,
  9058. (long) line,
  9059. (const char *) func,
  9060. (const char *) duk__get_term_2(level),
  9061. (const char *) duk__debug_buf,
  9062. (const char *) duk__get_term_3(level));
  9063. #else
  9064. DUK_FPRINTF(DUK_STDERR, "%s[%s] %s:%ld (%s):%s %s%s\n",
  9065. (const char *) duk__get_term_1(level),
  9066. (const char *) duk__get_level_string(level),
  9067. (const char *) file,
  9068. (long) line,
  9069. (const char *) func,
  9070. (const char *) duk__get_term_2(level),
  9071. (const char *) duk__debug_buf,
  9072. (const char *) duk__get_term_3(level));
  9073. #endif
  9074. DUK_FFLUSH(DUK_STDERR);
  9075. va_end(ap);
  9076. }
  9077. #else /* DUK_USE_VARIADIC_MACROS */
  9078. DUK_INTERNAL char duk_debug_file_stash[DUK_DEBUG_STASH_SIZE];
  9079. DUK_INTERNAL char duk_debug_line_stash[DUK_DEBUG_STASH_SIZE];
  9080. DUK_INTERNAL char duk_debug_func_stash[DUK_DEBUG_STASH_SIZE];
  9081. DUK_INTERNAL duk_small_int_t duk_debug_level_stash;
  9082. DUK_INTERNAL void duk_debug_log(const char *fmt, ...) {
  9083. va_list ap;
  9084. duk_small_int_t level = duk_debug_level_stash;
  9085. va_start(ap, fmt);
  9086. DUK_MEMZERO((void *) duk__debug_buf, (size_t) DUK__DEBUG_BUFSIZE);
  9087. duk_debug_vsnprintf(duk__debug_buf, DUK__DEBUG_BUFSIZE - 1, fmt, ap);
  9088. #ifdef DUK_USE_DPRINT_RDTSC
  9089. DUK_FPRINTF(DUK_STDERR, "%s[%s] <%llu> %s:%s (%s):%s %s%s\n",
  9090. (const char *) duk__get_term_1(level),
  9091. (const char *) duk__get_level_string(duk_debug_level_stash),
  9092. (unsigned long long) duk_rdtsc(), /* match duk_features.h */
  9093. (const char *) duk_debug_file_stash,
  9094. (const char *) duk_debug_line_stash,
  9095. (const char *) duk_debug_func_stash,
  9096. (const char *) duk__get_term_2(level),
  9097. (const char *) duk__debug_buf,
  9098. (const char *) duk__get_term_3(level));
  9099. #else
  9100. DUK_FPRINTF(DUK_STDERR, "%s[%s] %s:%s (%s):%s %s%s\n",
  9101. (const char *) duk__get_term_1(level),
  9102. (const char *) duk__get_level_string(duk_debug_level_stash),
  9103. (const char *) duk_debug_file_stash,
  9104. (const char *) duk_debug_line_stash,
  9105. (const char *) duk_debug_func_stash,
  9106. (const char *) duk__get_term_2(level),
  9107. (const char *) duk__debug_buf,
  9108. (const char *) duk__get_term_3(level));
  9109. #endif
  9110. DUK_FFLUSH(DUK_STDERR);
  9111. va_end(ap);
  9112. }
  9113. #endif /* DUK_USE_VARIADIC_MACROS */
  9114. #else /* DUK_USE_DEBUG */
  9115. /*
  9116. * Debugging disabled
  9117. */
  9118. #endif /* DUK_USE_DEBUG */
  9119. #line 1 "duk_builtins.c"
  9120. /*
  9121. * Automatically generated by genbuiltins.py, do not edit!
  9122. */
  9123. /* include removed: duk_internal.h */
  9124. #if defined(DUK_USE_DOUBLE_LE)
  9125. DUK_INTERNAL const duk_uint8_t duk_strings_data[1943] = {
  9126. 55,86,227,24,145,55,102,120,144,3,63,94,228,54,100,137,186,26,20,164,137,
  9127. 186,50,11,164,109,77,215,5,61,35,106,3,25,110,8,22,158,130,38,163,8,217,
  9128. 200,158,76,156,210,117,128,153,203,210,70,46,137,187,18,27,164,187,201,209,
  9129. 130,100,55,91,70,4,145,63,66,231,44,128,105,187,41,197,13,49,122,8,196,24,
  9130. 71,75,70,138,104,115,77,215,5,36,20,201,214,209,107,79,104,209,144,168,105,
  9131. 6,207,251,209,104,209,125,212,227,66,127,235,191,239,232,180,90,52,95,69,
  9132. 247,83,141,9,255,174,255,191,162,211,80,210,253,23,221,78,52,39,254,183,
  9133. 254,254,139,72,105,126,139,238,167,26,19,255,91,255,127,69,166,129,191,69,
  9134. 247,83,141,9,255,175,255,191,162,213,26,50,23,232,190,234,113,161,63,245,
  9135. 115,119,86,227,118,83,138,26,98,9,110,48,86,22,148,160,152,22,82,70,46,137,
  9136. 44,8,180,163,32,104,98,206,32,17,7,16,88,101,100,206,42,70,36,108,205,18,
  9137. 74,140,33,196,230,60,2,152,146,33,38,230,8,36,79,182,251,65,156,151,24,200,
  9138. 33,145,162,25,80,209,24,67,0,166,68,52,174,61,73,25,33,205,25,27,84,177,
  9139. 195,234,220,1,144,105,99,135,217,16,17,17,208,72,199,179,60,93,100,146,49,
  9140. 232,162,64,76,135,19,152,244,44,136,223,98,67,4,18,33,247,217,158,36,0,209,
  9141. 190,156,13,26,201,21,111,165,67,64,180,100,145,62,250,32,45,100,33,55,214,
  9142. 1,229,223,65,19,72,187,236,206,137,35,125,120,190,201,104,105,15,190,201,
  9143. 212,136,136,125,246,160,137,27,83,239,171,37,200,218,159,125,168,34,192,61,
  9144. 27,233,93,22,1,114,78,250,28,76,130,112,200,93,245,164,188,207,190,204,17,
  9145. 49,38,109,246,160,93,8,119,185,13,153,34,96,208,165,36,85,190,206,32,17,6,
  9146. 9,129,75,67,73,214,209,129,36,80,84,44,157,104,24,65,60,69,148,192,37,59,
  9147. 179,60,93,110,207,15,39,73,24,186,39,232,232,169,129,228,18,6,120,146,20,
  9148. 68,72,157,105,241,116,221,173,58,68,159,95,23,77,211,195,201,215,20,238,
  9149. 179,122,162,98,73,35,104,194,68,19,35,134,69,146,100,235,226,231,146,51,
  9150. 192,206,9,23,175,139,175,131,8,11,89,8,206,161,181,2,208,63,160,232,193,50,
  9151. 23,246,254,187,235,190,187,247,69,241,95,18,31,160,15,214,11,235,126,192,
  9152. 95,87,246,1,251,4,253,111,80,210,161,168,158,19,245,125,67,74,134,162,120,
  9153. 71,80,210,161,168,158,12,224,164,130,153,165,56,161,166,51,104,192,146,39,
  9154. 11,156,178,1,169,163,70,66,161,164,26,101,56,161,166,65,112,57,129,164,148,
  9155. 35,49,201,13,44,93,70,140,209,3,70,230,13,238,176,216,134,141,128,184,214,
  9156. 227,20,171,115,162,50,93,227,19,164,65,17,11,40,38,6,253,145,1,48,52,128,
  9157. 146,26,64,9,210,24,3,34,250,80,140,254,200,254,148,35,63,177,215,217,11,
  9158. 207,65,188,183,27,236,126,192,133,242,220,111,178,32,252,182,253,145,60,
  9159. 182,253,143,216,7,164,59,9,41,0,196,35,64,194,21,13,125,38,84,52,100,185,
  9160. 62,163,239,254,235,234,82,176,74,125,67,70,75,165,148,92,208,180,52,138,65,
  9161. 154,232,147,162,4,136,105,58,145,17,9,50,74,100,37,200,37,205,222,51,39,47,
  9162. 78,40,105,143,34,79,184,32,34,115,18,125,193,1,19,77,222,76,156,213,205,
  9163. 222,68,157,47,78,40,105,151,55,122,147,20,189,56,161,166,116,137,63,82,98,
  9164. 47,168,181,247,4,4,87,34,79,165,162,215,220,16,17,92,137,63,82,98,103,156,
  9165. 217,157,18,36,250,199,54,103,84,137,63,82,98,31,129,50,30,68,159,70,9,145,
  9166. 114,36,253,73,136,254,117,35,36,72,147,233,221,72,201,178,36,253,73,137,
  9167. 158,67,105,50,73,82,36,250,196,54,147,36,155,34,79,212,152,165,226,9,205,
  9168. 28,149,34,79,178,32,156,209,202,82,36,253,73,137,158,66,214,137,16,78,104,
  9169. 228,249,18,125,98,22,180,72,130,115,71,35,200,147,236,208,194,68,196,159,
  9170. 102,134,19,46,105,58,226,150,68,156,140,73,250,147,19,60,133,173,18,32,156,
  9171. 209,201,230,36,250,196,45,104,145,4,230,142,77,49,39,234,76,82,241,4,230,
  9172. 142,74,49,39,217,16,78,104,228,211,18,126,164,196,207,33,180,153,36,163,18,
  9173. 125,98,27,73,146,75,49,39,234,76,71,243,169,25,32,196,159,78,234,70,73,49,
  9174. 39,234,76,67,240,48,99,18,125,24,48,163,18,126,164,196,63,2,100,57,137,62,
  9175. 140,19,34,204,73,250,147,19,60,230,204,232,49,39,214,57,179,59,140,73,250,
  9176. 147,17,125,69,175,184,32,34,179,18,125,45,22,190,224,128,137,204,73,246,
  9177. 104,97,37,55,117,110,16,22,78,205,12,39,101,56,161,166,148,221,213,184,64,
  9178. 89,58,48,76,157,148,226,134,153,147,119,102,134,19,178,156,80,211,50,110,
  9179. 232,193,50,118,83,138,26,97,181,214,31,169,49,21,224,140,136,185,187,175,
  9180. 137,4,137,33,205,108,221,210,93,238,105,27,52,1,103,155,186,84,92,131,143,
  9181. 158,233,34,104,169,52,134,149,13,68,241,31,52,134,4,209,82,105,13,42,26,
  9182. 137,224,125,104,58,212,249,136,110,170,5,208,137,243,1,125,84,11,161,13,42,
  9183. 6,83,137,39,20,50,51,119,86,225,1,100,237,30,242,71,162,4,136,185,187,180,
  9184. 123,201,30,136,18,36,102,238,173,194,2,201,213,186,196,143,68,9,17,115,119,
  9185. 86,235,18,61,16,36,68,202,129,148,226,134,152,178,122,209,51,72,128,136,
  9186. 142,120,145,235,0,136,86,2,98,59,86,225,1,100,232,156,199,130,36,80,142,8,
  9187. 244,78,25,58,9,152,71,4,122,9,176,177,115,58,35,130,61,19,134,69,196,131,
  9188. 160,137,216,160,199,153,162,65,208,68,49,80,185,146,35,96,30,114,186,61,32,
  9189. 4,114,73,204,33,73,82,71,11,88,37,62,161,163,37,250,226,157,13,25,47,215,
  9190. 20,244,108,142,130,204,210,122,208,34,18,78,140,203,37,160,68,44,142,130,
  9191. 204,241,37,73,25,16,143,164,142,55,185,228,75,144,211,9,205,16,38,116,75,
  9192. 160,140,65,132,130,38,163,8,217,200,194,2,214,72,144,40,104,200,32,45,101,
  9193. 3,222,188,81,241,115,201,25,227,168,151,72,218,48,145,0,86,70,162,93,124,
  9194. 93,55,79,15,39,92,87,28,18,235,172,222,190,46,121,35,60,30,160,93,9,215,21,
  9195. 211,119,86,225,1,100,236,167,20,52,200,155,187,41,197,13,50,196,230,202,
  9196. 113,160,166,232,142,68,152,204,73,168,141,163,9,16,5,100,96,156,210,160,
  9197. 212,136,2,178,34,209,68,192,21,144,181,2,232,66,40,152,147,17,46,146,243,
  9198. 35,100,128,172,136,68,186,88,187,36,106,17,46,200,128,89,7,23,196,149,35,
  9199. 103,210,94,100,108,144,230,200,197,137,9,146,18,68,2,224,50,21,13,39,95,23,
  9200. 60,145,154,9,39,12,133,67,73,215,197,207,36,103,131,10,36,4,201,51,18,125,
  9201. 117,155,215,197,207,36,103,142,180,12,36,176,98,79,174,179,122,248,185,228,
  9202. 140,241,209,146,66,138,31,55,69,198,36,250,248,186,110,158,30,78,184,169,
  9203. 124,93,55,79,15,33,150,70,154,103,40,22,72,204,175,138,27,52,81,164,144,
  9204. 128,242,24,146,16,30,73,17,162,112,201,234,69,2,243,152,247,52,141,154,72,
  9205. 209,56,100,245,34,137,12,130,112,201,234,69,2,243,152,247,52,141,154,70,65,
  9206. 56,100,245,34,132,34,93,42,26,137,144,168,151,90,14,181,79,4,100,78,149,
  9207. 110,4,208,240,70,68,234,27,50,18,160,90,61,72,160,158,140,93,20,246,120,
  9208. 121,58,72,197,209,95,101,134,204,23,233,35,23,69,221,137,10,72,145,162,39,
  9209. 73,24,186,42,236,64,211,19,164,140,93,20,244,149,2,250,72,197,209,40,98,64,
  9210. 40,130,4,136,81,2,98,58,4,230,205,13,161,16,50,6,134,49,34,113,144,160,162,
  9211. 230,97,145,100,153,4,55,16,139,145,14,84,52,11,94,6,87,69,5,163,69,52,57,
  9212. 162,65,68,134,169,13,148,192,209,17,197,27,73,99,68,147,164,90,105,89,19,
  9213. 17,201,51,162,69,153,226,235,14,113,193,167,135,145,197,29,65,18,85,200,25,
  9214. 108,116,44,132,178,38,114,137,96,148,138,39,54,83,33,27,70,24,151,123,163,
  9215. 51,146,243,35,71,35,33,143,116,102,89,81,228,137,27,69,172,147,141,8,82,
  9216. 129,114,34,144,199,172,140,35,103,36,161,179,36,74,1,16,107,36,206,240,9,
  9217. 64,49,14,248,162,160,153,18,248,186,100,20,200,51,62,129,90,4,105,76,19,64,
  9218. 139,132,17,99,
  9219. };
  9220. /* to convert a heap stridx to a token number, subtract
  9221. * DUK_STRIDX_START_RESERVED and add DUK_TOK_START_RESERVED.
  9222. */
  9223. /* native functions: 128 */
  9224. DUK_INTERNAL const duk_c_function duk_bi_native_functions[128] = {
  9225. duk_bi_array_constructor,
  9226. duk_bi_array_constructor_is_array,
  9227. duk_bi_array_prototype_concat,
  9228. duk_bi_array_prototype_indexof_shared,
  9229. duk_bi_array_prototype_iter_shared,
  9230. duk_bi_array_prototype_join_shared,
  9231. duk_bi_array_prototype_pop,
  9232. duk_bi_array_prototype_push,
  9233. duk_bi_array_prototype_reduce_shared,
  9234. duk_bi_array_prototype_reverse,
  9235. duk_bi_array_prototype_shift,
  9236. duk_bi_array_prototype_slice,
  9237. duk_bi_array_prototype_sort,
  9238. duk_bi_array_prototype_splice,
  9239. duk_bi_array_prototype_to_string,
  9240. duk_bi_array_prototype_unshift,
  9241. duk_bi_boolean_constructor,
  9242. duk_bi_boolean_prototype_tostring_shared,
  9243. duk_bi_buffer_constructor,
  9244. duk_bi_buffer_prototype_tostring_shared,
  9245. duk_bi_date_constructor,
  9246. duk_bi_date_constructor_now,
  9247. duk_bi_date_constructor_parse,
  9248. duk_bi_date_constructor_utc,
  9249. duk_bi_date_prototype_get_shared,
  9250. duk_bi_date_prototype_get_timezone_offset,
  9251. duk_bi_date_prototype_set_shared,
  9252. duk_bi_date_prototype_set_time,
  9253. duk_bi_date_prototype_to_json,
  9254. duk_bi_date_prototype_tostring_shared,
  9255. duk_bi_date_prototype_value_of,
  9256. duk_bi_duktape_object_act,
  9257. duk_bi_duktape_object_compact,
  9258. duk_bi_duktape_object_dec,
  9259. duk_bi_duktape_object_enc,
  9260. duk_bi_duktape_object_fin,
  9261. duk_bi_duktape_object_gc,
  9262. duk_bi_duktape_object_info,
  9263. duk_bi_error_constructor_shared,
  9264. duk_bi_error_prototype_filename_getter,
  9265. duk_bi_error_prototype_linenumber_getter,
  9266. duk_bi_error_prototype_nop_setter,
  9267. duk_bi_error_prototype_stack_getter,
  9268. duk_bi_error_prototype_to_string,
  9269. duk_bi_function_constructor,
  9270. duk_bi_function_prototype,
  9271. duk_bi_function_prototype_apply,
  9272. duk_bi_function_prototype_bind,
  9273. duk_bi_function_prototype_call,
  9274. duk_bi_function_prototype_to_string,
  9275. duk_bi_global_object_decode_uri,
  9276. duk_bi_global_object_decode_uri_component,
  9277. duk_bi_global_object_encode_uri,
  9278. duk_bi_global_object_encode_uri_component,
  9279. duk_bi_global_object_escape,
  9280. duk_bi_global_object_eval,
  9281. duk_bi_global_object_is_finite,
  9282. duk_bi_global_object_is_nan,
  9283. duk_bi_global_object_parse_float,
  9284. duk_bi_global_object_parse_int,
  9285. duk_bi_global_object_print_helper,
  9286. duk_bi_global_object_require,
  9287. duk_bi_global_object_unescape,
  9288. duk_bi_json_object_parse,
  9289. duk_bi_json_object_stringify,
  9290. duk_bi_logger_constructor,
  9291. duk_bi_logger_prototype_fmt,
  9292. duk_bi_logger_prototype_log_shared,
  9293. duk_bi_logger_prototype_raw,
  9294. duk_bi_math_object_max,
  9295. duk_bi_math_object_min,
  9296. duk_bi_math_object_onearg_shared,
  9297. duk_bi_math_object_random,
  9298. duk_bi_math_object_twoarg_shared,
  9299. duk_bi_number_constructor,
  9300. duk_bi_number_prototype_to_exponential,
  9301. duk_bi_number_prototype_to_fixed,
  9302. duk_bi_number_prototype_to_locale_string,
  9303. duk_bi_number_prototype_to_precision,
  9304. duk_bi_number_prototype_to_string,
  9305. duk_bi_number_prototype_value_of,
  9306. duk_bi_object_constructor,
  9307. duk_bi_object_constructor_create,
  9308. duk_bi_object_constructor_define_properties,
  9309. duk_bi_object_constructor_define_property,
  9310. duk_bi_object_constructor_get_own_property_descriptor,
  9311. duk_bi_object_constructor_is_extensible,
  9312. duk_bi_object_constructor_is_sealed_frozen_shared,
  9313. duk_bi_object_constructor_keys_shared,
  9314. duk_bi_object_constructor_prevent_extensions,
  9315. duk_bi_object_constructor_seal_freeze_shared,
  9316. duk_bi_object_getprototype_shared,
  9317. duk_bi_object_prototype_has_own_property,
  9318. duk_bi_object_prototype_is_prototype_of,
  9319. duk_bi_object_prototype_property_is_enumerable,
  9320. duk_bi_object_prototype_to_locale_string,
  9321. duk_bi_object_prototype_to_string,
  9322. duk_bi_object_prototype_value_of,
  9323. duk_bi_object_setprototype_shared,
  9324. duk_bi_pointer_constructor,
  9325. duk_bi_pointer_prototype_tostring_shared,
  9326. duk_bi_proxy_constructor,
  9327. duk_bi_regexp_constructor,
  9328. duk_bi_regexp_prototype_exec,
  9329. duk_bi_regexp_prototype_test,
  9330. duk_bi_regexp_prototype_to_string,
  9331. duk_bi_string_constructor,
  9332. duk_bi_string_constructor_from_char_code,
  9333. duk_bi_string_prototype_caseconv_shared,
  9334. duk_bi_string_prototype_char_at,
  9335. duk_bi_string_prototype_char_code_at,
  9336. duk_bi_string_prototype_concat,
  9337. duk_bi_string_prototype_indexof_shared,
  9338. duk_bi_string_prototype_locale_compare,
  9339. duk_bi_string_prototype_match,
  9340. duk_bi_string_prototype_replace,
  9341. duk_bi_string_prototype_search,
  9342. duk_bi_string_prototype_slice,
  9343. duk_bi_string_prototype_split,
  9344. duk_bi_string_prototype_substr,
  9345. duk_bi_string_prototype_substring,
  9346. duk_bi_string_prototype_to_string,
  9347. duk_bi_string_prototype_trim,
  9348. duk_bi_thread_constructor,
  9349. duk_bi_thread_current,
  9350. duk_bi_thread_resume,
  9351. duk_bi_thread_yield,
  9352. duk_bi_type_error_thrower,
  9353. };
  9354. DUK_INTERNAL const duk_uint8_t duk_builtins_data[1341] = {
  9355. 105,195,74,136,77,40,105,44,9,124,104,45,3,3,72,0,71,225,65,165,168,33,243,
  9356. 6,145,0,122,24,210,148,14,249,35,120,160,55,226,13,76,192,196,177,164,152,
  9357. 22,192,4,202,52,147,72,152,0,169,70,146,105,11,0,23,40,210,77,32,96,3,37,
  9358. 26,73,163,236,0,108,163,73,52,121,128,14,148,105,38,142,176,1,242,144,56,
  9359. 208,254,84,6,166,82,242,80,210,246,1,250,67,72,144,15,232,13,44,96,47,162,
  9360. 52,160,128,62,80,160,255,253,102,76,0,0,0,0,0,0,15,135,243,84,0,0,0,0,0,0,
  9361. 15,7,243,124,64,153,132,18,49,2,38,48,64,200,7,153,64,227,48,26,103,3,13,0,
  9362. 89,165,34,53,36,38,180,128,216,143,155,81,227,114,58,111,2,142,0,73,194,94,
  9363. 56,202,167,33,209,195,114,70,206,209,26,58,36,100,228,145,131,130,69,204,
  9364. 137,22,51,36,84,208,145,67,82,68,205,137,18,62,36,68,240,122,32,120,62,0,2,
  9365. 87,61,39,255,254,9,46,24,0,10,31,224,29,13,91,40,0,9,101,137,32,0,48,197,
  9366. 84,66,214,9,10,82,68,37,81,144,133,52,65,214,137,6,90,40,0,12,21,100,144,
  9367. 69,114,64,213,202,0,3,2,86,36,5,96,160,0,63,254,16,37,135,91,98,25,242,192,
  9368. 7,194,248,30,236,32,123,46,17,234,186,71,162,241,5,23,240,0,15,241,1,70,74,
  9369. 3,8,249,49,3,204,185,15,35,3,231,137,121,240,163,254,0,46,224,18,7,248,192,
  9370. 42,249,14,3,224,20,32,0,46,208,35,231,96,41,29,96,192,117,3,159,58,66,64,
  9371. 232,10,3,156,45,14,96,194,57,67,87,156,129,231,206,48,51,240,0,23,16,25,
  9372. 255,255,251,132,16,209,192,8,106,0,2,223,4,53,0,2,111,2,26,128,1,183,65,13,
  9373. 64,1,27,129,7,224,0,45,176,131,255,255,241,73,252,0,91,77,103,193,254,64,
  9374. 36,200,64,101,31,47,32,123,188,129,178,218,70,195,113,29,173,231,206,55,3,
  9375. 71,19,129,168,0,11,93,196,141,103,34,53,92,208,212,116,35,157,213,13,55,
  9376. 100,52,158,16,209,108,3,65,176,12,246,192,128,0,179,155,2,0,2,205,122,3,49,
  9377. 221,2,151,248,0,7,249,64,147,35,4,249,17,8,0,11,220,68,2,155,248,172,184,
  9378. 31,255,255,255,255,255,253,239,236,168,0,32,0,0,0,0,0,0,12,152,0,0,0,0,0,0,
  9379. 31,15,236,120,0,0,0,0,0,0,30,15,236,136,0,0,0,0,0,0,30,31,224,7,249,128,
  9380. 147,32,0,0,0,0,0,0,0,0,12,249,79,35,225,52,143,117,0,49,147,8,197,75,35,17,
  9381. 56,130,159,248,1,176,197,136,194,23,254,96,138,128,63,206,4,153,32,0,0,0,0,
  9382. 0,3,225,254,215,200,232,24,3,161,0,1,95,142,132,0,9,240,58,16,0,53,240,232,
  9383. 64,1,23,163,161,0,5,77,142,132,0,25,52,58,16,0,116,200,225,30,227,192,94,
  9384. 15,1,118,48,16,0,133,208,192,64,2,87,35,1,0,10,92,12,4,0,45,110,48,16,0,
  9385. 197,176,192,64,3,86,163,1,0,14,90,12,4,0,61,102,48,16,1,5,144,192,64,4,86,
  9386. 35,1,0,18,88,12,4,0,77,94,48,16,1,69,112,192,64,5,85,163,1,0,22,86,12,4,0,
  9387. 93,86,50,5,80,217,21,35,69,0,24,84,13,20,0,101,78,52,190,0,52,166,26,95,0,
  9388. 27,82,141,63,128,14,41,6,159,192,7,84,99,83,224,3,202,33,169,240,1,245,8,
  9389. 209,64,8,20,3,69,0,33,79,141,47,128,17,39,134,151,192,8,211,163,79,224,4,
  9390. 137,193,167,240,2,84,192,192,64,9,146,227,69,0,39,21,31,192,0,63,208,24,
  9391. 147,4,12,0,32,41,56,72,240,60,100,148,100,140,100,132,128,0,0,0,0,0,0,0,0,
  9392. 210,172,228,74,52,17,242,210,1,83,252,0,3,253,33,81,132,11,69,144,24,166,
  9393. 229,69,37,23,39,41,40,57,65,72,47,146,176,10,175,224,0,159,234,4,140,41,18,
  9394. 44,128,192,10,191,224,0,159,235,4,140,41,10,44,128,192,10,207,224,0,159,
  9395. 236,4,140,41,2,44,128,192,10,223,224,0,159,237,4,140,40,250,44,128,192,10,
  9396. 239,224,0,159,238,4,140,40,242,44,128,192,10,255,224,0,159,239,4,140,40,
  9397. 234,44,128,192,7,255,228,34,160,52,171,138,69,133,95,130,160,34,96,11,42,
  9398. 218,221,216,181,129,32,34,32,119,156,253,127,33,23,115,31,161,224,127,65,
  9399. 21,178,163,138,251,159,161,160,7,114,147,10,189,229,237,159,161,96,12,22,
  9400. 162,42,125,144,132,160,33,32,102,157,191,179,79,80,115,31,160,224,102,157,
  9401. 191,179,79,80,123,31,164,130,71,34,5,28,160,0,40,4,114,128,1,31,209,202,0,
  9402. 6,126,73,65,245,28,160,0,135,196,114,128,2,158,209,202,0,12,122,71,40,0,57,
  9403. 229,28,160,1,7,132,85,227,186,50,241,217,37,32,0,39,84,128,29,17,202,0,18,
  9404. 115,71,40,0,81,201,28,160,1,103,20,114,128,6,7,255,224,4,195,63,65,193,1,
  9405. 130,255,248,0,11,255,224,0,31,255,138,52,128,0,0,0,0,1,219,134,128,3,57,
  9406. 192,71,72,4,229,0,29,99,140,201,72,50,31,32,196,144,131,2,49,225,121,16,
  9407. 240,184,132,120,82,64,65,102,252,0,233,239,200,20,62,176,78,248,0,255,148,
  9408. 0,5,163,240,0,15,249,192,9,242,38,16,0,23,184,152,5,171,240,0,15,250,64,9,
  9409. 242,200,16,0,23,187,32,5,179,240,0,15,250,194,15,72,0,0,0,0,0,0,0,64,15,
  9410. 201,4,195,187,126,226,4,200,68,18,162,16,72,134,60,35,67,31,0,1,25,161,143,
  9411. 128,1,8,144,199,192,0,196,40,99,224,0,130,4,49,240,0,84,255,252,36,100,16,
  9412. 184,155,250,226,217,150,47,46,91,249,34,224,139,229,229,203,127,36,26,119,
  9413. 32,203,203,150,254,72,52,97,221,147,102,157,217,192,
  9414. };
  9415. #ifdef DUK_USE_BUILTIN_INITJS
  9416. DUK_INTERNAL const duk_uint8_t duk_initjs_data[187] = {
  9417. 40,102,117,110,99,116,105,111,110,40,100,44,97,41,123,102,117,110,99,116,
  9418. 105,111,110,32,98,40,97,44,98,44,99,41,123,79,98,106,101,99,116,46,100,101,
  9419. 102,105,110,101,80,114,111,112,101,114,116,121,40,97,44,98,44,123,118,97,
  9420. 108,117,101,58,99,44,119,114,105,116,97,98,108,101,58,33,48,44,101,110,117,
  9421. 109,101,114,97,98,108,101,58,33,49,44,99,111,110,102,105,103,117,114,97,98,
  9422. 108,101,58,33,48,125,41,125,98,40,97,46,76,111,103,103,101,114,44,34,99,
  9423. 108,111,103,34,44,110,101,119,32,97,46,76,111,103,103,101,114,40,34,67,34,
  9424. 41,41,59,98,40,97,44,34,109,111,100,76,111,97,100,101,100,34,44,123,125,41,
  9425. 125,41,40,116,104,105,115,44,68,117,107,116,97,112,101,41,59,10,0,
  9426. };
  9427. #endif /* DUK_USE_BUILTIN_INITJS */
  9428. #elif defined(DUK_USE_DOUBLE_BE)
  9429. DUK_INTERNAL const duk_uint8_t duk_strings_data[1943] = {
  9430. 55,86,227,24,145,55,102,120,144,3,63,94,228,54,100,137,186,26,20,164,137,
  9431. 186,50,11,164,109,77,215,5,61,35,106,3,25,110,8,22,158,130,38,163,8,217,
  9432. 200,158,76,156,210,117,128,153,203,210,70,46,137,187,18,27,164,187,201,209,
  9433. 130,100,55,91,70,4,145,63,66,231,44,128,105,187,41,197,13,49,122,8,196,24,
  9434. 71,75,70,138,104,115,77,215,5,36,20,201,214,209,107,79,104,209,144,168,105,
  9435. 6,207,251,209,104,209,125,212,227,66,127,235,191,239,232,180,90,52,95,69,
  9436. 247,83,141,9,255,174,255,191,162,211,80,210,253,23,221,78,52,39,254,183,
  9437. 254,254,139,72,105,126,139,238,167,26,19,255,91,255,127,69,166,129,191,69,
  9438. 247,83,141,9,255,175,255,191,162,213,26,50,23,232,190,234,113,161,63,245,
  9439. 115,119,86,227,118,83,138,26,98,9,110,48,86,22,148,160,152,22,82,70,46,137,
  9440. 44,8,180,163,32,104,98,206,32,17,7,16,88,101,100,206,42,70,36,108,205,18,
  9441. 74,140,33,196,230,60,2,152,146,33,38,230,8,36,79,182,251,65,156,151,24,200,
  9442. 33,145,162,25,80,209,24,67,0,166,68,52,174,61,73,25,33,205,25,27,84,177,
  9443. 195,234,220,1,144,105,99,135,217,16,17,17,208,72,199,179,60,93,100,146,49,
  9444. 232,162,64,76,135,19,152,244,44,136,223,98,67,4,18,33,247,217,158,36,0,209,
  9445. 190,156,13,26,201,21,111,165,67,64,180,100,145,62,250,32,45,100,33,55,214,
  9446. 1,229,223,65,19,72,187,236,206,137,35,125,120,190,201,104,105,15,190,201,
  9447. 212,136,136,125,246,160,137,27,83,239,171,37,200,218,159,125,168,34,192,61,
  9448. 27,233,93,22,1,114,78,250,28,76,130,112,200,93,245,164,188,207,190,204,17,
  9449. 49,38,109,246,160,93,8,119,185,13,153,34,96,208,165,36,85,190,206,32,17,6,
  9450. 9,129,75,67,73,214,209,129,36,80,84,44,157,104,24,65,60,69,148,192,37,59,
  9451. 179,60,93,110,207,15,39,73,24,186,39,232,232,169,129,228,18,6,120,146,20,
  9452. 68,72,157,105,241,116,221,173,58,68,159,95,23,77,211,195,201,215,20,238,
  9453. 179,122,162,98,73,35,104,194,68,19,35,134,69,146,100,235,226,231,146,51,
  9454. 192,206,9,23,175,139,175,131,8,11,89,8,206,161,181,2,208,63,160,232,193,50,
  9455. 23,246,254,187,235,190,187,247,69,241,95,18,31,160,15,214,11,235,126,192,
  9456. 95,87,246,1,251,4,253,111,80,210,161,168,158,19,245,125,67,74,134,162,120,
  9457. 71,80,210,161,168,158,12,224,164,130,153,165,56,161,166,51,104,192,146,39,
  9458. 11,156,178,1,169,163,70,66,161,164,26,101,56,161,166,65,112,57,129,164,148,
  9459. 35,49,201,13,44,93,70,140,209,3,70,230,13,238,176,216,134,141,128,184,214,
  9460. 227,20,171,115,162,50,93,227,19,164,65,17,11,40,38,6,253,145,1,48,52,128,
  9461. 146,26,64,9,210,24,3,34,250,80,140,254,200,254,148,35,63,177,215,217,11,
  9462. 207,65,188,183,27,236,126,192,133,242,220,111,178,32,252,182,253,145,60,
  9463. 182,253,143,216,7,164,59,9,41,0,196,35,64,194,21,13,125,38,84,52,100,185,
  9464. 62,163,239,254,235,234,82,176,74,125,67,70,75,165,148,92,208,180,52,138,65,
  9465. 154,232,147,162,4,136,105,58,145,17,9,50,74,100,37,200,37,205,222,51,39,47,
  9466. 78,40,105,143,34,79,184,32,34,115,18,125,193,1,19,77,222,76,156,213,205,
  9467. 222,68,157,47,78,40,105,151,55,122,147,20,189,56,161,166,116,137,63,82,98,
  9468. 47,168,181,247,4,4,87,34,79,165,162,215,220,16,17,92,137,63,82,98,103,156,
  9469. 217,157,18,36,250,199,54,103,84,137,63,82,98,31,129,50,30,68,159,70,9,145,
  9470. 114,36,253,73,136,254,117,35,36,72,147,233,221,72,201,178,36,253,73,137,
  9471. 158,67,105,50,73,82,36,250,196,54,147,36,155,34,79,212,152,165,226,9,205,
  9472. 28,149,34,79,178,32,156,209,202,82,36,253,73,137,158,66,214,137,16,78,104,
  9473. 228,249,18,125,98,22,180,72,130,115,71,35,200,147,236,208,194,68,196,159,
  9474. 102,134,19,46,105,58,226,150,68,156,140,73,250,147,19,60,133,173,18,32,156,
  9475. 209,201,230,36,250,196,45,104,145,4,230,142,77,49,39,234,76,82,241,4,230,
  9476. 142,74,49,39,217,16,78,104,228,211,18,126,164,196,207,33,180,153,36,163,18,
  9477. 125,98,27,73,146,75,49,39,234,76,71,243,169,25,32,196,159,78,234,70,73,49,
  9478. 39,234,76,67,240,48,99,18,125,24,48,163,18,126,164,196,63,2,100,57,137,62,
  9479. 140,19,34,204,73,250,147,19,60,230,204,232,49,39,214,57,179,59,140,73,250,
  9480. 147,17,125,69,175,184,32,34,179,18,125,45,22,190,224,128,137,204,73,246,
  9481. 104,97,37,55,117,110,16,22,78,205,12,39,101,56,161,166,148,221,213,184,64,
  9482. 89,58,48,76,157,148,226,134,153,147,119,102,134,19,178,156,80,211,50,110,
  9483. 232,193,50,118,83,138,26,97,181,214,31,169,49,21,224,140,136,185,187,175,
  9484. 137,4,137,33,205,108,221,210,93,238,105,27,52,1,103,155,186,84,92,131,143,
  9485. 158,233,34,104,169,52,134,149,13,68,241,31,52,134,4,209,82,105,13,42,26,
  9486. 137,224,125,104,58,212,249,136,110,170,5,208,137,243,1,125,84,11,161,13,42,
  9487. 6,83,137,39,20,50,51,119,86,225,1,100,237,30,242,71,162,4,136,185,187,180,
  9488. 123,201,30,136,18,36,102,238,173,194,2,201,213,186,196,143,68,9,17,115,119,
  9489. 86,235,18,61,16,36,68,202,129,148,226,134,152,178,122,209,51,72,128,136,
  9490. 142,120,145,235,0,136,86,2,98,59,86,225,1,100,232,156,199,130,36,80,142,8,
  9491. 244,78,25,58,9,152,71,4,122,9,176,177,115,58,35,130,61,19,134,69,196,131,
  9492. 160,137,216,160,199,153,162,65,208,68,49,80,185,146,35,96,30,114,186,61,32,
  9493. 4,114,73,204,33,73,82,71,11,88,37,62,161,163,37,250,226,157,13,25,47,215,
  9494. 20,244,108,142,130,204,210,122,208,34,18,78,140,203,37,160,68,44,142,130,
  9495. 204,241,37,73,25,16,143,164,142,55,185,228,75,144,211,9,205,16,38,116,75,
  9496. 160,140,65,132,130,38,163,8,217,200,194,2,214,72,144,40,104,200,32,45,101,
  9497. 3,222,188,81,241,115,201,25,227,168,151,72,218,48,145,0,86,70,162,93,124,
  9498. 93,55,79,15,39,92,87,28,18,235,172,222,190,46,121,35,60,30,160,93,9,215,21,
  9499. 211,119,86,225,1,100,236,167,20,52,200,155,187,41,197,13,50,196,230,202,
  9500. 113,160,166,232,142,68,152,204,73,168,141,163,9,16,5,100,96,156,210,160,
  9501. 212,136,2,178,34,209,68,192,21,144,181,2,232,66,40,152,147,17,46,146,243,
  9502. 35,100,128,172,136,68,186,88,187,36,106,17,46,200,128,89,7,23,196,149,35,
  9503. 103,210,94,100,108,144,230,200,197,137,9,146,18,68,2,224,50,21,13,39,95,23,
  9504. 60,145,154,9,39,12,133,67,73,215,197,207,36,103,131,10,36,4,201,51,18,125,
  9505. 117,155,215,197,207,36,103,142,180,12,36,176,98,79,174,179,122,248,185,228,
  9506. 140,241,209,146,66,138,31,55,69,198,36,250,248,186,110,158,30,78,184,169,
  9507. 124,93,55,79,15,33,150,70,154,103,40,22,72,204,175,138,27,52,81,164,144,
  9508. 128,242,24,146,16,30,73,17,162,112,201,234,69,2,243,152,247,52,141,154,72,
  9509. 209,56,100,245,34,137,12,130,112,201,234,69,2,243,152,247,52,141,154,70,65,
  9510. 56,100,245,34,132,34,93,42,26,137,144,168,151,90,14,181,79,4,100,78,149,
  9511. 110,4,208,240,70,68,234,27,50,18,160,90,61,72,160,158,140,93,20,246,120,
  9512. 121,58,72,197,209,95,101,134,204,23,233,35,23,69,221,137,10,72,145,162,39,
  9513. 73,24,186,42,236,64,211,19,164,140,93,20,244,149,2,250,72,197,209,40,98,64,
  9514. 40,130,4,136,81,2,98,58,4,230,205,13,161,16,50,6,134,49,34,113,144,160,162,
  9515. 230,97,145,100,153,4,55,16,139,145,14,84,52,11,94,6,87,69,5,163,69,52,57,
  9516. 162,65,68,134,169,13,148,192,209,17,197,27,73,99,68,147,164,90,105,89,19,
  9517. 17,201,51,162,69,153,226,235,14,113,193,167,135,145,197,29,65,18,85,200,25,
  9518. 108,116,44,132,178,38,114,137,96,148,138,39,54,83,33,27,70,24,151,123,163,
  9519. 51,146,243,35,71,35,33,143,116,102,89,81,228,137,27,69,172,147,141,8,82,
  9520. 129,114,34,144,199,172,140,35,103,36,161,179,36,74,1,16,107,36,206,240,9,
  9521. 64,49,14,248,162,160,153,18,248,186,100,20,200,51,62,129,90,4,105,76,19,64,
  9522. 139,132,17,99,
  9523. };
  9524. /* to convert a heap stridx to a token number, subtract
  9525. * DUK_STRIDX_START_RESERVED and add DUK_TOK_START_RESERVED.
  9526. */
  9527. /* native functions: 128 */
  9528. DUK_INTERNAL const duk_c_function duk_bi_native_functions[128] = {
  9529. duk_bi_array_constructor,
  9530. duk_bi_array_constructor_is_array,
  9531. duk_bi_array_prototype_concat,
  9532. duk_bi_array_prototype_indexof_shared,
  9533. duk_bi_array_prototype_iter_shared,
  9534. duk_bi_array_prototype_join_shared,
  9535. duk_bi_array_prototype_pop,
  9536. duk_bi_array_prototype_push,
  9537. duk_bi_array_prototype_reduce_shared,
  9538. duk_bi_array_prototype_reverse,
  9539. duk_bi_array_prototype_shift,
  9540. duk_bi_array_prototype_slice,
  9541. duk_bi_array_prototype_sort,
  9542. duk_bi_array_prototype_splice,
  9543. duk_bi_array_prototype_to_string,
  9544. duk_bi_array_prototype_unshift,
  9545. duk_bi_boolean_constructor,
  9546. duk_bi_boolean_prototype_tostring_shared,
  9547. duk_bi_buffer_constructor,
  9548. duk_bi_buffer_prototype_tostring_shared,
  9549. duk_bi_date_constructor,
  9550. duk_bi_date_constructor_now,
  9551. duk_bi_date_constructor_parse,
  9552. duk_bi_date_constructor_utc,
  9553. duk_bi_date_prototype_get_shared,
  9554. duk_bi_date_prototype_get_timezone_offset,
  9555. duk_bi_date_prototype_set_shared,
  9556. duk_bi_date_prototype_set_time,
  9557. duk_bi_date_prototype_to_json,
  9558. duk_bi_date_prototype_tostring_shared,
  9559. duk_bi_date_prototype_value_of,
  9560. duk_bi_duktape_object_act,
  9561. duk_bi_duktape_object_compact,
  9562. duk_bi_duktape_object_dec,
  9563. duk_bi_duktape_object_enc,
  9564. duk_bi_duktape_object_fin,
  9565. duk_bi_duktape_object_gc,
  9566. duk_bi_duktape_object_info,
  9567. duk_bi_error_constructor_shared,
  9568. duk_bi_error_prototype_filename_getter,
  9569. duk_bi_error_prototype_linenumber_getter,
  9570. duk_bi_error_prototype_nop_setter,
  9571. duk_bi_error_prototype_stack_getter,
  9572. duk_bi_error_prototype_to_string,
  9573. duk_bi_function_constructor,
  9574. duk_bi_function_prototype,
  9575. duk_bi_function_prototype_apply,
  9576. duk_bi_function_prototype_bind,
  9577. duk_bi_function_prototype_call,
  9578. duk_bi_function_prototype_to_string,
  9579. duk_bi_global_object_decode_uri,
  9580. duk_bi_global_object_decode_uri_component,
  9581. duk_bi_global_object_encode_uri,
  9582. duk_bi_global_object_encode_uri_component,
  9583. duk_bi_global_object_escape,
  9584. duk_bi_global_object_eval,
  9585. duk_bi_global_object_is_finite,
  9586. duk_bi_global_object_is_nan,
  9587. duk_bi_global_object_parse_float,
  9588. duk_bi_global_object_parse_int,
  9589. duk_bi_global_object_print_helper,
  9590. duk_bi_global_object_require,
  9591. duk_bi_global_object_unescape,
  9592. duk_bi_json_object_parse,
  9593. duk_bi_json_object_stringify,
  9594. duk_bi_logger_constructor,
  9595. duk_bi_logger_prototype_fmt,
  9596. duk_bi_logger_prototype_log_shared,
  9597. duk_bi_logger_prototype_raw,
  9598. duk_bi_math_object_max,
  9599. duk_bi_math_object_min,
  9600. duk_bi_math_object_onearg_shared,
  9601. duk_bi_math_object_random,
  9602. duk_bi_math_object_twoarg_shared,
  9603. duk_bi_number_constructor,
  9604. duk_bi_number_prototype_to_exponential,
  9605. duk_bi_number_prototype_to_fixed,
  9606. duk_bi_number_prototype_to_locale_string,
  9607. duk_bi_number_prototype_to_precision,
  9608. duk_bi_number_prototype_to_string,
  9609. duk_bi_number_prototype_value_of,
  9610. duk_bi_object_constructor,
  9611. duk_bi_object_constructor_create,
  9612. duk_bi_object_constructor_define_properties,
  9613. duk_bi_object_constructor_define_property,
  9614. duk_bi_object_constructor_get_own_property_descriptor,
  9615. duk_bi_object_constructor_is_extensible,
  9616. duk_bi_object_constructor_is_sealed_frozen_shared,
  9617. duk_bi_object_constructor_keys_shared,
  9618. duk_bi_object_constructor_prevent_extensions,
  9619. duk_bi_object_constructor_seal_freeze_shared,
  9620. duk_bi_object_getprototype_shared,
  9621. duk_bi_object_prototype_has_own_property,
  9622. duk_bi_object_prototype_is_prototype_of,
  9623. duk_bi_object_prototype_property_is_enumerable,
  9624. duk_bi_object_prototype_to_locale_string,
  9625. duk_bi_object_prototype_to_string,
  9626. duk_bi_object_prototype_value_of,
  9627. duk_bi_object_setprototype_shared,
  9628. duk_bi_pointer_constructor,
  9629. duk_bi_pointer_prototype_tostring_shared,
  9630. duk_bi_proxy_constructor,
  9631. duk_bi_regexp_constructor,
  9632. duk_bi_regexp_prototype_exec,
  9633. duk_bi_regexp_prototype_test,
  9634. duk_bi_regexp_prototype_to_string,
  9635. duk_bi_string_constructor,
  9636. duk_bi_string_constructor_from_char_code,
  9637. duk_bi_string_prototype_caseconv_shared,
  9638. duk_bi_string_prototype_char_at,
  9639. duk_bi_string_prototype_char_code_at,
  9640. duk_bi_string_prototype_concat,
  9641. duk_bi_string_prototype_indexof_shared,
  9642. duk_bi_string_prototype_locale_compare,
  9643. duk_bi_string_prototype_match,
  9644. duk_bi_string_prototype_replace,
  9645. duk_bi_string_prototype_search,
  9646. duk_bi_string_prototype_slice,
  9647. duk_bi_string_prototype_split,
  9648. duk_bi_string_prototype_substr,
  9649. duk_bi_string_prototype_substring,
  9650. duk_bi_string_prototype_to_string,
  9651. duk_bi_string_prototype_trim,
  9652. duk_bi_thread_constructor,
  9653. duk_bi_thread_current,
  9654. duk_bi_thread_resume,
  9655. duk_bi_thread_yield,
  9656. duk_bi_type_error_thrower,
  9657. };
  9658. DUK_INTERNAL const duk_uint8_t duk_builtins_data[1341] = {
  9659. 105,195,74,136,77,40,105,44,9,124,104,45,3,3,72,0,71,225,65,165,168,33,243,
  9660. 6,145,0,122,24,210,148,14,249,35,120,160,55,226,13,76,192,196,177,164,152,
  9661. 22,192,4,202,52,147,72,152,0,169,70,146,105,11,0,23,40,210,77,32,96,3,37,
  9662. 26,73,163,236,0,108,163,73,52,121,128,14,148,105,38,142,176,1,242,144,56,
  9663. 208,254,84,6,166,82,242,80,210,246,1,250,67,72,144,15,232,13,44,96,47,162,
  9664. 52,160,128,62,80,160,255,253,102,76,7,255,128,0,0,0,0,0,3,84,7,255,0,0,0,0,
  9665. 0,0,3,124,64,153,132,18,49,2,38,48,64,200,7,153,64,227,48,26,103,3,13,0,89,
  9666. 165,34,53,36,38,180,128,216,143,155,81,227,114,58,111,2,142,0,73,194,94,56,
  9667. 202,167,33,209,195,114,70,206,209,26,58,36,100,228,145,131,130,69,204,137,
  9668. 22,51,36,84,208,145,67,82,68,205,137,18,62,36,68,240,122,32,120,62,0,2,87,
  9669. 61,39,255,254,9,46,24,0,10,31,224,29,13,91,40,0,9,101,137,32,0,48,197,84,
  9670. 66,214,9,10,82,68,37,81,144,133,52,65,214,137,6,90,40,0,12,21,100,144,69,
  9671. 114,64,213,202,0,3,2,86,36,5,96,160,0,63,254,16,37,135,91,98,25,242,192,7,
  9672. 194,248,30,236,32,123,46,17,234,186,71,162,241,5,23,240,0,15,241,1,70,74,3,
  9673. 8,249,49,3,204,185,15,35,3,231,137,121,240,163,254,0,46,224,18,7,248,192,
  9674. 42,249,14,3,224,20,32,0,46,208,35,231,96,41,29,96,192,117,3,159,58,66,64,
  9675. 232,10,3,156,45,14,96,194,57,67,87,156,129,231,206,48,51,240,0,23,16,25,
  9676. 255,255,251,132,16,209,192,8,106,0,2,223,4,53,0,2,111,2,26,128,1,183,65,13,
  9677. 64,1,27,129,7,224,0,45,176,131,255,255,241,73,252,0,91,77,103,193,254,64,
  9678. 36,200,64,101,31,47,32,123,188,129,178,218,70,195,113,29,173,231,206,55,3,
  9679. 71,19,129,168,0,11,93,196,141,103,34,53,92,208,212,116,35,157,213,13,55,
  9680. 100,52,158,16,209,108,3,65,176,12,246,192,128,0,179,155,2,0,2,205,122,3,49,
  9681. 221,2,151,248,0,7,249,64,147,35,4,249,17,8,0,11,220,68,2,155,248,172,184,
  9682. 15,253,255,255,255,255,255,255,236,168,0,0,0,0,0,0,0,0,44,152,15,255,0,0,0,
  9683. 0,0,0,12,120,15,254,0,0,0,0,0,0,12,136,31,254,0,0,0,0,0,0,0,7,249,128,147,
  9684. 32,0,0,0,0,0,0,0,0,12,249,79,35,225,52,143,117,0,49,147,8,197,75,35,17,56,
  9685. 130,159,248,1,176,197,136,194,23,254,96,138,128,63,206,4,153,33,255,224,0,
  9686. 0,0,0,0,2,215,200,232,24,3,161,0,1,95,142,132,0,9,240,58,16,0,53,240,232,
  9687. 64,1,23,163,161,0,5,77,142,132,0,25,52,58,16,0,116,200,225,30,227,192,94,
  9688. 15,1,118,48,16,0,133,208,192,64,2,87,35,1,0,10,92,12,4,0,45,110,48,16,0,
  9689. 197,176,192,64,3,86,163,1,0,14,90,12,4,0,61,102,48,16,1,5,144,192,64,4,86,
  9690. 35,1,0,18,88,12,4,0,77,94,48,16,1,69,112,192,64,5,85,163,1,0,22,86,12,4,0,
  9691. 93,86,50,5,80,217,21,35,69,0,24,84,13,20,0,101,78,52,190,0,52,166,26,95,0,
  9692. 27,82,141,63,128,14,41,6,159,192,7,84,99,83,224,3,202,33,169,240,1,245,8,
  9693. 209,64,8,20,3,69,0,33,79,141,47,128,17,39,134,151,192,8,211,163,79,224,4,
  9694. 137,193,167,240,2,84,192,192,64,9,146,227,69,0,39,21,31,192,0,63,208,24,
  9695. 147,4,12,0,32,41,56,72,240,60,100,148,100,140,100,132,128,0,0,0,0,0,0,0,0,
  9696. 210,172,228,74,52,17,242,210,1,83,252,0,3,253,33,81,132,11,69,144,24,166,
  9697. 229,69,37,23,39,41,40,57,65,72,47,146,176,10,175,224,0,159,234,4,140,41,18,
  9698. 44,128,192,10,191,224,0,159,235,4,140,41,10,44,128,192,10,207,224,0,159,
  9699. 236,4,140,41,2,44,128,192,10,223,224,0,159,237,4,140,40,250,44,128,192,10,
  9700. 239,224,0,159,238,4,140,40,242,44,128,192,10,255,224,0,159,239,4,140,40,
  9701. 234,44,128,192,7,255,228,34,160,32,2,223,133,69,138,43,180,162,96,32,1,53,
  9702. 216,221,218,170,139,34,32,31,243,23,33,127,125,28,247,161,224,31,251,138,
  9703. 163,178,149,193,127,33,160,31,237,229,189,138,147,114,135,33,96,32,4,144,
  9704. 253,170,34,22,140,33,32,31,243,80,79,51,63,157,230,160,224,31,251,80,79,51,
  9705. 63,157,230,164,130,71,34,5,28,160,0,40,4,114,128,1,31,209,202,0,6,126,73,
  9706. 65,245,28,160,0,135,196,114,128,2,158,209,202,0,12,122,71,40,0,57,229,28,
  9707. 160,1,7,132,85,227,186,50,241,217,37,32,0,39,84,128,29,17,202,0,18,115,71,
  9708. 40,0,81,201,28,160,1,103,20,114,128,6,7,255,224,4,195,63,65,193,1,130,255,
  9709. 248,0,11,255,224,0,31,255,138,52,128,129,135,218,0,0,0,0,0,3,57,192,71,72,
  9710. 4,229,0,29,99,140,201,72,50,31,32,196,144,131,2,49,225,121,16,240,184,132,
  9711. 120,82,64,65,102,252,0,233,239,200,20,62,176,78,248,0,255,148,0,5,163,240,
  9712. 0,15,249,192,9,242,38,16,0,23,184,152,5,171,240,0,15,250,64,9,242,200,16,0,
  9713. 23,187,32,5,179,240,0,15,250,194,15,72,64,0,0,0,0,0,0,0,15,201,4,195,187,
  9714. 126,226,4,200,68,18,162,16,72,134,60,35,67,31,0,1,25,161,143,128,1,8,144,
  9715. 199,192,0,196,40,99,224,0,130,4,49,240,0,84,255,252,36,100,16,184,155,250,
  9716. 226,217,150,47,46,91,249,34,224,139,229,229,203,127,36,26,119,32,203,203,
  9717. 150,254,72,52,97,221,147,102,157,217,192,
  9718. };
  9719. #ifdef DUK_USE_BUILTIN_INITJS
  9720. DUK_INTERNAL const duk_uint8_t duk_initjs_data[187] = {
  9721. 40,102,117,110,99,116,105,111,110,40,100,44,97,41,123,102,117,110,99,116,
  9722. 105,111,110,32,98,40,97,44,98,44,99,41,123,79,98,106,101,99,116,46,100,101,
  9723. 102,105,110,101,80,114,111,112,101,114,116,121,40,97,44,98,44,123,118,97,
  9724. 108,117,101,58,99,44,119,114,105,116,97,98,108,101,58,33,48,44,101,110,117,
  9725. 109,101,114,97,98,108,101,58,33,49,44,99,111,110,102,105,103,117,114,97,98,
  9726. 108,101,58,33,48,125,41,125,98,40,97,46,76,111,103,103,101,114,44,34,99,
  9727. 108,111,103,34,44,110,101,119,32,97,46,76,111,103,103,101,114,40,34,67,34,
  9728. 41,41,59,98,40,97,44,34,109,111,100,76,111,97,100,101,100,34,44,123,125,41,
  9729. 125,41,40,116,104,105,115,44,68,117,107,116,97,112,101,41,59,10,0,
  9730. };
  9731. #endif /* DUK_USE_BUILTIN_INITJS */
  9732. #elif defined(DUK_USE_DOUBLE_ME)
  9733. DUK_INTERNAL const duk_uint8_t duk_strings_data[1943] = {
  9734. 55,86,227,24,145,55,102,120,144,3,63,94,228,54,100,137,186,26,20,164,137,
  9735. 186,50,11,164,109,77,215,5,61,35,106,3,25,110,8,22,158,130,38,163,8,217,
  9736. 200,158,76,156,210,117,128,153,203,210,70,46,137,187,18,27,164,187,201,209,
  9737. 130,100,55,91,70,4,145,63,66,231,44,128,105,187,41,197,13,49,122,8,196,24,
  9738. 71,75,70,138,104,115,77,215,5,36,20,201,214,209,107,79,104,209,144,168,105,
  9739. 6,207,251,209,104,209,125,212,227,66,127,235,191,239,232,180,90,52,95,69,
  9740. 247,83,141,9,255,174,255,191,162,211,80,210,253,23,221,78,52,39,254,183,
  9741. 254,254,139,72,105,126,139,238,167,26,19,255,91,255,127,69,166,129,191,69,
  9742. 247,83,141,9,255,175,255,191,162,213,26,50,23,232,190,234,113,161,63,245,
  9743. 115,119,86,227,118,83,138,26,98,9,110,48,86,22,148,160,152,22,82,70,46,137,
  9744. 44,8,180,163,32,104,98,206,32,17,7,16,88,101,100,206,42,70,36,108,205,18,
  9745. 74,140,33,196,230,60,2,152,146,33,38,230,8,36,79,182,251,65,156,151,24,200,
  9746. 33,145,162,25,80,209,24,67,0,166,68,52,174,61,73,25,33,205,25,27,84,177,
  9747. 195,234,220,1,144,105,99,135,217,16,17,17,208,72,199,179,60,93,100,146,49,
  9748. 232,162,64,76,135,19,152,244,44,136,223,98,67,4,18,33,247,217,158,36,0,209,
  9749. 190,156,13,26,201,21,111,165,67,64,180,100,145,62,250,32,45,100,33,55,214,
  9750. 1,229,223,65,19,72,187,236,206,137,35,125,120,190,201,104,105,15,190,201,
  9751. 212,136,136,125,246,160,137,27,83,239,171,37,200,218,159,125,168,34,192,61,
  9752. 27,233,93,22,1,114,78,250,28,76,130,112,200,93,245,164,188,207,190,204,17,
  9753. 49,38,109,246,160,93,8,119,185,13,153,34,96,208,165,36,85,190,206,32,17,6,
  9754. 9,129,75,67,73,214,209,129,36,80,84,44,157,104,24,65,60,69,148,192,37,59,
  9755. 179,60,93,110,207,15,39,73,24,186,39,232,232,169,129,228,18,6,120,146,20,
  9756. 68,72,157,105,241,116,221,173,58,68,159,95,23,77,211,195,201,215,20,238,
  9757. 179,122,162,98,73,35,104,194,68,19,35,134,69,146,100,235,226,231,146,51,
  9758. 192,206,9,23,175,139,175,131,8,11,89,8,206,161,181,2,208,63,160,232,193,50,
  9759. 23,246,254,187,235,190,187,247,69,241,95,18,31,160,15,214,11,235,126,192,
  9760. 95,87,246,1,251,4,253,111,80,210,161,168,158,19,245,125,67,74,134,162,120,
  9761. 71,80,210,161,168,158,12,224,164,130,153,165,56,161,166,51,104,192,146,39,
  9762. 11,156,178,1,169,163,70,66,161,164,26,101,56,161,166,65,112,57,129,164,148,
  9763. 35,49,201,13,44,93,70,140,209,3,70,230,13,238,176,216,134,141,128,184,214,
  9764. 227,20,171,115,162,50,93,227,19,164,65,17,11,40,38,6,253,145,1,48,52,128,
  9765. 146,26,64,9,210,24,3,34,250,80,140,254,200,254,148,35,63,177,215,217,11,
  9766. 207,65,188,183,27,236,126,192,133,242,220,111,178,32,252,182,253,145,60,
  9767. 182,253,143,216,7,164,59,9,41,0,196,35,64,194,21,13,125,38,84,52,100,185,
  9768. 62,163,239,254,235,234,82,176,74,125,67,70,75,165,148,92,208,180,52,138,65,
  9769. 154,232,147,162,4,136,105,58,145,17,9,50,74,100,37,200,37,205,222,51,39,47,
  9770. 78,40,105,143,34,79,184,32,34,115,18,125,193,1,19,77,222,76,156,213,205,
  9771. 222,68,157,47,78,40,105,151,55,122,147,20,189,56,161,166,116,137,63,82,98,
  9772. 47,168,181,247,4,4,87,34,79,165,162,215,220,16,17,92,137,63,82,98,103,156,
  9773. 217,157,18,36,250,199,54,103,84,137,63,82,98,31,129,50,30,68,159,70,9,145,
  9774. 114,36,253,73,136,254,117,35,36,72,147,233,221,72,201,178,36,253,73,137,
  9775. 158,67,105,50,73,82,36,250,196,54,147,36,155,34,79,212,152,165,226,9,205,
  9776. 28,149,34,79,178,32,156,209,202,82,36,253,73,137,158,66,214,137,16,78,104,
  9777. 228,249,18,125,98,22,180,72,130,115,71,35,200,147,236,208,194,68,196,159,
  9778. 102,134,19,46,105,58,226,150,68,156,140,73,250,147,19,60,133,173,18,32,156,
  9779. 209,201,230,36,250,196,45,104,145,4,230,142,77,49,39,234,76,82,241,4,230,
  9780. 142,74,49,39,217,16,78,104,228,211,18,126,164,196,207,33,180,153,36,163,18,
  9781. 125,98,27,73,146,75,49,39,234,76,71,243,169,25,32,196,159,78,234,70,73,49,
  9782. 39,234,76,67,240,48,99,18,125,24,48,163,18,126,164,196,63,2,100,57,137,62,
  9783. 140,19,34,204,73,250,147,19,60,230,204,232,49,39,214,57,179,59,140,73,250,
  9784. 147,17,125,69,175,184,32,34,179,18,125,45,22,190,224,128,137,204,73,246,
  9785. 104,97,37,55,117,110,16,22,78,205,12,39,101,56,161,166,148,221,213,184,64,
  9786. 89,58,48,76,157,148,226,134,153,147,119,102,134,19,178,156,80,211,50,110,
  9787. 232,193,50,118,83,138,26,97,181,214,31,169,49,21,224,140,136,185,187,175,
  9788. 137,4,137,33,205,108,221,210,93,238,105,27,52,1,103,155,186,84,92,131,143,
  9789. 158,233,34,104,169,52,134,149,13,68,241,31,52,134,4,209,82,105,13,42,26,
  9790. 137,224,125,104,58,212,249,136,110,170,5,208,137,243,1,125,84,11,161,13,42,
  9791. 6,83,137,39,20,50,51,119,86,225,1,100,237,30,242,71,162,4,136,185,187,180,
  9792. 123,201,30,136,18,36,102,238,173,194,2,201,213,186,196,143,68,9,17,115,119,
  9793. 86,235,18,61,16,36,68,202,129,148,226,134,152,178,122,209,51,72,128,136,
  9794. 142,120,145,235,0,136,86,2,98,59,86,225,1,100,232,156,199,130,36,80,142,8,
  9795. 244,78,25,58,9,152,71,4,122,9,176,177,115,58,35,130,61,19,134,69,196,131,
  9796. 160,137,216,160,199,153,162,65,208,68,49,80,185,146,35,96,30,114,186,61,32,
  9797. 4,114,73,204,33,73,82,71,11,88,37,62,161,163,37,250,226,157,13,25,47,215,
  9798. 20,244,108,142,130,204,210,122,208,34,18,78,140,203,37,160,68,44,142,130,
  9799. 204,241,37,73,25,16,143,164,142,55,185,228,75,144,211,9,205,16,38,116,75,
  9800. 160,140,65,132,130,38,163,8,217,200,194,2,214,72,144,40,104,200,32,45,101,
  9801. 3,222,188,81,241,115,201,25,227,168,151,72,218,48,145,0,86,70,162,93,124,
  9802. 93,55,79,15,39,92,87,28,18,235,172,222,190,46,121,35,60,30,160,93,9,215,21,
  9803. 211,119,86,225,1,100,236,167,20,52,200,155,187,41,197,13,50,196,230,202,
  9804. 113,160,166,232,142,68,152,204,73,168,141,163,9,16,5,100,96,156,210,160,
  9805. 212,136,2,178,34,209,68,192,21,144,181,2,232,66,40,152,147,17,46,146,243,
  9806. 35,100,128,172,136,68,186,88,187,36,106,17,46,200,128,89,7,23,196,149,35,
  9807. 103,210,94,100,108,144,230,200,197,137,9,146,18,68,2,224,50,21,13,39,95,23,
  9808. 60,145,154,9,39,12,133,67,73,215,197,207,36,103,131,10,36,4,201,51,18,125,
  9809. 117,155,215,197,207,36,103,142,180,12,36,176,98,79,174,179,122,248,185,228,
  9810. 140,241,209,146,66,138,31,55,69,198,36,250,248,186,110,158,30,78,184,169,
  9811. 124,93,55,79,15,33,150,70,154,103,40,22,72,204,175,138,27,52,81,164,144,
  9812. 128,242,24,146,16,30,73,17,162,112,201,234,69,2,243,152,247,52,141,154,72,
  9813. 209,56,100,245,34,137,12,130,112,201,234,69,2,243,152,247,52,141,154,70,65,
  9814. 56,100,245,34,132,34,93,42,26,137,144,168,151,90,14,181,79,4,100,78,149,
  9815. 110,4,208,240,70,68,234,27,50,18,160,90,61,72,160,158,140,93,20,246,120,
  9816. 121,58,72,197,209,95,101,134,204,23,233,35,23,69,221,137,10,72,145,162,39,
  9817. 73,24,186,42,236,64,211,19,164,140,93,20,244,149,2,250,72,197,209,40,98,64,
  9818. 40,130,4,136,81,2,98,58,4,230,205,13,161,16,50,6,134,49,34,113,144,160,162,
  9819. 230,97,145,100,153,4,55,16,139,145,14,84,52,11,94,6,87,69,5,163,69,52,57,
  9820. 162,65,68,134,169,13,148,192,209,17,197,27,73,99,68,147,164,90,105,89,19,
  9821. 17,201,51,162,69,153,226,235,14,113,193,167,135,145,197,29,65,18,85,200,25,
  9822. 108,116,44,132,178,38,114,137,96,148,138,39,54,83,33,27,70,24,151,123,163,
  9823. 51,146,243,35,71,35,33,143,116,102,89,81,228,137,27,69,172,147,141,8,82,
  9824. 129,114,34,144,199,172,140,35,103,36,161,179,36,74,1,16,107,36,206,240,9,
  9825. 64,49,14,248,162,160,153,18,248,186,100,20,200,51,62,129,90,4,105,76,19,64,
  9826. 139,132,17,99,
  9827. };
  9828. /* to convert a heap stridx to a token number, subtract
  9829. * DUK_STRIDX_START_RESERVED and add DUK_TOK_START_RESERVED.
  9830. */
  9831. /* native functions: 128 */
  9832. DUK_INTERNAL const duk_c_function duk_bi_native_functions[128] = {
  9833. duk_bi_array_constructor,
  9834. duk_bi_array_constructor_is_array,
  9835. duk_bi_array_prototype_concat,
  9836. duk_bi_array_prototype_indexof_shared,
  9837. duk_bi_array_prototype_iter_shared,
  9838. duk_bi_array_prototype_join_shared,
  9839. duk_bi_array_prototype_pop,
  9840. duk_bi_array_prototype_push,
  9841. duk_bi_array_prototype_reduce_shared,
  9842. duk_bi_array_prototype_reverse,
  9843. duk_bi_array_prototype_shift,
  9844. duk_bi_array_prototype_slice,
  9845. duk_bi_array_prototype_sort,
  9846. duk_bi_array_prototype_splice,
  9847. duk_bi_array_prototype_to_string,
  9848. duk_bi_array_prototype_unshift,
  9849. duk_bi_boolean_constructor,
  9850. duk_bi_boolean_prototype_tostring_shared,
  9851. duk_bi_buffer_constructor,
  9852. duk_bi_buffer_prototype_tostring_shared,
  9853. duk_bi_date_constructor,
  9854. duk_bi_date_constructor_now,
  9855. duk_bi_date_constructor_parse,
  9856. duk_bi_date_constructor_utc,
  9857. duk_bi_date_prototype_get_shared,
  9858. duk_bi_date_prototype_get_timezone_offset,
  9859. duk_bi_date_prototype_set_shared,
  9860. duk_bi_date_prototype_set_time,
  9861. duk_bi_date_prototype_to_json,
  9862. duk_bi_date_prototype_tostring_shared,
  9863. duk_bi_date_prototype_value_of,
  9864. duk_bi_duktape_object_act,
  9865. duk_bi_duktape_object_compact,
  9866. duk_bi_duktape_object_dec,
  9867. duk_bi_duktape_object_enc,
  9868. duk_bi_duktape_object_fin,
  9869. duk_bi_duktape_object_gc,
  9870. duk_bi_duktape_object_info,
  9871. duk_bi_error_constructor_shared,
  9872. duk_bi_error_prototype_filename_getter,
  9873. duk_bi_error_prototype_linenumber_getter,
  9874. duk_bi_error_prototype_nop_setter,
  9875. duk_bi_error_prototype_stack_getter,
  9876. duk_bi_error_prototype_to_string,
  9877. duk_bi_function_constructor,
  9878. duk_bi_function_prototype,
  9879. duk_bi_function_prototype_apply,
  9880. duk_bi_function_prototype_bind,
  9881. duk_bi_function_prototype_call,
  9882. duk_bi_function_prototype_to_string,
  9883. duk_bi_global_object_decode_uri,
  9884. duk_bi_global_object_decode_uri_component,
  9885. duk_bi_global_object_encode_uri,
  9886. duk_bi_global_object_encode_uri_component,
  9887. duk_bi_global_object_escape,
  9888. duk_bi_global_object_eval,
  9889. duk_bi_global_object_is_finite,
  9890. duk_bi_global_object_is_nan,
  9891. duk_bi_global_object_parse_float,
  9892. duk_bi_global_object_parse_int,
  9893. duk_bi_global_object_print_helper,
  9894. duk_bi_global_object_require,
  9895. duk_bi_global_object_unescape,
  9896. duk_bi_json_object_parse,
  9897. duk_bi_json_object_stringify,
  9898. duk_bi_logger_constructor,
  9899. duk_bi_logger_prototype_fmt,
  9900. duk_bi_logger_prototype_log_shared,
  9901. duk_bi_logger_prototype_raw,
  9902. duk_bi_math_object_max,
  9903. duk_bi_math_object_min,
  9904. duk_bi_math_object_onearg_shared,
  9905. duk_bi_math_object_random,
  9906. duk_bi_math_object_twoarg_shared,
  9907. duk_bi_number_constructor,
  9908. duk_bi_number_prototype_to_exponential,
  9909. duk_bi_number_prototype_to_fixed,
  9910. duk_bi_number_prototype_to_locale_string,
  9911. duk_bi_number_prototype_to_precision,
  9912. duk_bi_number_prototype_to_string,
  9913. duk_bi_number_prototype_value_of,
  9914. duk_bi_object_constructor,
  9915. duk_bi_object_constructor_create,
  9916. duk_bi_object_constructor_define_properties,
  9917. duk_bi_object_constructor_define_property,
  9918. duk_bi_object_constructor_get_own_property_descriptor,
  9919. duk_bi_object_constructor_is_extensible,
  9920. duk_bi_object_constructor_is_sealed_frozen_shared,
  9921. duk_bi_object_constructor_keys_shared,
  9922. duk_bi_object_constructor_prevent_extensions,
  9923. duk_bi_object_constructor_seal_freeze_shared,
  9924. duk_bi_object_getprototype_shared,
  9925. duk_bi_object_prototype_has_own_property,
  9926. duk_bi_object_prototype_is_prototype_of,
  9927. duk_bi_object_prototype_property_is_enumerable,
  9928. duk_bi_object_prototype_to_locale_string,
  9929. duk_bi_object_prototype_to_string,
  9930. duk_bi_object_prototype_value_of,
  9931. duk_bi_object_setprototype_shared,
  9932. duk_bi_pointer_constructor,
  9933. duk_bi_pointer_prototype_tostring_shared,
  9934. duk_bi_proxy_constructor,
  9935. duk_bi_regexp_constructor,
  9936. duk_bi_regexp_prototype_exec,
  9937. duk_bi_regexp_prototype_test,
  9938. duk_bi_regexp_prototype_to_string,
  9939. duk_bi_string_constructor,
  9940. duk_bi_string_constructor_from_char_code,
  9941. duk_bi_string_prototype_caseconv_shared,
  9942. duk_bi_string_prototype_char_at,
  9943. duk_bi_string_prototype_char_code_at,
  9944. duk_bi_string_prototype_concat,
  9945. duk_bi_string_prototype_indexof_shared,
  9946. duk_bi_string_prototype_locale_compare,
  9947. duk_bi_string_prototype_match,
  9948. duk_bi_string_prototype_replace,
  9949. duk_bi_string_prototype_search,
  9950. duk_bi_string_prototype_slice,
  9951. duk_bi_string_prototype_split,
  9952. duk_bi_string_prototype_substr,
  9953. duk_bi_string_prototype_substring,
  9954. duk_bi_string_prototype_to_string,
  9955. duk_bi_string_prototype_trim,
  9956. duk_bi_thread_constructor,
  9957. duk_bi_thread_current,
  9958. duk_bi_thread_resume,
  9959. duk_bi_thread_yield,
  9960. duk_bi_type_error_thrower,
  9961. };
  9962. DUK_INTERNAL const duk_uint8_t duk_builtins_data[1341] = {
  9963. 105,195,74,136,77,40,105,44,9,124,104,45,3,3,72,0,71,225,65,165,168,33,243,
  9964. 6,145,0,122,24,210,148,14,249,35,120,160,55,226,13,76,192,196,177,164,152,
  9965. 22,192,4,202,52,147,72,152,0,169,70,146,105,11,0,23,40,210,77,32,96,3,37,
  9966. 26,73,163,236,0,108,163,73,52,121,128,14,148,105,38,142,176,1,242,144,56,
  9967. 208,254,84,6,166,82,242,80,210,246,1,250,67,72,144,15,232,13,44,96,47,162,
  9968. 52,160,128,62,80,160,255,253,102,76,0,0,15,135,240,0,0,0,3,84,0,0,15,7,240,
  9969. 0,0,0,3,124,64,153,132,18,49,2,38,48,64,200,7,153,64,227,48,26,103,3,13,0,
  9970. 89,165,34,53,36,38,180,128,216,143,155,81,227,114,58,111,2,142,0,73,194,94,
  9971. 56,202,167,33,209,195,114,70,206,209,26,58,36,100,228,145,131,130,69,204,
  9972. 137,22,51,36,84,208,145,67,82,68,205,137,18,62,36,68,240,122,32,120,62,0,2,
  9973. 87,61,39,255,254,9,46,24,0,10,31,224,29,13,91,40,0,9,101,137,32,0,48,197,
  9974. 84,66,214,9,10,82,68,37,81,144,133,52,65,214,137,6,90,40,0,12,21,100,144,
  9975. 69,114,64,213,202,0,3,2,86,36,5,96,160,0,63,254,16,37,135,91,98,25,242,192,
  9976. 7,194,248,30,236,32,123,46,17,234,186,71,162,241,5,23,240,0,15,241,1,70,74,
  9977. 3,8,249,49,3,204,185,15,35,3,231,137,121,240,163,254,0,46,224,18,7,248,192,
  9978. 42,249,14,3,224,20,32,0,46,208,35,231,96,41,29,96,192,117,3,159,58,66,64,
  9979. 232,10,3,156,45,14,96,194,57,67,87,156,129,231,206,48,51,240,0,23,16,25,
  9980. 255,255,251,132,16,209,192,8,106,0,2,223,4,53,0,2,111,2,26,128,1,183,65,13,
  9981. 64,1,27,129,7,224,0,45,176,131,255,255,241,73,252,0,91,77,103,193,254,64,
  9982. 36,200,64,101,31,47,32,123,188,129,178,218,70,195,113,29,173,231,206,55,3,
  9983. 71,19,129,168,0,11,93,196,141,103,34,53,92,208,212,116,35,157,213,13,55,
  9984. 100,52,158,16,209,108,3,65,176,12,246,192,128,0,179,155,2,0,2,205,122,3,49,
  9985. 221,2,151,248,0,7,249,64,147,35,4,249,17,8,0,11,220,68,2,155,248,172,184,
  9986. 31,255,253,239,255,255,255,255,236,168,0,0,0,0,0,32,0,0,12,152,0,0,31,15,
  9987. 224,0,0,0,12,120,0,0,30,15,224,0,0,0,12,136,0,0,30,31,224,0,0,0,0,7,249,
  9988. 128,147,32,0,0,0,0,0,0,0,0,12,249,79,35,225,52,143,117,0,49,147,8,197,75,
  9989. 35,17,56,130,159,248,1,176,197,136,194,23,254,96,138,128,63,206,4,153,32,0,
  9990. 3,225,252,0,0,0,2,215,200,232,24,3,161,0,1,95,142,132,0,9,240,58,16,0,53,
  9991. 240,232,64,1,23,163,161,0,5,77,142,132,0,25,52,58,16,0,116,200,225,30,227,
  9992. 192,94,15,1,118,48,16,0,133,208,192,64,2,87,35,1,0,10,92,12,4,0,45,110,48,
  9993. 16,0,197,176,192,64,3,86,163,1,0,14,90,12,4,0,61,102,48,16,1,5,144,192,64,
  9994. 4,86,35,1,0,18,88,12,4,0,77,94,48,16,1,69,112,192,64,5,85,163,1,0,22,86,12,
  9995. 4,0,93,86,50,5,80,217,21,35,69,0,24,84,13,20,0,101,78,52,190,0,52,166,26,
  9996. 95,0,27,82,141,63,128,14,41,6,159,192,7,84,99,83,224,3,202,33,169,240,1,
  9997. 245,8,209,64,8,20,3,69,0,33,79,141,47,128,17,39,134,151,192,8,211,163,79,
  9998. 224,4,137,193,167,240,2,84,192,192,64,9,146,227,69,0,39,21,31,192,0,63,208,
  9999. 24,147,4,12,0,32,41,56,72,240,60,100,148,100,140,100,132,128,0,0,0,0,0,0,0,
  10000. 0,210,172,228,74,52,17,242,210,1,83,252,0,3,253,33,81,132,11,69,144,24,166,
  10001. 229,69,37,23,39,41,40,57,65,72,47,146,176,10,175,224,0,159,234,4,140,41,18,
  10002. 44,128,192,10,191,224,0,159,235,4,140,41,10,44,128,192,10,207,224,0,159,
  10003. 236,4,140,41,2,44,128,192,10,223,224,0,159,237,4,140,40,250,44,128,192,10,
  10004. 239,224,0,159,238,4,140,40,242,44,128,192,10,255,224,0,159,239,4,140,40,
  10005. 234,44,128,192,7,255,228,34,160,5,95,130,160,52,171,138,69,162,96,88,181,
  10006. 129,32,11,42,218,221,162,32,33,23,115,31,247,156,253,127,33,224,35,138,251,
  10007. 159,255,65,21,178,161,160,61,229,237,159,135,114,147,10,161,96,125,144,132,
  10008. 160,12,22,162,42,33,32,79,80,115,31,230,157,191,179,32,224,79,80,123,31,
  10009. 230,157,191,179,36,130,71,34,5,28,160,0,40,4,114,128,1,31,209,202,0,6,126,
  10010. 73,65,245,28,160,0,135,196,114,128,2,158,209,202,0,12,122,71,40,0,57,229,
  10011. 28,160,1,7,132,85,227,186,50,241,217,37,32,0,39,84,128,29,17,202,0,18,115,
  10012. 71,40,0,81,201,28,160,1,103,20,114,128,6,7,255,224,4,195,63,65,193,1,130,
  10013. 255,248,0,11,255,224,0,31,255,138,52,128,1,219,134,128,0,0,0,0,3,57,192,71,
  10014. 72,4,229,0,29,99,140,201,72,50,31,32,196,144,131,2,49,225,121,16,240,184,
  10015. 132,120,82,64,65,102,252,0,233,239,200,20,62,176,78,248,0,255,148,0,5,163,
  10016. 240,0,15,249,192,9,242,38,16,0,23,184,152,5,171,240,0,15,250,64,9,242,200,
  10017. 16,0,23,187,32,5,179,240,0,15,250,194,15,72,0,0,0,64,0,0,0,0,15,201,4,195,
  10018. 187,126,226,4,200,68,18,162,16,72,134,60,35,67,31,0,1,25,161,143,128,1,8,
  10019. 144,199,192,0,196,40,99,224,0,130,4,49,240,0,84,255,252,36,100,16,184,155,
  10020. 250,226,217,150,47,46,91,249,34,224,139,229,229,203,127,36,26,119,32,203,
  10021. 203,150,254,72,52,97,221,147,102,157,217,192,
  10022. };
  10023. #ifdef DUK_USE_BUILTIN_INITJS
  10024. DUK_INTERNAL const duk_uint8_t duk_initjs_data[187] = {
  10025. 40,102,117,110,99,116,105,111,110,40,100,44,97,41,123,102,117,110,99,116,
  10026. 105,111,110,32,98,40,97,44,98,44,99,41,123,79,98,106,101,99,116,46,100,101,
  10027. 102,105,110,101,80,114,111,112,101,114,116,121,40,97,44,98,44,123,118,97,
  10028. 108,117,101,58,99,44,119,114,105,116,97,98,108,101,58,33,48,44,101,110,117,
  10029. 109,101,114,97,98,108,101,58,33,49,44,99,111,110,102,105,103,117,114,97,98,
  10030. 108,101,58,33,48,125,41,125,98,40,97,46,76,111,103,103,101,114,44,34,99,
  10031. 108,111,103,34,44,110,101,119,32,97,46,76,111,103,103,101,114,40,34,67,34,
  10032. 41,41,59,98,40,97,44,34,109,111,100,76,111,97,100,101,100,34,44,123,125,41,
  10033. 125,41,40,116,104,105,115,44,68,117,107,116,97,112,101,41,59,10,0,
  10034. };
  10035. #endif /* DUK_USE_BUILTIN_INITJS */
  10036. #else
  10037. #error invalid endianness defines
  10038. #endif
  10039. #line 1 "duk_error_macros.c"
  10040. /*
  10041. * Error, fatal, and panic handling.
  10042. */
  10043. /* include removed: duk_internal.h */
  10044. #define DUK__ERRFMT_BUFSIZE 256 /* size for formatting buffers */
  10045. #ifdef DUK_USE_VERBOSE_ERRORS
  10046. #ifdef DUK_USE_VARIADIC_MACROS
  10047. DUK_INTERNAL void duk_err_handle_error(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, ...) {
  10048. va_list ap;
  10049. char msg[DUK__ERRFMT_BUFSIZE];
  10050. va_start(ap, fmt);
  10051. (void) DUK_VSNPRINTF(msg, sizeof(msg), fmt, ap);
  10052. msg[sizeof(msg) - 1] = (char) 0;
  10053. duk_err_create_and_throw(thr, code, msg, filename, line);
  10054. va_end(ap); /* dead code, but ensures portability (see Linux man page notes) */
  10055. }
  10056. #else /* DUK_USE_VARIADIC_MACROS */
  10057. DUK_INTERNAL const char *duk_err_file_stash = NULL;
  10058. DUK_INTERNAL duk_int_t duk_err_line_stash = 0;
  10059. DUK_NORETURN(DUK_LOCAL_DECL void duk__handle_error(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, va_list ap));
  10060. DUK_LOCAL void duk__handle_error(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, va_list ap) {
  10061. char msg[DUK__ERRFMT_BUFSIZE];
  10062. (void) DUK_VSNPRINTF(msg, sizeof(msg), fmt, ap);
  10063. msg[sizeof(msg) - 1] = (char) 0;
  10064. duk_err_create_and_throw(thr, code, msg, filename, line);
  10065. }
  10066. DUK_INTERNAL void duk_err_handle_error(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, ...) {
  10067. va_list ap;
  10068. va_start(ap, fmt);
  10069. duk__handle_error(filename, line, thr, code, fmt, ap);
  10070. va_end(ap); /* dead code */
  10071. }
  10072. DUK_INTERNAL void duk_err_handle_error_stash(duk_hthread *thr, duk_errcode_t code, const char *fmt, ...) {
  10073. va_list ap;
  10074. va_start(ap, fmt);
  10075. duk__handle_error(duk_err_file_stash, duk_err_line_stash, thr, code, fmt, ap);
  10076. va_end(ap); /* dead code */
  10077. }
  10078. #endif /* DUK_USE_VARIADIC_MACROS */
  10079. #else /* DUK_USE_VERBOSE_ERRORS */
  10080. #ifdef DUK_USE_VARIADIC_MACROS
  10081. DUK_INTERNAL void duk_err_handle_error(duk_hthread *thr, duk_errcode_t code) {
  10082. duk_err_create_and_throw(thr, code);
  10083. }
  10084. #else /* DUK_USE_VARIADIC_MACROS */
  10085. DUK_INTERNAL void duk_err_handle_error_nonverbose1(duk_hthread *thr, duk_errcode_t code, const char *fmt, ...) {
  10086. DUK_UNREF(fmt);
  10087. duk_err_create_and_throw(thr, code);
  10088. }
  10089. DUK_INTERNAL void duk_err_handle_error_nonverbose2(const char *filename, duk_int_t line, duk_hthread *thr, duk_errcode_t code, const char *fmt, ...) {
  10090. DUK_UNREF(filename);
  10091. DUK_UNREF(line);
  10092. DUK_UNREF(fmt);
  10093. duk_err_create_and_throw(thr, code);
  10094. }
  10095. #endif /* DUK_USE_VARIADIC_MACROS */
  10096. #endif /* DUK_USE_VERBOSE_ERRORS */
  10097. /*
  10098. * Default fatal error handler
  10099. */
  10100. DUK_INTERNAL void duk_default_fatal_handler(duk_context *ctx, duk_errcode_t code, const char *msg) {
  10101. DUK_UNREF(ctx);
  10102. #ifdef DUK_USE_FILE_IO
  10103. DUK_FPRINTF(DUK_STDERR, "FATAL %ld: %s\n", (long) code, (const char *) (msg ? msg : "null"));
  10104. DUK_FFLUSH(DUK_STDERR);
  10105. #else
  10106. /* omit print */
  10107. #endif
  10108. DUK_D(DUK_DPRINT("default fatal handler called, code %ld -> calling DUK_PANIC()", (long) code));
  10109. DUK_PANIC(code, msg);
  10110. DUK_UNREACHABLE();
  10111. }
  10112. /*
  10113. * Default panic handler
  10114. */
  10115. #if !defined(DUK_USE_PANIC_HANDLER)
  10116. DUK_INTERNAL void duk_default_panic_handler(duk_errcode_t code, const char *msg) {
  10117. #ifdef DUK_USE_FILE_IO
  10118. DUK_FPRINTF(DUK_STDERR, "PANIC %ld: %s ("
  10119. #if defined(DUK_USE_PANIC_ABORT)
  10120. "calling abort"
  10121. #elif defined(DUK_USE_PANIC_EXIT)
  10122. "calling exit"
  10123. #elif defined(DUK_USE_PANIC_SEGFAULT)
  10124. "segfaulting on purpose"
  10125. #else
  10126. #error no DUK_USE_PANIC_xxx macro defined
  10127. #endif
  10128. ")\n", (long) code, (const char *) (msg ? msg : "null"));
  10129. DUK_FFLUSH(DUK_STDERR);
  10130. #else
  10131. /* omit print */
  10132. DUK_UNREF(code);
  10133. DUK_UNREF(msg);
  10134. #endif
  10135. #if defined(DUK_USE_PANIC_ABORT)
  10136. DUK_ABORT();
  10137. #elif defined(DUK_USE_PANIC_EXIT)
  10138. DUK_EXIT(-1);
  10139. #elif defined(DUK_USE_PANIC_SEGFAULT)
  10140. /* exit() afterwards to satisfy "noreturn" */
  10141. DUK_CAUSE_SEGFAULT(); /* SCANBUILD: "Dereference of null pointer", normal */
  10142. DUK_EXIT(-1);
  10143. #else
  10144. #error no DUK_USE_PANIC_xxx macro defined
  10145. #endif
  10146. DUK_UNREACHABLE();
  10147. }
  10148. #endif /* !DUK_USE_PANIC_HANDLER */
  10149. #undef DUK__ERRFMT_BUFSIZE
  10150. #line 1 "duk_unicode_support.c"
  10151. /*
  10152. * Various Unicode help functions for character classification predicates,
  10153. * case conversion, decoding, etc.
  10154. */
  10155. /* include removed: duk_internal.h */
  10156. /*
  10157. * XUTF-8 and CESU-8 encoding/decoding
  10158. */
  10159. DUK_INTERNAL duk_small_int_t duk_unicode_get_xutf8_length(duk_ucodepoint_t cp) {
  10160. duk_uint_fast32_t x = (duk_uint_fast32_t) cp;
  10161. if (x < 0x80UL) {
  10162. /* 7 bits */
  10163. return 1;
  10164. } else if (x < 0x800UL) {
  10165. /* 11 bits */
  10166. return 2;
  10167. } else if (x < 0x10000UL) {
  10168. /* 16 bits */
  10169. return 3;
  10170. } else if (x < 0x200000UL) {
  10171. /* 21 bits */
  10172. return 4;
  10173. } else if (x < 0x4000000UL) {
  10174. /* 26 bits */
  10175. return 5;
  10176. } else if (x < (duk_ucodepoint_t) 0x80000000UL) {
  10177. /* 31 bits */
  10178. return 6;
  10179. } else {
  10180. /* 36 bits */
  10181. return 7;
  10182. }
  10183. }
  10184. DUK_INTERNAL duk_uint8_t duk_unicode_xutf8_markers[7] = {
  10185. 0x00, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe
  10186. };
  10187. /* Encode to extended UTF-8; 'out' must have space for at least
  10188. * DUK_UNICODE_MAX_XUTF8_LENGTH bytes. Allows encoding of any
  10189. * 32-bit (unsigned) codepoint.
  10190. */
  10191. DUK_INTERNAL duk_small_int_t duk_unicode_encode_xutf8(duk_ucodepoint_t cp, duk_uint8_t *out) {
  10192. duk_uint_fast32_t x = (duk_uint_fast32_t) cp;
  10193. duk_small_int_t len;
  10194. duk_uint8_t marker;
  10195. duk_small_int_t i;
  10196. len = duk_unicode_get_xutf8_length(cp);
  10197. DUK_ASSERT(len > 0);
  10198. marker = duk_unicode_xutf8_markers[len - 1]; /* 64-bit OK because always >= 0 */
  10199. i = len;
  10200. DUK_ASSERT(i > 0);
  10201. do {
  10202. i--;
  10203. if (i > 0) {
  10204. out[i] = (duk_uint8_t) (0x80 + (x & 0x3f));
  10205. x >>= 6;
  10206. } else {
  10207. /* Note: masking of 'x' is not necessary because of
  10208. * range check and shifting -> no bits overlapping
  10209. * the marker should be set.
  10210. */
  10211. out[0] = (duk_uint8_t) (marker + x);
  10212. }
  10213. } while (i > 0);
  10214. return len;
  10215. }
  10216. /* Encode to CESU-8; 'out' must have space for at least
  10217. * DUK_UNICODE_MAX_CESU8_LENGTH bytes; codepoints above U+10FFFF
  10218. * will encode to garbage but won't overwrite the output buffer.
  10219. */
  10220. DUK_INTERNAL duk_small_int_t duk_unicode_encode_cesu8(duk_ucodepoint_t cp, duk_uint8_t *out) {
  10221. duk_uint_fast32_t x = (duk_uint_fast32_t) cp;
  10222. duk_small_int_t len;
  10223. if (x < 0x80UL) {
  10224. out[0] = (duk_uint8_t) x;
  10225. len = 1;
  10226. } else if (x < 0x800UL) {
  10227. out[0] = (duk_uint8_t) (0xc0 + ((x >> 6) & 0x1f));
  10228. out[1] = (duk_uint8_t) (0x80 + (x & 0x3f));
  10229. len = 2;
  10230. } else if (x < 0x10000UL) {
  10231. /* surrogate pairs get encoded here */
  10232. out[0] = (duk_uint8_t) (0xe0 + ((x >> 12) & 0x0f));
  10233. out[1] = (duk_uint8_t) (0x80 + ((x >> 6) & 0x3f));
  10234. out[2] = (duk_uint8_t) (0x80 + (x & 0x3f));
  10235. len = 3;
  10236. } else {
  10237. /*
  10238. * Unicode codepoints above U+FFFF are encoded as surrogate
  10239. * pairs here. This ensures that all CESU-8 codepoints are
  10240. * 16-bit values as expected in Ecmascript. The surrogate
  10241. * pairs always get a 3-byte encoding (each) in CESU-8.
  10242. * See: http://en.wikipedia.org/wiki/Surrogate_pair
  10243. *
  10244. * 20-bit codepoint, 10 bits (A and B) per surrogate pair:
  10245. *
  10246. * x = 0b00000000 0000AAAA AAAAAABB BBBBBBBB
  10247. * sp1 = 0b110110AA AAAAAAAA (0xd800 + ((x >> 10) & 0x3ff))
  10248. * sp2 = 0b110111BB BBBBBBBB (0xdc00 + (x & 0x3ff))
  10249. *
  10250. * Encoded into CESU-8:
  10251. *
  10252. * sp1 -> 0b11101101 (0xe0 + ((sp1 >> 12) & 0x0f))
  10253. * -> 0b1010AAAA (0x80 + ((sp1 >> 6) & 0x3f))
  10254. * -> 0b10AAAAAA (0x80 + (sp1 & 0x3f))
  10255. * sp2 -> 0b11101101 (0xe0 + ((sp2 >> 12) & 0x0f))
  10256. * -> 0b1011BBBB (0x80 + ((sp2 >> 6) & 0x3f))
  10257. * -> 0b10BBBBBB (0x80 + (sp2 & 0x3f))
  10258. *
  10259. * Note that 0x10000 must be subtracted first. The code below
  10260. * avoids the sp1, sp2 temporaries which saves around 20 bytes
  10261. * of code.
  10262. */
  10263. x -= 0x10000UL;
  10264. out[0] = (duk_uint8_t) (0xed);
  10265. out[1] = (duk_uint8_t) (0xa0 + ((x >> 16) & 0x0f));
  10266. out[2] = (duk_uint8_t) (0x80 + ((x >> 10) & 0x3f));
  10267. out[3] = (duk_uint8_t) (0xed);
  10268. out[4] = (duk_uint8_t) (0xb0 + ((x >> 6) & 0x0f));
  10269. out[5] = (duk_uint8_t) (0x80 + (x & 0x3f));
  10270. len = 6;
  10271. }
  10272. return len;
  10273. }
  10274. /* Decode helper. Return zero on error. */
  10275. DUK_INTERNAL duk_small_int_t duk_unicode_decode_xutf8(duk_hthread *thr, const duk_uint8_t **ptr, const duk_uint8_t *ptr_start, const duk_uint8_t *ptr_end, duk_ucodepoint_t *out_cp) {
  10276. const duk_uint8_t *p;
  10277. duk_uint32_t res;
  10278. duk_uint_fast8_t ch;
  10279. duk_small_int_t n;
  10280. DUK_UNREF(thr);
  10281. p = *ptr;
  10282. if (p < ptr_start || p >= ptr_end) {
  10283. goto fail;
  10284. }
  10285. /*
  10286. * UTF-8 decoder which accepts longer than standard byte sequences.
  10287. * This allows full 32-bit code points to be used.
  10288. */
  10289. ch = (duk_uint_fast8_t) (*p++);
  10290. if (ch < 0x80) {
  10291. /* 0xxx xxxx [7 bits] */
  10292. res = (duk_uint32_t) (ch & 0x7f);
  10293. n = 0;
  10294. } else if (ch < 0xc0) {
  10295. /* 10xx xxxx -> invalid */
  10296. goto fail;
  10297. } else if (ch < 0xe0) {
  10298. /* 110x xxxx 10xx xxxx [11 bits] */
  10299. res = (duk_uint32_t) (ch & 0x1f);
  10300. n = 1;
  10301. } else if (ch < 0xf0) {
  10302. /* 1110 xxxx 10xx xxxx 10xx xxxx [16 bits] */
  10303. res = (duk_uint32_t) (ch & 0x0f);
  10304. n = 2;
  10305. } else if (ch < 0xf8) {
  10306. /* 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx [21 bits] */
  10307. res = (duk_uint32_t) (ch & 0x07);
  10308. n = 3;
  10309. } else if (ch < 0xfc) {
  10310. /* 1111 10xx 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx [26 bits] */
  10311. res = (duk_uint32_t) (ch & 0x03);
  10312. n = 4;
  10313. } else if (ch < 0xfe) {
  10314. /* 1111 110x 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx [31 bits] */
  10315. res = (duk_uint32_t) (ch & 0x01);
  10316. n = 5;
  10317. } else if (ch < 0xff) {
  10318. /* 1111 1110 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx [36 bits] */
  10319. res = (duk_uint32_t) (0);
  10320. n = 6;
  10321. } else {
  10322. /* 8-byte format could be:
  10323. * 1111 1111 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx 10xx xxxx [41 bits]
  10324. *
  10325. * However, this format would not have a zero bit following the
  10326. * leading one bits and would not allow 0xFF to be used as an
  10327. * "invalid xutf-8" marker for internal keys. Further, 8-byte
  10328. * encodings (up to 41 bit code points) are not currently needed.
  10329. */
  10330. goto fail;
  10331. }
  10332. DUK_ASSERT(p >= ptr_start); /* verified at beginning */
  10333. if (p + n > ptr_end) {
  10334. /* check pointer at end */
  10335. goto fail;
  10336. }
  10337. while (n > 0) {
  10338. DUK_ASSERT(p >= ptr_start && p < ptr_end);
  10339. res = res << 6;
  10340. res += (duk_uint32_t) ((*p++) & 0x3f);
  10341. n--;
  10342. }
  10343. *ptr = p;
  10344. *out_cp = res;
  10345. return 1;
  10346. fail:
  10347. return 0;
  10348. }
  10349. /* used by e.g. duk_regexp_executor.c, string built-ins */
  10350. DUK_INTERNAL duk_ucodepoint_t duk_unicode_decode_xutf8_checked(duk_hthread *thr, const duk_uint8_t **ptr, const duk_uint8_t *ptr_start, const duk_uint8_t *ptr_end) {
  10351. duk_ucodepoint_t cp;
  10352. if (duk_unicode_decode_xutf8(thr, ptr, ptr_start, ptr_end, &cp)) {
  10353. return cp;
  10354. }
  10355. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, "utf-8 decode failed");
  10356. DUK_UNREACHABLE();
  10357. return 0;
  10358. }
  10359. /* (extended) utf-8 length without codepoint encoding validation, used
  10360. * for string interning (should probably be inlined).
  10361. */
  10362. DUK_INTERNAL duk_size_t duk_unicode_unvalidated_utf8_length(const duk_uint8_t *data, duk_size_t blen) {
  10363. const duk_uint8_t *p = data;
  10364. const duk_uint8_t *p_end = data + blen;
  10365. duk_size_t clen = 0;
  10366. while (p < p_end) {
  10367. duk_uint8_t x = *p++;
  10368. if (x < 0x80 || x >= 0xc0) {
  10369. /* 10xxxxxx = continuation chars (0x80...0xbf), above
  10370. * and below that initial bytes.
  10371. */
  10372. clen++;
  10373. }
  10374. }
  10375. return clen;
  10376. }
  10377. /*
  10378. * Unicode range matcher
  10379. *
  10380. * Matches a codepoint against a packed bitstream of character ranges.
  10381. * Used for slow path Unicode matching.
  10382. */
  10383. /* Must match src/extract_chars.py, generate_match_table3(). */
  10384. DUK_LOCAL duk_uint32_t duk__uni_decode_value(duk_bitdecoder_ctx *bd_ctx) {
  10385. duk_uint32_t t;
  10386. t = (duk_uint32_t) duk_bd_decode(bd_ctx, 4);
  10387. if (t <= 0x0eU) {
  10388. return t;
  10389. }
  10390. t = (duk_uint32_t) duk_bd_decode(bd_ctx, 8);
  10391. if (t <= 0xfdU) {
  10392. return t + 0x0f;
  10393. }
  10394. if (t == 0xfeU) {
  10395. t = (duk_uint32_t) duk_bd_decode(bd_ctx, 12);
  10396. return t + 0x0fU + 0xfeU;
  10397. } else {
  10398. t = (duk_uint32_t) duk_bd_decode(bd_ctx, 24);
  10399. return t + 0x0fU + 0xfeU + 0x1000UL;
  10400. }
  10401. }
  10402. DUK_LOCAL duk_small_int_t duk__uni_range_match(const duk_uint8_t *unitab, duk_size_t unilen, duk_codepoint_t cp) {
  10403. duk_bitdecoder_ctx bd_ctx;
  10404. duk_codepoint_t prev_re;
  10405. DUK_MEMZERO(&bd_ctx, sizeof(bd_ctx));
  10406. bd_ctx.data = (duk_uint8_t *) unitab;
  10407. bd_ctx.length = (duk_size_t) unilen;
  10408. prev_re = 0;
  10409. for (;;) {
  10410. duk_codepoint_t r1, r2;
  10411. r1 = (duk_codepoint_t) duk__uni_decode_value(&bd_ctx);
  10412. if (r1 == 0) {
  10413. break;
  10414. }
  10415. r2 = (duk_codepoint_t) duk__uni_decode_value(&bd_ctx);
  10416. r1 = prev_re + r1;
  10417. r2 = r1 + r2;
  10418. prev_re = r2;
  10419. /* [r1,r2] is the range */
  10420. DUK_DDD(DUK_DDDPRINT("duk__uni_range_match: cp=%06lx range=[0x%06lx,0x%06lx]",
  10421. (unsigned long) cp, (unsigned long) r1, (unsigned long) r2));
  10422. if (cp >= r1 && cp <= r2) {
  10423. return 1;
  10424. }
  10425. }
  10426. return 0;
  10427. }
  10428. /*
  10429. * "WhiteSpace" production check.
  10430. */
  10431. DUK_INTERNAL duk_small_int_t duk_unicode_is_whitespace(duk_codepoint_t cp) {
  10432. /*
  10433. * E5 Section 7.2 specifies six characters specifically as
  10434. * white space:
  10435. *
  10436. * 0009;<control>;Cc;0;S;;;;;N;CHARACTER TABULATION;;;;
  10437. * 000B;<control>;Cc;0;S;;;;;N;LINE TABULATION;;;;
  10438. * 000C;<control>;Cc;0;WS;;;;;N;FORM FEED (FF);;;;
  10439. * 0020;SPACE;Zs;0;WS;;;;;N;;;;;
  10440. * 00A0;NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;NON-BREAKING SPACE;;;;
  10441. * FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;;
  10442. *
  10443. * It also specifies any Unicode category 'Zs' characters as white
  10444. * space. These can be extracted with the "src/extract_chars.py" script.
  10445. * Current result:
  10446. *
  10447. * RAW OUTPUT:
  10448. * ===========
  10449. * 0020;SPACE;Zs;0;WS;;;;;N;;;;;
  10450. * 00A0;NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;NON-BREAKING SPACE;;;;
  10451. * 1680;OGHAM SPACE MARK;Zs;0;WS;;;;;N;;;;;
  10452. * 180E;MONGOLIAN VOWEL SEPARATOR;Zs;0;WS;;;;;N;;;;;
  10453. * 2000;EN QUAD;Zs;0;WS;2002;;;;N;;;;;
  10454. * 2001;EM QUAD;Zs;0;WS;2003;;;;N;;;;;
  10455. * 2002;EN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10456. * 2003;EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10457. * 2004;THREE-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10458. * 2005;FOUR-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10459. * 2006;SIX-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10460. * 2007;FIGURE SPACE;Zs;0;WS;<noBreak> 0020;;;;N;;;;;
  10461. * 2008;PUNCTUATION SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10462. * 2009;THIN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10463. * 200A;HAIR SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10464. * 202F;NARROW NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;;;;;
  10465. * 205F;MEDIUM MATHEMATICAL SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
  10466. * 3000;IDEOGRAPHIC SPACE;Zs;0;WS;<wide> 0020;;;;N;;;;;
  10467. *
  10468. * RANGES:
  10469. * =======
  10470. * 0x0020
  10471. * 0x00a0
  10472. * 0x1680
  10473. * 0x180e
  10474. * 0x2000 ... 0x200a
  10475. * 0x202f
  10476. * 0x205f
  10477. * 0x3000
  10478. *
  10479. * A manual decoder (below) is probably most compact for this.
  10480. */
  10481. duk_uint_fast8_t lo;
  10482. duk_uint_fast32_t hi;
  10483. /* cp == -1 (EOF) never matches and causes return value 0 */
  10484. lo = (duk_uint_fast8_t) (cp & 0xff);
  10485. hi = (duk_uint_fast32_t) (cp >> 8); /* does not fit into an uchar */
  10486. if (hi == 0x0000UL) {
  10487. if (lo == 0x09U || lo == 0x0bU || lo == 0x0cU ||
  10488. lo == 0x20U || lo == 0xa0U) {
  10489. return 1;
  10490. }
  10491. } else if (hi == 0x0020UL) {
  10492. if (lo <= 0x0aU || lo == 0x2fU || lo == 0x5fU) {
  10493. return 1;
  10494. }
  10495. } else if (cp == 0x1680L || cp == 0x180eL || cp == 0x3000L ||
  10496. cp == 0xfeffL) {
  10497. return 1;
  10498. }
  10499. return 0;
  10500. }
  10501. /*
  10502. * "LineTerminator" production check.
  10503. */
  10504. DUK_INTERNAL duk_small_int_t duk_unicode_is_line_terminator(duk_codepoint_t cp) {
  10505. /*
  10506. * E5 Section 7.3
  10507. *
  10508. * A LineTerminatorSequence essentially merges <CR> <LF> sequences
  10509. * into a single line terminator. This must be handled by the caller.
  10510. */
  10511. if (cp == 0x000aL || cp == 0x000dL || cp == 0x2028L ||
  10512. cp == 0x2029L) {
  10513. return 1;
  10514. }
  10515. return 0;
  10516. }
  10517. /*
  10518. * "IdentifierStart" production check.
  10519. */
  10520. DUK_INTERNAL duk_small_int_t duk_unicode_is_identifier_start(duk_codepoint_t cp) {
  10521. /*
  10522. * E5 Section 7.6:
  10523. *
  10524. * IdentifierStart:
  10525. * UnicodeLetter
  10526. * $
  10527. * _
  10528. * \ UnicodeEscapeSequence
  10529. *
  10530. * IdentifierStart production has one multi-character production:
  10531. *
  10532. * \ UnicodeEscapeSequence
  10533. *
  10534. * The '\' character is -not- matched by this function. Rather, the caller
  10535. * should decode the escape and then call this function to check whether the
  10536. * decoded character is acceptable (see discussion in E5 Section 7.6).
  10537. *
  10538. * The "UnicodeLetter" alternative of the production allows letters
  10539. * from various Unicode categories. These can be extracted with the
  10540. * "src/extract_chars.py" script.
  10541. *
  10542. * Because the result has hundreds of Unicode codepoint ranges, matching
  10543. * for any values >= 0x80 are done using a very slow range-by-range scan
  10544. * and a packed range format.
  10545. *
  10546. * The ASCII portion (codepoints 0x00 ... 0x7f) is fast-pathed below because
  10547. * it matters the most. The ASCII related ranges of IdentifierStart are:
  10548. *
  10549. * 0x0041 ... 0x005a ['A' ... 'Z']
  10550. * 0x0061 ... 0x007a ['a' ... 'z']
  10551. * 0x0024 ['$']
  10552. * 0x005f ['_']
  10553. */
  10554. /* ASCII (and EOF) fast path -- quick accept and reject */
  10555. if (cp <= 0x7fL) {
  10556. if ((cp >= 'a' && cp <= 'z') ||
  10557. (cp >= 'A' && cp <= 'Z') ||
  10558. cp == '_' || cp == '$') {
  10559. return 1;
  10560. }
  10561. return 0;
  10562. }
  10563. /* Non-ASCII slow path (range-by-range linear comparison), very slow */
  10564. #ifdef DUK_USE_SOURCE_NONBMP
  10565. if (duk__uni_range_match(duk_unicode_ids_noa,
  10566. (duk_size_t) sizeof(duk_unicode_ids_noa),
  10567. (duk_codepoint_t) cp)) {
  10568. return 1;
  10569. }
  10570. return 0;
  10571. #else
  10572. if (cp < 0x10000L) {
  10573. if (duk__uni_range_match(duk_unicode_ids_noabmp,
  10574. sizeof(duk_unicode_ids_noabmp),
  10575. (duk_codepoint_t) cp)) {
  10576. return 1;
  10577. }
  10578. return 0;
  10579. } else {
  10580. /* without explicit non-BMP support, assume non-BMP characters
  10581. * are always accepted as identifier characters.
  10582. */
  10583. return 1;
  10584. }
  10585. #endif
  10586. }
  10587. /*
  10588. * "IdentifierPart" production check.
  10589. */
  10590. DUK_INTERNAL duk_small_int_t duk_unicode_is_identifier_part(duk_codepoint_t cp) {
  10591. /*
  10592. * E5 Section 7.6:
  10593. *
  10594. * IdentifierPart:
  10595. * IdentifierStart
  10596. * UnicodeCombiningMark
  10597. * UnicodeDigit
  10598. * UnicodeConnectorPunctuation
  10599. * <ZWNJ> [U+200C]
  10600. * <ZWJ> [U+200D]
  10601. *
  10602. * IdentifierPart production has one multi-character production
  10603. * as part of its IdentifierStart alternative. The '\' character
  10604. * of an escape sequence is not matched here, see discussion in
  10605. * duk_unicode_is_identifier_start().
  10606. *
  10607. * To match non-ASCII characters (codepoints >= 0x80), a very slow
  10608. * linear range-by-range scan is used. The codepoint is first compared
  10609. * to the IdentifierStart ranges, and if it doesn't match, then to a
  10610. * set consisting of code points in IdentifierPart but not in
  10611. * IdentifierStart. This is done to keep the unicode range data small,
  10612. * at the expense of speed.
  10613. *
  10614. * The ASCII fast path consists of:
  10615. *
  10616. * 0x0030 ... 0x0039 ['0' ... '9', UnicodeDigit]
  10617. * 0x0041 ... 0x005a ['A' ... 'Z', IdentifierStart]
  10618. * 0x0061 ... 0x007a ['a' ... 'z', IdentifierStart]
  10619. * 0x0024 ['$', IdentifierStart]
  10620. * 0x005f ['_', IdentifierStart and
  10621. * UnicodeConnectorPunctuation]
  10622. *
  10623. * UnicodeCombiningMark has no code points <= 0x7f.
  10624. *
  10625. * The matching code reuses the "identifier start" tables, and then
  10626. * consults a separate range set for characters in "identifier part"
  10627. * but not in "identifier start". These can be extracted with the
  10628. * "src/extract_chars.py" script.
  10629. *
  10630. * UnicodeCombiningMark -> categories Mn, Mc
  10631. * UnicodeDigit -> categories Nd
  10632. * UnicodeConnectorPunctuation -> categories Pc
  10633. */
  10634. /* ASCII (and EOF) fast path -- quick accept and reject */
  10635. if (cp <= 0x7fL) {
  10636. if ((cp >= 'a' && cp <= 'z') ||
  10637. (cp >= 'A' && cp <= 'Z') ||
  10638. (cp >= '0' && cp <= '9') ||
  10639. cp == '_' || cp == '$') {
  10640. return 1;
  10641. }
  10642. return 0;
  10643. }
  10644. /* Non-ASCII slow path (range-by-range linear comparison), very slow */
  10645. #ifdef DUK_USE_SOURCE_NONBMP
  10646. if (duk__uni_range_match(duk_unicode_ids_noa,
  10647. sizeof(duk_unicode_ids_noa),
  10648. (duk_codepoint_t) cp) ||
  10649. duk__uni_range_match(duk_unicode_idp_m_ids_noa,
  10650. sizeof(duk_unicode_idp_m_ids_noa),
  10651. (duk_codepoint_t) cp)) {
  10652. return 1;
  10653. }
  10654. return 0;
  10655. #else
  10656. if (cp < 0x10000L) {
  10657. if (duk__uni_range_match(duk_unicode_ids_noabmp,
  10658. sizeof(duk_unicode_ids_noabmp),
  10659. (duk_codepoint_t) cp) ||
  10660. duk__uni_range_match(duk_unicode_idp_m_ids_noabmp,
  10661. sizeof(duk_unicode_idp_m_ids_noabmp),
  10662. (duk_codepoint_t) cp)) {
  10663. return 1;
  10664. }
  10665. return 0;
  10666. } else {
  10667. /* without explicit non-BMP support, assume non-BMP characters
  10668. * are always accepted as identifier characters.
  10669. */
  10670. return 1;
  10671. }
  10672. #endif
  10673. }
  10674. /*
  10675. * Unicode letter check.
  10676. */
  10677. DUK_INTERNAL duk_small_int_t duk_unicode_is_letter(duk_codepoint_t cp) {
  10678. /*
  10679. * Unicode letter is now taken to be the categories:
  10680. *
  10681. * Lu, Ll, Lt, Lm, Lo
  10682. *
  10683. * (Not sure if this is exactly correct.)
  10684. *
  10685. * The ASCII fast path consists of:
  10686. *
  10687. * 0x0041 ... 0x005a ['A' ... 'Z']
  10688. * 0x0061 ... 0x007a ['a' ... 'z']
  10689. */
  10690. /* ASCII (and EOF) fast path -- quick accept and reject */
  10691. if (cp <= 0x7fL) {
  10692. if ((cp >= 'a' && cp <= 'z') ||
  10693. (cp >= 'A' && cp <= 'Z')) {
  10694. return 1;
  10695. }
  10696. return 0;
  10697. }
  10698. /* Non-ASCII slow path (range-by-range linear comparison), very slow */
  10699. #ifdef DUK_USE_SOURCE_NONBMP
  10700. if (duk__uni_range_match(duk_unicode_ids_noa,
  10701. sizeof(duk_unicode_ids_noa),
  10702. (duk_codepoint_t) cp) &&
  10703. !duk__uni_range_match(duk_unicode_ids_m_let_noa,
  10704. sizeof(duk_unicode_ids_m_let_noa),
  10705. (duk_codepoint_t) cp)) {
  10706. return 1;
  10707. }
  10708. return 0;
  10709. #else
  10710. if (cp < 0x10000L) {
  10711. if (duk__uni_range_match(duk_unicode_ids_noabmp,
  10712. sizeof(duk_unicode_ids_noabmp),
  10713. (duk_codepoint_t) cp) &&
  10714. !duk__uni_range_match(duk_unicode_ids_m_let_noabmp,
  10715. sizeof(duk_unicode_ids_m_let_noabmp),
  10716. (duk_codepoint_t) cp)) {
  10717. return 1;
  10718. }
  10719. return 0;
  10720. } else {
  10721. /* without explicit non-BMP support, assume non-BMP characters
  10722. * are always accepted as letters.
  10723. */
  10724. return 1;
  10725. }
  10726. #endif
  10727. }
  10728. /*
  10729. * Complex case conversion helper which decodes a bit-packed conversion
  10730. * control stream generated by unicode/extract_caseconv.py. The conversion
  10731. * is very slow because it runs through the conversion data in a linear
  10732. * fashion to save space (which is why ASCII characters have a special
  10733. * fast path before arriving here).
  10734. *
  10735. * The particular bit counts etc have been determined experimentally to
  10736. * be small but still sufficient, and must match the Python script
  10737. * (src/extract_caseconv.py).
  10738. *
  10739. * The return value is the case converted codepoint or -1 if the conversion
  10740. * results in multiple characters (this is useful for regexp Canonicalization
  10741. * operation). If 'buf' is not NULL, the result codepoint(s) are also
  10742. * appended to the hbuffer.
  10743. *
  10744. * Context and locale specific rules must be checked before consulting
  10745. * this function.
  10746. */
  10747. DUK_LOCAL
  10748. duk_codepoint_t duk__slow_case_conversion(duk_hthread *thr,
  10749. duk_hbuffer_dynamic *buf,
  10750. duk_codepoint_t cp,
  10751. duk_bitdecoder_ctx *bd_ctx) {
  10752. duk_small_int_t skip = 0;
  10753. duk_small_int_t n;
  10754. duk_small_int_t t;
  10755. duk_small_int_t count;
  10756. duk_codepoint_t tmp_cp;
  10757. duk_codepoint_t start_i;
  10758. duk_codepoint_t start_o;
  10759. DUK_DDD(DUK_DDDPRINT("slow case conversion for codepoint: %ld", (long) cp));
  10760. /* range conversion with a "skip" */
  10761. DUK_DDD(DUK_DDDPRINT("checking ranges"));
  10762. for (;;) {
  10763. skip++;
  10764. n = (duk_small_int_t) duk_bd_decode(bd_ctx, 6);
  10765. if (n == 0x3f) {
  10766. /* end marker */
  10767. break;
  10768. }
  10769. DUK_DDD(DUK_DDDPRINT("skip=%ld, n=%ld", (long) skip, (long) n));
  10770. while (n--) {
  10771. start_i = (duk_codepoint_t) duk_bd_decode(bd_ctx, 16);
  10772. start_o = (duk_codepoint_t) duk_bd_decode(bd_ctx, 16);
  10773. count = (duk_small_int_t) duk_bd_decode(bd_ctx, 7);
  10774. DUK_DDD(DUK_DDDPRINT("range: start_i=%ld, start_o=%ld, count=%ld, skip=%ld",
  10775. (long) start_i, (long) start_o, (long) count, (long) skip));
  10776. if (cp >= start_i) {
  10777. tmp_cp = cp - start_i; /* always >= 0 */
  10778. if (tmp_cp < (duk_codepoint_t) count * (duk_codepoint_t) skip &&
  10779. (tmp_cp % (duk_codepoint_t) skip) == 0) {
  10780. DUK_DDD(DUK_DDDPRINT("range matches input codepoint"));
  10781. cp = start_o + tmp_cp;
  10782. goto single;
  10783. }
  10784. }
  10785. }
  10786. }
  10787. /* 1:1 conversion */
  10788. n = (duk_small_int_t) duk_bd_decode(bd_ctx, 6);
  10789. DUK_DDD(DUK_DDDPRINT("checking 1:1 conversions (count %ld)", (long) n));
  10790. while (n--) {
  10791. start_i = (duk_codepoint_t) duk_bd_decode(bd_ctx, 16);
  10792. start_o = (duk_codepoint_t) duk_bd_decode(bd_ctx, 16);
  10793. DUK_DDD(DUK_DDDPRINT("1:1 conversion %ld -> %ld", (long) start_i, (long) start_o));
  10794. if (cp == start_i) {
  10795. DUK_DDD(DUK_DDDPRINT("1:1 matches input codepoint"));
  10796. cp = start_o;
  10797. goto single;
  10798. }
  10799. }
  10800. /* complex, multicharacter conversion */
  10801. n = (duk_small_int_t) duk_bd_decode(bd_ctx, 7);
  10802. DUK_DDD(DUK_DDDPRINT("checking 1:n conversions (count %ld)", (long) n));
  10803. while (n--) {
  10804. start_i = (duk_codepoint_t) duk_bd_decode(bd_ctx, 16);
  10805. t = (duk_small_int_t) duk_bd_decode(bd_ctx, 2);
  10806. DUK_DDD(DUK_DDDPRINT("1:n conversion %ld -> %ld chars", (long) start_i, (long) t));
  10807. if (cp == start_i) {
  10808. DUK_DDD(DUK_DDDPRINT("1:n matches input codepoint"));
  10809. if (buf) {
  10810. while (t--) {
  10811. tmp_cp = (duk_codepoint_t) duk_bd_decode(bd_ctx, 16);
  10812. DUK_ASSERT(buf != NULL);
  10813. duk_hbuffer_append_xutf8(thr, buf, (duk_ucodepoint_t) tmp_cp);
  10814. }
  10815. }
  10816. return -1;
  10817. } else {
  10818. while (t--) {
  10819. (void) duk_bd_decode(bd_ctx, 16);
  10820. }
  10821. }
  10822. }
  10823. /* default: no change */
  10824. DUK_DDD(DUK_DDDPRINT("no rule matches, output is same as input"));
  10825. /* fall through */
  10826. single:
  10827. if (buf) {
  10828. duk_hbuffer_append_xutf8(thr, buf, cp);
  10829. }
  10830. return cp;
  10831. }
  10832. /*
  10833. * Case conversion helper, with context/local sensitivity.
  10834. * For proper case conversion, one needs to know the character
  10835. * and the preceding and following characters, as well as
  10836. * locale/language.
  10837. */
  10838. /* XXX: add 'language' argument when locale/language sensitive rule
  10839. * support added.
  10840. */
  10841. DUK_LOCAL
  10842. duk_codepoint_t duk__case_transform_helper(duk_hthread *thr,
  10843. duk_hbuffer_dynamic *buf,
  10844. duk_codepoint_t cp,
  10845. duk_codepoint_t prev,
  10846. duk_codepoint_t next,
  10847. duk_bool_t uppercase) {
  10848. duk_bitdecoder_ctx bd_ctx;
  10849. /* fast path for ASCII */
  10850. if (cp < 0x80L) {
  10851. /* XXX: there are language sensitive rules for the ASCII range.
  10852. * If/when language/locale support is implemented, they need to
  10853. * be implemented here for the fast path. There are no context
  10854. * sensitive rules for ASCII range.
  10855. */
  10856. if (uppercase) {
  10857. if (cp >= 'a' && cp <= 'z') {
  10858. cp = cp - 'a' + 'A';
  10859. }
  10860. } else {
  10861. if (cp >= 'A' && cp <= 'Z') {
  10862. cp = cp - 'A' + 'a';
  10863. }
  10864. }
  10865. goto singlechar;
  10866. }
  10867. /* context and locale specific rules which cannot currently be represented
  10868. * in the caseconv bitstream: hardcoded rules in C
  10869. */
  10870. if (uppercase) {
  10871. /* XXX: turkish / azeri */
  10872. } else {
  10873. /*
  10874. * Final sigma context specific rule. This is a rather tricky
  10875. * rule and this handling is probably not 100% correct now.
  10876. * The rule is not locale/language specific so it is supported.
  10877. */
  10878. if (cp == 0x03a3L && /* U+03A3 = GREEK CAPITAL LETTER SIGMA */
  10879. duk_unicode_is_letter(prev) && /* prev exists and is not a letter */
  10880. !duk_unicode_is_letter(next)) { /* next does not exist or next is not a letter */
  10881. /* Capital sigma occurred at "end of word", lowercase to
  10882. * U+03C2 = GREEK SMALL LETTER FINAL SIGMA. Otherwise
  10883. * fall through and let the normal rules lowercase it to
  10884. * U+03C3 = GREEK SMALL LETTER SIGMA.
  10885. */
  10886. cp = 0x03c2L;
  10887. goto singlechar;
  10888. }
  10889. /* XXX: lithuanian not implemented */
  10890. /* XXX: lithuanian, explicit dot rules */
  10891. /* XXX: turkish / azeri, lowercase rules */
  10892. }
  10893. /* 1:1 or special conversions, but not locale/context specific: script generated rules */
  10894. DUK_MEMZERO(&bd_ctx, sizeof(bd_ctx));
  10895. if (uppercase) {
  10896. bd_ctx.data = (duk_uint8_t *) duk_unicode_caseconv_uc;
  10897. bd_ctx.length = (duk_size_t) sizeof(duk_unicode_caseconv_uc);
  10898. } else {
  10899. bd_ctx.data = (duk_uint8_t *) duk_unicode_caseconv_lc;
  10900. bd_ctx.length = (duk_size_t) sizeof(duk_unicode_caseconv_lc);
  10901. }
  10902. return duk__slow_case_conversion(thr, buf, cp, &bd_ctx);
  10903. singlechar:
  10904. if (buf) {
  10905. duk_hbuffer_append_xutf8(thr, buf, cp);
  10906. }
  10907. return cp;
  10908. /* unused now, not needed until Turkish/Azeri */
  10909. #if 0
  10910. nochar:
  10911. return -1;
  10912. #endif
  10913. }
  10914. /*
  10915. * Replace valstack top with case converted version.
  10916. */
  10917. DUK_INTERNAL void duk_unicode_case_convert_string(duk_hthread *thr, duk_small_int_t uppercase) {
  10918. duk_context *ctx = (duk_context *) thr;
  10919. duk_hstring *h_input;
  10920. duk_hbuffer_dynamic *h_buf;
  10921. const duk_uint8_t *p, *p_start, *p_end;
  10922. duk_codepoint_t prev, curr, next;
  10923. h_input = duk_require_hstring(ctx, -1);
  10924. DUK_ASSERT(h_input != NULL);
  10925. /* XXX: should init the buffer with a spare of at least h_input->blen
  10926. * to avoid unnecessary growth steps.
  10927. */
  10928. duk_push_dynamic_buffer(ctx, 0);
  10929. h_buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  10930. DUK_ASSERT(h_buf != NULL);
  10931. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(h_buf));
  10932. /* [ ... input buffer ] */
  10933. p_start = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h_input);
  10934. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_input);
  10935. p = p_start;
  10936. prev = -1; DUK_UNREF(prev);
  10937. curr = -1;
  10938. next = -1;
  10939. for (;;) {
  10940. prev = curr;
  10941. curr = next;
  10942. next = -1;
  10943. if (p < p_end) {
  10944. next = (int) duk_unicode_decode_xutf8_checked(thr, &p, p_start, p_end);
  10945. } else {
  10946. /* end of input and last char has been processed */
  10947. if (curr < 0) {
  10948. break;
  10949. }
  10950. }
  10951. /* on first round, skip */
  10952. if (curr >= 0) {
  10953. /* may generate any number of output codepoints */
  10954. duk__case_transform_helper(thr,
  10955. h_buf,
  10956. (duk_codepoint_t) curr,
  10957. prev,
  10958. next,
  10959. uppercase);
  10960. }
  10961. }
  10962. duk_to_string(ctx, -1); /* invalidates h_buf pointer */
  10963. duk_remove(ctx, -2);
  10964. }
  10965. #ifdef DUK_USE_REGEXP_SUPPORT
  10966. /*
  10967. * Canonicalize() abstract operation needed for canonicalization of individual
  10968. * codepoints during regexp compilation and execution, see E5 Section 15.10.2.8.
  10969. * Note that codepoints are canonicalized one character at a time, so no context
  10970. * specific rules can apply. Locale specific rules can apply, though.
  10971. */
  10972. DUK_INTERNAL duk_codepoint_t duk_unicode_re_canonicalize_char(duk_hthread *thr, duk_codepoint_t cp) {
  10973. duk_codepoint_t y;
  10974. y = duk__case_transform_helper(thr,
  10975. NULL, /* buf */
  10976. cp, /* curr char */
  10977. -1, /* prev char */
  10978. -1, /* next char */
  10979. 1); /* uppercase */
  10980. if ((y < 0) || (cp >= 0x80 && y < 0x80)) {
  10981. /* multiple codepoint conversion or non-ASCII mapped to ASCII
  10982. * --> leave as is.
  10983. */
  10984. return cp;
  10985. }
  10986. return y;
  10987. }
  10988. /*
  10989. * E5 Section 15.10.2.6 "IsWordChar" abstract operation. Assume
  10990. * x < 0 for characters read outside the string.
  10991. */
  10992. DUK_INTERNAL duk_small_int_t duk_unicode_re_is_wordchar(duk_codepoint_t x) {
  10993. /*
  10994. * Note: the description in E5 Section 15.10.2.6 has a typo, it
  10995. * contains 'A' twice and lacks 'a'; the intent is [0-9a-zA-Z_].
  10996. */
  10997. if ((x >= '0' && x <= '9') ||
  10998. (x >= 'a' && x <= 'z') ||
  10999. (x >= 'A' && x <= 'Z') ||
  11000. (x == '_')) {
  11001. return 1;
  11002. }
  11003. return 0;
  11004. }
  11005. /*
  11006. * Regexp range tables
  11007. */
  11008. /* exposed because lexer needs these too */
  11009. DUK_INTERNAL duk_uint16_t duk_unicode_re_ranges_digit[2] = {
  11010. (duk_uint16_t) 0x0030UL, (duk_uint16_t) 0x0039UL,
  11011. };
  11012. DUK_INTERNAL duk_uint16_t duk_unicode_re_ranges_white[22] = {
  11013. (duk_uint16_t) 0x0009UL, (duk_uint16_t) 0x000DUL,
  11014. (duk_uint16_t) 0x0020UL, (duk_uint16_t) 0x0020UL,
  11015. (duk_uint16_t) 0x00A0UL, (duk_uint16_t) 0x00A0UL,
  11016. (duk_uint16_t) 0x1680UL, (duk_uint16_t) 0x1680UL,
  11017. (duk_uint16_t) 0x180EUL, (duk_uint16_t) 0x180EUL,
  11018. (duk_uint16_t) 0x2000UL, (duk_uint16_t) 0x200AUL,
  11019. (duk_uint16_t) 0x2028UL, (duk_uint16_t) 0x2029UL,
  11020. (duk_uint16_t) 0x202FUL, (duk_uint16_t) 0x202FUL,
  11021. (duk_uint16_t) 0x205FUL, (duk_uint16_t) 0x205FUL,
  11022. (duk_uint16_t) 0x3000UL, (duk_uint16_t) 0x3000UL,
  11023. (duk_uint16_t) 0xFEFFUL, (duk_uint16_t) 0xFEFFUL,
  11024. };
  11025. DUK_INTERNAL duk_uint16_t duk_unicode_re_ranges_wordchar[8] = {
  11026. (duk_uint16_t) 0x0030UL, (duk_uint16_t) 0x0039UL,
  11027. (duk_uint16_t) 0x0041UL, (duk_uint16_t) 0x005AUL,
  11028. (duk_uint16_t) 0x005FUL, (duk_uint16_t) 0x005FUL,
  11029. (duk_uint16_t) 0x0061UL, (duk_uint16_t) 0x007AUL,
  11030. };
  11031. DUK_INTERNAL duk_uint16_t duk_unicode_re_ranges_not_digit[4] = {
  11032. (duk_uint16_t) 0x0000UL, (duk_uint16_t) 0x002FUL,
  11033. (duk_uint16_t) 0x003AUL, (duk_uint16_t) 0xFFFFUL,
  11034. };
  11035. DUK_INTERNAL duk_uint16_t duk_unicode_re_ranges_not_white[24] = {
  11036. (duk_uint16_t) 0x0000UL, (duk_uint16_t) 0x0008UL,
  11037. (duk_uint16_t) 0x000EUL, (duk_uint16_t) 0x001FUL,
  11038. (duk_uint16_t) 0x0021UL, (duk_uint16_t) 0x009FUL,
  11039. (duk_uint16_t) 0x00A1UL, (duk_uint16_t) 0x167FUL,
  11040. (duk_uint16_t) 0x1681UL, (duk_uint16_t) 0x180DUL,
  11041. (duk_uint16_t) 0x180FUL, (duk_uint16_t) 0x1FFFUL,
  11042. (duk_uint16_t) 0x200BUL, (duk_uint16_t) 0x2027UL,
  11043. (duk_uint16_t) 0x202AUL, (duk_uint16_t) 0x202EUL,
  11044. (duk_uint16_t) 0x2030UL, (duk_uint16_t) 0x205EUL,
  11045. (duk_uint16_t) 0x2060UL, (duk_uint16_t) 0x2FFFUL,
  11046. (duk_uint16_t) 0x3001UL, (duk_uint16_t) 0xFEFEUL,
  11047. (duk_uint16_t) 0xFF00UL, (duk_uint16_t) 0xFFFFUL,
  11048. };
  11049. DUK_INTERNAL duk_uint16_t duk_unicode_re_ranges_not_wordchar[10] = {
  11050. (duk_uint16_t) 0x0000UL, (duk_uint16_t) 0x002FUL,
  11051. (duk_uint16_t) 0x003AUL, (duk_uint16_t) 0x0040UL,
  11052. (duk_uint16_t) 0x005BUL, (duk_uint16_t) 0x005EUL,
  11053. (duk_uint16_t) 0x0060UL, (duk_uint16_t) 0x0060UL,
  11054. (duk_uint16_t) 0x007BUL, (duk_uint16_t) 0xFFFFUL,
  11055. };
  11056. #endif /* DUK_USE_REGEXP_SUPPORT */
  11057. #line 1 "duk_util_misc.c"
  11058. /*
  11059. * Misc util stuff
  11060. */
  11061. /* include removed: duk_internal.h */
  11062. /*
  11063. * Lowercase digits for radix values 2 to 36. Also doubles as lowercase
  11064. * hex nybble table.
  11065. */
  11066. DUK_INTERNAL duk_uint8_t duk_lc_digits[36] = {
  11067. '0', '1', '2', '3', '4', '5', '6', '7',
  11068. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
  11069. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  11070. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  11071. 'w', 'x', 'y', 'z'
  11072. };
  11073. DUK_INTERNAL duk_uint8_t duk_uc_nybbles[16] = {
  11074. '0', '1', '2', '3', '4', '5', '6', '7',
  11075. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  11076. };
  11077. /*
  11078. * Table for decoding ASCII hex digits, -1 if invalid.
  11079. */
  11080. DUK_INTERNAL duk_int8_t duk_hex_dectab[256] = {
  11081. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00-0x0f */
  11082. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10-0x1f */
  11083. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x20-0x2f */
  11084. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 0x30-0x3f */
  11085. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x40-0x4f */
  11086. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x50-0x5f */
  11087. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x60-0x6f */
  11088. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x70-0x7f */
  11089. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x80-0x8f */
  11090. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x90-0x9f */
  11091. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xa0-0xaf */
  11092. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xb0-0xbf */
  11093. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xc0-0xcf */
  11094. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xd0-0xdf */
  11095. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xe0-0xef */
  11096. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 /* 0xf0-0xff */
  11097. };
  11098. /*
  11099. * Arbitrary byteswap for potentially unaligned values
  11100. *
  11101. * Used to byteswap pointers e.g. in debugger code.
  11102. */
  11103. #if defined(DUK_USE_DEBUGGER_SUPPORT) /* For now only needed by the debugger. */
  11104. DUK_INTERNAL void duk_byteswap_bytes(duk_uint8_t *p, duk_small_uint_t len) {
  11105. duk_uint8_t tmp;
  11106. duk_uint8_t *q = p + len - 1;
  11107. while (p - q < 0) {
  11108. tmp = *p;
  11109. *p = *q;
  11110. *q = tmp;
  11111. p++;
  11112. q--;
  11113. }
  11114. }
  11115. #endif
  11116. #line 1 "duk_util_hashprime.c"
  11117. /*
  11118. * Round a number upwards to a prime (not usually the nearest one).
  11119. *
  11120. * Uses a table of successive 32-bit primes whose ratio is roughly
  11121. * constant. This keeps the relative upwards 'rounding error' bounded
  11122. * and the data size small. A simple 'predict-correct' compression is
  11123. * used to compress primes to one byte per prime. See genhashsizes.py
  11124. * for details.
  11125. *
  11126. * The minimum prime returned here must be coordinated with the possible
  11127. * probe sequence steps in duk_hobject and duk_heap stringtable.
  11128. */
  11129. /* include removed: duk_internal.h */
  11130. /* Awkward inclusion condition: drop out of compilation if not needed by any
  11131. * call site: object hash part or probing stringtable.
  11132. */
  11133. #if defined(DUK_USE_HOBJECT_HASH_PART) || defined(DUK_USE_STRTAB_PROBE)
  11134. /* hash size ratio goal, must match genhashsizes.py */
  11135. #define DUK__HASH_SIZE_RATIO 1177 /* floor(1.15 * (1 << 10)) */
  11136. /* prediction corrections for prime list (see genhashsizes.py) */
  11137. DUK_LOCAL const duk_int8_t duk__hash_size_corrections[] = {
  11138. 17, /* minimum prime */
  11139. 4, 3, 4, 1, 4, 1, 1, 2, 2, 2, 2, 1, 6, 6, 9, 5, 1, 2, 2, 5, 1, 3, 3, 3,
  11140. 5, 4, 4, 2, 4, 8, 3, 4, 23, 2, 4, 7, 8, 11, 2, 12, 15, 10, 1, 1, 5, 1, 5,
  11141. 8, 9, 17, 14, 10, 7, 5, 2, 46, 21, 1, 9, 9, 4, 4, 10, 23, 36, 6, 20, 29,
  11142. 18, 6, 19, 21, 16, 11, 5, 5, 48, 9, 1, 39, 14, 8, 4, 29, 9, 1, 15, 48, 12,
  11143. 22, 6, 15, 27, 4, 2, 17, 28, 8, 9, 4, 5, 8, 3, 3, 8, 37, 11, 15, 8, 30,
  11144. 43, 6, 33, 41, 5, 20, 32, 41, 38, 24, 77, 14, 19, 11, 4, 35, 18, 19, 41,
  11145. 10, 23, 16, 9, 2,
  11146. -1
  11147. };
  11148. /* probe steps (see genhashsizes.py), currently assumed to be 32 entries long
  11149. * (DUK_UTIL_GET_HASH_PROBE_STEP macro).
  11150. */
  11151. DUK_INTERNAL duk_uint8_t duk_util_probe_steps[32] = {
  11152. 2, 3, 5, 7, 11, 13, 19, 31, 41, 47, 59, 67, 73, 79, 89, 101, 103, 107,
  11153. 109, 127, 137, 139, 149, 157, 163, 167, 173, 181, 191, 193, 197, 199
  11154. };
  11155. DUK_INTERNAL duk_uint32_t duk_util_get_hash_prime(duk_uint32_t size) {
  11156. const duk_int8_t *p = duk__hash_size_corrections;
  11157. duk_uint32_t curr;
  11158. curr = (duk_uint32_t) *p++;
  11159. for (;;) {
  11160. duk_small_int_t t = (duk_small_int_t) *p++;
  11161. if (t < 0) {
  11162. /* may happen if size is very close to 2^32-1 */
  11163. break;
  11164. }
  11165. /* prediction: portable variant using doubles if 64-bit values not available */
  11166. #ifdef DUK_USE_64BIT_OPS
  11167. curr = (duk_uint32_t) ((((duk_uint64_t) curr) * ((duk_uint64_t) DUK__HASH_SIZE_RATIO)) >> 10);
  11168. #else
  11169. /* 32-bit x 11-bit = 43-bit, fits accurately into a double */
  11170. curr = (duk_uint32_t) DUK_FLOOR(((double) curr) * ((double) DUK__HASH_SIZE_RATIO) / 1024.0);
  11171. #endif
  11172. /* correction */
  11173. curr += t;
  11174. DUK_DDD(DUK_DDDPRINT("size=%ld, curr=%ld", (long) size, (long) curr));
  11175. if (curr >= size) {
  11176. return curr;
  11177. }
  11178. }
  11179. return 0;
  11180. }
  11181. #endif /* DUK_USE_HOBJECT_HASH_PART || DUK_USE_STRTAB_PROBE */
  11182. #line 1 "duk_hobject_class.c"
  11183. /*
  11184. * Hobject Ecmascript [[Class]].
  11185. */
  11186. /* include removed: duk_internal.h */
  11187. /* Maybe better to check these elsewhere */
  11188. #if (DUK_STRIDX_UC_ARGUMENTS > 255)
  11189. #error constant too large
  11190. #endif
  11191. #if (DUK_STRIDX_ARRAY > 255)
  11192. #error constant too large
  11193. #endif
  11194. #if (DUK_STRIDX_UC_BOOLEAN > 255)
  11195. #error constant too large
  11196. #endif
  11197. #if (DUK_STRIDX_DATE > 255)
  11198. #error constant too large
  11199. #endif
  11200. #if (DUK_STRIDX_UC_ERROR > 255)
  11201. #error constant too large
  11202. #endif
  11203. #if (DUK_STRIDX_UC_FUNCTION > 255)
  11204. #error constant too large
  11205. #endif
  11206. #if (DUK_STRIDX_JSON > 255)
  11207. #error constant too large
  11208. #endif
  11209. #if (DUK_STRIDX_MATH > 255)
  11210. #error constant too large
  11211. #endif
  11212. #if (DUK_STRIDX_UC_NUMBER > 255)
  11213. #error constant too large
  11214. #endif
  11215. #if (DUK_STRIDX_UC_OBJECT > 255)
  11216. #error constant too large
  11217. #endif
  11218. #if (DUK_STRIDX_REG_EXP > 255)
  11219. #error constant too large
  11220. #endif
  11221. #if (DUK_STRIDX_UC_STRING > 255)
  11222. #error constant too large
  11223. #endif
  11224. #if (DUK_STRIDX_GLOBAL > 255)
  11225. #error constant too large
  11226. #endif
  11227. #if (DUK_STRIDX_EMPTY_STRING > 255)
  11228. #error constant too large
  11229. #endif
  11230. /* Note: assumes that these string indexes are 8-bit, genstrings.py must ensure that */
  11231. DUK_INTERNAL duk_uint8_t duk_class_number_to_stridx[32] = {
  11232. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11233. DUK_STRIDX_UC_ARGUMENTS,
  11234. DUK_STRIDX_ARRAY,
  11235. DUK_STRIDX_UC_BOOLEAN,
  11236. DUK_STRIDX_DATE,
  11237. DUK_STRIDX_UC_ERROR,
  11238. DUK_STRIDX_UC_FUNCTION,
  11239. DUK_STRIDX_JSON,
  11240. DUK_STRIDX_MATH,
  11241. DUK_STRIDX_UC_NUMBER,
  11242. DUK_STRIDX_UC_OBJECT,
  11243. DUK_STRIDX_REG_EXP,
  11244. DUK_STRIDX_UC_STRING,
  11245. DUK_STRIDX_GLOBAL,
  11246. DUK_STRIDX_OBJ_ENV,
  11247. DUK_STRIDX_DEC_ENV,
  11248. DUK_STRIDX_UC_BUFFER,
  11249. DUK_STRIDX_UC_POINTER,
  11250. DUK_STRIDX_UC_THREAD, /* UNUSED, intentionally empty */
  11251. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11252. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11253. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11254. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11255. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11256. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11257. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11258. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11259. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11260. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11261. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11262. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11263. DUK_STRIDX_EMPTY_STRING, /* UNUSED, intentionally empty */
  11264. };
  11265. #line 1 "duk_alloc_default.c"
  11266. /*
  11267. * Default allocation functions.
  11268. *
  11269. * Assumes behavior such as malloc allowing zero size, yielding
  11270. * a NULL or a unique pointer which is a no-op for free.
  11271. */
  11272. /* include removed: duk_internal.h */
  11273. DUK_INTERNAL void *duk_default_alloc_function(void *udata, duk_size_t size) {
  11274. void *res;
  11275. DUK_UNREF(udata);
  11276. res = DUK_ANSI_MALLOC(size);
  11277. DUK_DDD(DUK_DDDPRINT("default alloc function: %lu -> %p",
  11278. (unsigned long) size, (void *) res));
  11279. return res;
  11280. }
  11281. DUK_INTERNAL void *duk_default_realloc_function(void *udata, void *ptr, duk_size_t newsize) {
  11282. void *res;
  11283. DUK_UNREF(udata);
  11284. res = DUK_ANSI_REALLOC(ptr, newsize);
  11285. DUK_DDD(DUK_DDDPRINT("default realloc function: %p %lu -> %p",
  11286. (void *) ptr, (unsigned long) newsize, (void *) res));
  11287. return res;
  11288. }
  11289. DUK_INTERNAL void duk_default_free_function(void *udata, void *ptr) {
  11290. DUK_DDD(DUK_DDDPRINT("default free function: %p", (void *) ptr));
  11291. DUK_UNREF(udata);
  11292. DUK_ANSI_FREE(ptr);
  11293. }
  11294. #line 1 "duk_api_buffer.c"
  11295. /*
  11296. * Buffer
  11297. */
  11298. /* include removed: duk_internal.h */
  11299. DUK_EXTERNAL void *duk_resize_buffer(duk_context *ctx, duk_idx_t index, duk_size_t new_size) {
  11300. duk_hthread *thr = (duk_hthread *) ctx;
  11301. duk_hbuffer_dynamic *h;
  11302. DUK_ASSERT(ctx != NULL);
  11303. h = (duk_hbuffer_dynamic *) duk_require_hbuffer(ctx, index);
  11304. DUK_ASSERT(h != NULL);
  11305. if (!DUK_HBUFFER_HAS_DYNAMIC(h)) {
  11306. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_BUFFER_NOT_DYNAMIC);
  11307. }
  11308. /* maximum size check is handled by callee */
  11309. duk_hbuffer_resize(thr, h, new_size, new_size); /* snug */
  11310. return DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, h);
  11311. }
  11312. #line 1 "duk_api_call.c"
  11313. /*
  11314. * Calls.
  11315. *
  11316. * Protected variants should avoid ever throwing an error.
  11317. */
  11318. /* include removed: duk_internal.h */
  11319. /* Prepare value stack for a method call through an object property.
  11320. * May currently throw an error e.g. when getting the property.
  11321. */
  11322. DUK_LOCAL void duk__call_prop_prep_stack(duk_context *ctx, duk_idx_t normalized_obj_index, duk_idx_t nargs) {
  11323. DUK_DDD(DUK_DDDPRINT("duk__call_prop_prep_stack, normalized_obj_index=%ld, nargs=%ld, stacktop=%ld",
  11324. (long) normalized_obj_index, (long) nargs, (long) duk_get_top(ctx)));
  11325. /* [... key arg1 ... argN] */
  11326. /* duplicate key */
  11327. duk_dup(ctx, -nargs - 1); /* Note: -nargs alone would fail for nargs == 0, this is OK */
  11328. duk_get_prop(ctx, normalized_obj_index);
  11329. DUK_DDD(DUK_DDDPRINT("func: %!T", (duk_tval *) duk_get_tval(ctx, -1)));
  11330. /* [... key arg1 ... argN func] */
  11331. duk_replace(ctx, -nargs - 2);
  11332. /* [... func arg1 ... argN] */
  11333. duk_dup(ctx, normalized_obj_index);
  11334. duk_insert(ctx, -nargs - 1);
  11335. /* [... func this arg1 ... argN] */
  11336. }
  11337. DUK_EXTERNAL void duk_call(duk_context *ctx, duk_idx_t nargs) {
  11338. duk_hthread *thr = (duk_hthread *) ctx;
  11339. duk_small_uint_t call_flags;
  11340. duk_idx_t idx_func;
  11341. duk_int_t rc;
  11342. DUK_ASSERT(ctx != NULL);
  11343. DUK_ASSERT(thr != NULL);
  11344. idx_func = duk_get_top(ctx) - nargs - 1;
  11345. if (idx_func < 0 || nargs < 0) {
  11346. /* note that we can't reliably pop anything here */
  11347. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  11348. }
  11349. /* XXX: awkward; we assume there is space for this, overwrite
  11350. * directly instead?
  11351. */
  11352. duk_push_undefined(ctx);
  11353. duk_insert(ctx, idx_func + 1);
  11354. call_flags = 0; /* not protected, respect reclimit, not constructor */
  11355. rc = duk_handle_call(thr, /* thread */
  11356. nargs, /* num_stack_args */
  11357. call_flags); /* call_flags */
  11358. DUK_UNREF(rc);
  11359. }
  11360. DUK_EXTERNAL void duk_call_method(duk_context *ctx, duk_idx_t nargs) {
  11361. duk_hthread *thr = (duk_hthread *) ctx;
  11362. duk_small_uint_t call_flags;
  11363. duk_idx_t idx_func;
  11364. duk_int_t rc;
  11365. DUK_ASSERT(ctx != NULL);
  11366. DUK_ASSERT(thr != NULL);
  11367. idx_func = duk_get_top(ctx) - nargs - 2; /* must work for nargs <= 0 */
  11368. if (idx_func < 0 || nargs < 0) {
  11369. /* note that we can't reliably pop anything here */
  11370. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  11371. }
  11372. call_flags = 0; /* not protected, respect reclimit, not constructor */
  11373. rc = duk_handle_call(thr, /* thread */
  11374. nargs, /* num_stack_args */
  11375. call_flags); /* call_flags */
  11376. DUK_UNREF(rc);
  11377. }
  11378. DUK_EXTERNAL void duk_call_prop(duk_context *ctx, duk_idx_t obj_index, duk_idx_t nargs) {
  11379. /*
  11380. * XXX: if duk_handle_call() took values through indices, this could be
  11381. * made much more sensible. However, duk_handle_call() needs to fudge
  11382. * the 'this' and 'func' values to handle bound function chains, which
  11383. * is now done "in-place", so this is not a trivial change.
  11384. */
  11385. obj_index = duk_require_normalize_index(ctx, obj_index); /* make absolute */
  11386. duk__call_prop_prep_stack(ctx, obj_index, nargs);
  11387. duk_call_method(ctx, nargs);
  11388. }
  11389. DUK_EXTERNAL duk_int_t duk_pcall(duk_context *ctx, duk_idx_t nargs) {
  11390. duk_hthread *thr = (duk_hthread *) ctx;
  11391. duk_small_uint_t call_flags;
  11392. duk_idx_t idx_func;
  11393. duk_int_t rc;
  11394. DUK_ASSERT(ctx != NULL);
  11395. DUK_ASSERT(thr != NULL);
  11396. idx_func = duk_get_top(ctx) - nargs - 1; /* must work for nargs <= 0 */
  11397. if (idx_func < 0 || nargs < 0) {
  11398. /* We can't reliably pop anything here because the stack input
  11399. * shape is incorrect. So we throw an error; if the caller has
  11400. * no catch point for this, a fatal error will occur. Another
  11401. * alternative would be to just return an error. But then the
  11402. * stack would be in an unknown state which might cause some
  11403. * very hard to diagnose problems later on. Also note that even
  11404. * if we did not throw an error here, the underlying call handler
  11405. * might STILL throw an out-of-memory error or some other internal
  11406. * fatal error.
  11407. */
  11408. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  11409. return DUK_EXEC_ERROR; /* unreachable */
  11410. }
  11411. /* awkward; we assume there is space for this */
  11412. duk_push_undefined(ctx);
  11413. duk_insert(ctx, idx_func + 1);
  11414. call_flags = DUK_CALL_FLAG_PROTECTED; /* protected, respect reclimit, not constructor */
  11415. rc = duk_handle_call(thr, /* thread */
  11416. nargs, /* num_stack_args */
  11417. call_flags); /* call_flags */
  11418. return rc;
  11419. }
  11420. DUK_EXTERNAL duk_int_t duk_pcall_method(duk_context *ctx, duk_idx_t nargs) {
  11421. duk_hthread *thr = (duk_hthread *) ctx;
  11422. duk_small_uint_t call_flags;
  11423. duk_idx_t idx_func;
  11424. duk_int_t rc;
  11425. DUK_ASSERT(ctx != NULL);
  11426. DUK_ASSERT(thr != NULL);
  11427. idx_func = duk_get_top(ctx) - nargs - 2; /* must work for nargs <= 0 */
  11428. if (idx_func < 0 || nargs < 0) {
  11429. /* See comments in duk_pcall(). */
  11430. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  11431. return DUK_EXEC_ERROR; /* unreachable */
  11432. }
  11433. call_flags = DUK_CALL_FLAG_PROTECTED; /* protected, respect reclimit, not constructor */
  11434. rc = duk_handle_call(thr, /* thread */
  11435. nargs, /* num_stack_args */
  11436. call_flags); /* call_flags */
  11437. return rc;
  11438. }
  11439. DUK_LOCAL duk_ret_t duk__pcall_prop_raw(duk_context *ctx) {
  11440. duk_idx_t obj_index;
  11441. duk_idx_t nargs;
  11442. /* Get the original arguments. Note that obj_index may be a relative
  11443. * index so the stack must have the same top when we use it.
  11444. */
  11445. obj_index = (duk_idx_t) duk_get_int(ctx, -2);
  11446. nargs = (duk_idx_t) duk_get_int(ctx, -1);
  11447. duk_pop_2(ctx);
  11448. obj_index = duk_require_normalize_index(ctx, obj_index); /* make absolute */
  11449. duk__call_prop_prep_stack(ctx, obj_index, nargs);
  11450. duk_call_method(ctx, nargs);
  11451. return 1;
  11452. }
  11453. DUK_EXTERNAL duk_int_t duk_pcall_prop(duk_context *ctx, duk_idx_t obj_index, duk_idx_t nargs) {
  11454. /*
  11455. * Must be careful to catch errors related to value stack manipulation
  11456. * and property lookup, not just the call itself.
  11457. */
  11458. duk_push_idx(ctx, obj_index);
  11459. duk_push_idx(ctx, nargs);
  11460. /* Inputs: explicit arguments (nargs), +1 for key, +2 for obj_index/nargs passing.
  11461. * If the value stack does not contain enough args, an error is thrown; this matches
  11462. * behavior of the other protected call API functions.
  11463. */
  11464. return duk_safe_call(ctx, duk__pcall_prop_raw, nargs + 1 + 2 /*nargs*/, 1 /*nrets*/);
  11465. }
  11466. DUK_EXTERNAL duk_int_t duk_safe_call(duk_context *ctx, duk_safe_call_function func, duk_idx_t nargs, duk_idx_t nrets) {
  11467. duk_hthread *thr = (duk_hthread *) ctx;
  11468. duk_int_t rc;
  11469. DUK_ASSERT(ctx != NULL);
  11470. DUK_ASSERT(thr != NULL);
  11471. if (duk_get_top(ctx) < nargs || nrets < 0) {
  11472. /* See comments in duk_pcall(). */
  11473. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  11474. return DUK_EXEC_ERROR; /* unreachable */
  11475. }
  11476. rc = duk_handle_safe_call(thr, /* thread */
  11477. func, /* func */
  11478. nargs, /* num_stack_args */
  11479. nrets); /* num_stack_res */
  11480. return rc;
  11481. }
  11482. DUK_EXTERNAL void duk_new(duk_context *ctx, duk_idx_t nargs) {
  11483. /*
  11484. * There are two [[Construct]] operations in the specification:
  11485. *
  11486. * - E5 Section 13.2.2: for Function objects
  11487. * - E5 Section 15.3.4.5.2: for "bound" Function objects
  11488. *
  11489. * The chain of bound functions is resolved in Section 15.3.4.5.2,
  11490. * with arguments "piling up" until the [[Construct]] internal
  11491. * method is called on the final, actual Function object. Note
  11492. * that the "prototype" property is looked up *only* from the
  11493. * final object, *before* calling the constructor.
  11494. *
  11495. * Currently we follow the bound function chain here to get the
  11496. * "prototype" property value from the final, non-bound function.
  11497. * However, we let duk_handle_call() handle the argument "piling"
  11498. * when the constructor is called. The bound function chain is
  11499. * thus now processed twice.
  11500. *
  11501. * When constructing new Array instances, an unnecessary object is
  11502. * created and discarded now: the standard [[Construct]] creates an
  11503. * object, and calls the Array constructor. The Array constructor
  11504. * returns an Array instance, which is used as the result value for
  11505. * the "new" operation; the object created before the Array constructor
  11506. * call is discarded.
  11507. *
  11508. * This would be easy to fix, e.g. by knowing that the Array constructor
  11509. * will always create a replacement object and skip creating the fallback
  11510. * object in that case.
  11511. *
  11512. * Note: functions called via "new" need to know they are called as a
  11513. * constructor. For instance, built-in constructors behave differently
  11514. * depending on how they are called.
  11515. */
  11516. /* XXX: merge this with duk_js_call.c, as this function implements
  11517. * core semantics (or perhaps merge the two files altogether).
  11518. */
  11519. duk_hthread *thr = (duk_hthread *) ctx;
  11520. duk_hobject *proto;
  11521. duk_hobject *cons;
  11522. duk_hobject *fallback;
  11523. duk_idx_t idx_cons;
  11524. duk_small_uint_t call_flags;
  11525. duk_int_t rc;
  11526. /* [... constructor arg1 ... argN] */
  11527. idx_cons = duk_require_normalize_index(ctx, -nargs - 1);
  11528. DUK_DDD(DUK_DDDPRINT("top=%ld, nargs=%ld, idx_cons=%ld",
  11529. (long) duk_get_top(ctx), (long) nargs, (long) idx_cons));
  11530. /* XXX: code duplication */
  11531. /*
  11532. * Figure out the final, non-bound constructor, to get "prototype"
  11533. * property.
  11534. */
  11535. duk_dup(ctx, idx_cons);
  11536. for (;;) {
  11537. cons = duk_get_hobject(ctx, -1);
  11538. if (cons == NULL || !DUK_HOBJECT_HAS_CONSTRUCTABLE(cons)) {
  11539. /* Checking constructability from anything else than the
  11540. * initial constructor is not strictly necessary, but a
  11541. * nice sanity check.
  11542. */
  11543. goto not_constructable;
  11544. }
  11545. if (!DUK_HOBJECT_HAS_BOUND(cons)) {
  11546. break;
  11547. }
  11548. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_TARGET); /* -> [... cons target] */
  11549. duk_remove(ctx, -2); /* -> [... target] */
  11550. }
  11551. DUK_ASSERT(cons != NULL && !DUK_HOBJECT_HAS_BOUND(cons));
  11552. /* [... constructor arg1 ... argN final_cons] */
  11553. /*
  11554. * Create "fallback" object to be used as the object instance,
  11555. * unless the constructor returns a replacement value.
  11556. * Its internal prototype needs to be set based on "prototype"
  11557. * property of the constructor.
  11558. */
  11559. duk_push_object(ctx); /* class Object, extensible */
  11560. /* [... constructor arg1 ... argN final_cons fallback] */
  11561. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_PROTOTYPE);
  11562. proto = duk_get_hobject(ctx, -1);
  11563. if (!proto) {
  11564. DUK_DDD(DUK_DDDPRINT("constructor has no 'prototype' property, or value not an object "
  11565. "-> leave standard Object prototype as fallback prototype"));
  11566. } else {
  11567. DUK_DDD(DUK_DDDPRINT("constructor has 'prototype' property with object value "
  11568. "-> set fallback prototype to that value: %!iO", (duk_heaphdr *) proto));
  11569. fallback = duk_get_hobject(ctx, -2);
  11570. DUK_ASSERT(fallback != NULL);
  11571. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, fallback, proto);
  11572. }
  11573. duk_pop(ctx);
  11574. /* [... constructor arg1 ... argN final_cons fallback] */
  11575. /*
  11576. * Manipulate callstack for the call.
  11577. */
  11578. duk_dup_top(ctx);
  11579. duk_insert(ctx, idx_cons + 1); /* use fallback as 'this' value */
  11580. duk_insert(ctx, idx_cons); /* also stash it before constructor,
  11581. * in case we need it (as the fallback value)
  11582. */
  11583. duk_pop(ctx); /* pop final_cons */
  11584. /* [... fallback constructor fallback(this) arg1 ... argN];
  11585. * Note: idx_cons points to first 'fallback', not 'constructor'.
  11586. */
  11587. DUK_DDD(DUK_DDDPRINT("before call, idx_cons+1 (constructor) -> %!T, idx_cons+2 (fallback/this) -> %!T, "
  11588. "nargs=%ld, top=%ld",
  11589. (duk_tval *) duk_get_tval(ctx, idx_cons + 1),
  11590. (duk_tval *) duk_get_tval(ctx, idx_cons + 2),
  11591. (long) nargs,
  11592. (long) duk_get_top(ctx)));
  11593. /*
  11594. * Call the constructor function (called in "constructor mode").
  11595. */
  11596. call_flags = DUK_CALL_FLAG_CONSTRUCTOR_CALL; /* not protected, respect reclimit, is a constructor call */
  11597. rc = duk_handle_call(thr, /* thread */
  11598. nargs, /* num_stack_args */
  11599. call_flags); /* call_flags */
  11600. DUK_UNREF(rc);
  11601. /* [... fallback retval] */
  11602. DUK_DDD(DUK_DDDPRINT("constructor call finished, rc=%ld, fallback=%!iT, retval=%!iT",
  11603. (long) rc,
  11604. (duk_tval *) duk_get_tval(ctx, -2),
  11605. (duk_tval *) duk_get_tval(ctx, -1)));
  11606. /*
  11607. * Determine whether to use the constructor return value as the created
  11608. * object instance or not.
  11609. */
  11610. if (duk_is_object(ctx, -1)) {
  11611. duk_remove(ctx, -2);
  11612. } else {
  11613. duk_pop(ctx);
  11614. }
  11615. /*
  11616. * Augment created errors upon creation (not when they are thrown or
  11617. * rethrown). __FILE__ and __LINE__ are not desirable here; the call
  11618. * stack reflects the caller which is correct.
  11619. */
  11620. #ifdef DUK_USE_AUGMENT_ERROR_CREATE
  11621. duk_err_augment_error_create(thr, thr, NULL, 0, 1 /*noblame_fileline*/);
  11622. #endif
  11623. /* [... retval] */
  11624. return;
  11625. not_constructable:
  11626. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_CONSTRUCTABLE);
  11627. }
  11628. DUK_EXTERNAL duk_bool_t duk_is_constructor_call(duk_context *ctx) {
  11629. duk_hthread *thr = (duk_hthread *) ctx;
  11630. duk_activation *act;
  11631. DUK_ASSERT(ctx != NULL);
  11632. DUK_ASSERT(thr != NULL);
  11633. DUK_ASSERT_DISABLE(thr->callstack_top >= 0);
  11634. act = duk_hthread_get_current_activation(thr);
  11635. DUK_ASSERT(act != NULL); /* because callstack_top > 0 */
  11636. return ((act->flags & DUK_ACT_FLAG_CONSTRUCT) != 0 ? 1 : 0);
  11637. }
  11638. DUK_EXTERNAL duk_bool_t duk_is_strict_call(duk_context *ctx) {
  11639. duk_hthread *thr = (duk_hthread *) ctx;
  11640. duk_activation *act;
  11641. /* For user code this could just return 1 (strict) always
  11642. * because all Duktape/C functions are considered strict,
  11643. * and strict is also the default when nothing is running.
  11644. * However, Duktape may call this function internally when
  11645. * the current activation is an Ecmascript function, so
  11646. * this cannot be replaced by a 'return 1' without fixing
  11647. * the internal call sites.
  11648. */
  11649. DUK_ASSERT(ctx != NULL);
  11650. DUK_ASSERT(thr != NULL);
  11651. DUK_ASSERT_DISABLE(thr->callstack_top >= 0);
  11652. act = duk_hthread_get_current_activation(thr);
  11653. if (act == NULL) {
  11654. /* Strict by default. */
  11655. return 1;
  11656. }
  11657. return ((act->flags & DUK_ACT_FLAG_STRICT) != 0 ? 1 : 0);
  11658. }
  11659. /*
  11660. * Duktape/C function magic
  11661. */
  11662. DUK_EXTERNAL duk_int_t duk_get_current_magic(duk_context *ctx) {
  11663. duk_hthread *thr = (duk_hthread *) ctx;
  11664. duk_activation *act;
  11665. duk_hobject *func;
  11666. DUK_ASSERT(ctx != NULL);
  11667. DUK_ASSERT(thr != NULL);
  11668. DUK_ASSERT_DISABLE(thr->callstack_top >= 0);
  11669. act = duk_hthread_get_current_activation(thr);
  11670. if (act) {
  11671. func = DUK_ACT_GET_FUNC(act);
  11672. if (!func) {
  11673. duk_tval *tv = &act->tv_func;
  11674. duk_small_uint_t lf_flags;
  11675. lf_flags = DUK_TVAL_GET_LIGHTFUNC_FLAGS(tv);
  11676. return (duk_int_t) DUK_LFUNC_FLAGS_GET_MAGIC(lf_flags);
  11677. }
  11678. DUK_ASSERT(func != NULL);
  11679. if (DUK_HOBJECT_IS_NATIVEFUNCTION(func)) {
  11680. duk_hnativefunction *nf = (duk_hnativefunction *) func;
  11681. return (duk_int_t) nf->magic;
  11682. }
  11683. }
  11684. return 0;
  11685. }
  11686. DUK_EXTERNAL duk_int_t duk_get_magic(duk_context *ctx, duk_idx_t index) {
  11687. duk_hthread *thr = (duk_hthread *) ctx;
  11688. duk_tval *tv;
  11689. duk_hobject *h;
  11690. DUK_ASSERT(ctx != NULL);
  11691. tv = duk_require_tval(ctx, index);
  11692. if (DUK_TVAL_IS_OBJECT(tv)) {
  11693. h = DUK_TVAL_GET_OBJECT(tv);
  11694. DUK_ASSERT(h != NULL);
  11695. if (!DUK_HOBJECT_HAS_NATIVEFUNCTION(h)) {
  11696. goto type_error;
  11697. }
  11698. return (duk_int_t) ((duk_hnativefunction *) h)->magic;
  11699. } else if (DUK_TVAL_IS_LIGHTFUNC(tv)) {
  11700. duk_small_uint_t lf_flags = DUK_TVAL_GET_LIGHTFUNC_FLAGS(tv);
  11701. return (duk_int_t) DUK_LFUNC_FLAGS_GET_MAGIC(lf_flags);
  11702. }
  11703. /* fall through */
  11704. type_error:
  11705. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_UNEXPECTED_TYPE);
  11706. return 0;
  11707. }
  11708. DUK_EXTERNAL void duk_set_magic(duk_context *ctx, duk_idx_t index, duk_int_t magic) {
  11709. duk_hnativefunction *nf;
  11710. DUK_ASSERT(ctx != NULL);
  11711. nf = duk_require_hnativefunction(ctx, index);
  11712. DUK_ASSERT(nf != NULL);
  11713. nf->magic = (duk_int16_t) magic;
  11714. }
  11715. #line 1 "duk_api_codec.c"
  11716. /*
  11717. * Encoding and decoding basic formats: hex, base64.
  11718. *
  11719. * These are in-place operations which may allow an optimized implementation.
  11720. */
  11721. /* include removed: duk_internal.h */
  11722. /* dst length must be exactly ceil(len/3)*4 */
  11723. DUK_LOCAL void duk__base64_encode_helper(const duk_uint8_t *src, const duk_uint8_t *src_end,
  11724. duk_uint8_t *dst, duk_uint8_t *dst_end) {
  11725. duk_small_uint_t i, snip;
  11726. duk_uint_fast32_t t;
  11727. duk_uint_fast8_t x, y;
  11728. DUK_UNREF(dst_end);
  11729. while (src < src_end) {
  11730. /* read 3 bytes into 't', padded by zero */
  11731. snip = 4;
  11732. t = 0;
  11733. for (i = 0; i < 3; i++) {
  11734. t = t << 8;
  11735. if (src >= src_end) {
  11736. snip--;
  11737. } else {
  11738. t += (duk_uint_fast32_t) (*src++);
  11739. }
  11740. }
  11741. /*
  11742. * Missing bytes snip base64 example
  11743. * 0 4 XXXX
  11744. * 1 3 XXX=
  11745. * 2 2 XX==
  11746. */
  11747. DUK_ASSERT(snip >= 2 && snip <= 4);
  11748. for (i = 0; i < 4; i++) {
  11749. x = (duk_uint_fast8_t) ((t >> 18) & 0x3f);
  11750. t = t << 6;
  11751. /* A straightforward 64-byte lookup would be faster
  11752. * and cleaner, but this is shorter.
  11753. */
  11754. if (i >= snip) {
  11755. y = '=';
  11756. } else if (x <= 25) {
  11757. y = x + 'A';
  11758. } else if (x <= 51) {
  11759. y = x - 26 + 'a';
  11760. } else if (x <= 61) {
  11761. y = x - 52 + '0';
  11762. } else if (x == 62) {
  11763. y = '+';
  11764. } else {
  11765. y = '/';
  11766. }
  11767. DUK_ASSERT(dst < dst_end);
  11768. *dst++ = (duk_uint8_t) y;
  11769. }
  11770. }
  11771. }
  11772. DUK_LOCAL duk_bool_t duk__base64_decode_helper(const duk_uint8_t *src, const duk_uint8_t *src_end,
  11773. duk_uint8_t *dst, duk_uint8_t *dst_end, duk_uint8_t **out_dst_final) {
  11774. duk_uint_fast32_t t;
  11775. duk_uint_fast8_t x, y;
  11776. duk_small_uint_t group_idx;
  11777. DUK_UNREF(dst_end);
  11778. t = 0;
  11779. group_idx = 0;
  11780. while (src < src_end) {
  11781. x = *src++;
  11782. if (x >= 'A' && x <= 'Z') {
  11783. y = x - 'A' + 0;
  11784. } else if (x >= 'a' && x <= 'z') {
  11785. y = x - 'a' + 26;
  11786. } else if (x >= '0' && x <= '9') {
  11787. y = x - '0' + 52;
  11788. } else if (x == '+') {
  11789. y = 62;
  11790. } else if (x == '/') {
  11791. y = 63;
  11792. } else if (x == '=') {
  11793. /* We don't check the zero padding bytes here right now.
  11794. * This seems to be common behavior for base-64 decoders.
  11795. */
  11796. if (group_idx == 2) {
  11797. /* xx== -> 1 byte, t contains 12 bits, 4 on right are zero */
  11798. t = t >> 4;
  11799. DUK_ASSERT(dst < dst_end);
  11800. *dst++ = (duk_uint8_t) t;
  11801. if (src >= src_end) {
  11802. goto error;
  11803. }
  11804. x = *src++;
  11805. if (x != '=') {
  11806. goto error;
  11807. }
  11808. } else if (group_idx == 3) {
  11809. /* xxx= -> 2 bytes, t contains 18 bits, 2 on right are zero */
  11810. t = t >> 2;
  11811. DUK_ASSERT(dst < dst_end);
  11812. *dst++ = (duk_uint8_t) ((t >> 8) & 0xff);
  11813. DUK_ASSERT(dst < dst_end);
  11814. *dst++ = (duk_uint8_t) (t & 0xff);
  11815. } else {
  11816. goto error;
  11817. }
  11818. /* Here we can choose either to end parsing and ignore
  11819. * whatever follows, or to continue parsing in case
  11820. * multiple (possibly padded) base64 strings have been
  11821. * concatenated. Currently, keep on parsing.
  11822. */
  11823. t = 0;
  11824. group_idx = 0;
  11825. continue;
  11826. } else if (x == 0x09 || x == 0x0a || x == 0x0d || x == 0x20) {
  11827. /* allow basic ASCII whitespace */
  11828. continue;
  11829. } else {
  11830. goto error;
  11831. }
  11832. t = (t << 6) + y;
  11833. if (group_idx == 3) {
  11834. /* output 3 bytes from 't' */
  11835. DUK_ASSERT(dst < dst_end);
  11836. *dst++ = (duk_uint8_t) ((t >> 16) & 0xff);
  11837. DUK_ASSERT(dst < dst_end);
  11838. *dst++ = (duk_uint8_t) ((t >> 8) & 0xff);
  11839. DUK_ASSERT(dst < dst_end);
  11840. *dst++ = (duk_uint8_t) (t & 0xff);
  11841. t = 0;
  11842. group_idx = 0;
  11843. } else {
  11844. group_idx++;
  11845. }
  11846. }
  11847. if (group_idx != 0) {
  11848. /* Here we'd have the option of decoding unpadded base64
  11849. * (e.g. "xxxxyy" instead of "xxxxyy==". Currently not
  11850. * accepted.
  11851. */
  11852. goto error;
  11853. }
  11854. *out_dst_final = dst;
  11855. return 1;
  11856. error:
  11857. return 0;
  11858. }
  11859. /* Shared handling for encode/decode argument. Fast path handling for
  11860. * buffer and string values because they're the most common. In particular,
  11861. * avoid creating a temporary string or buffer when possible.
  11862. */
  11863. DUK_LOCAL const duk_uint8_t *duk__prep_codec_arg(duk_context *ctx, duk_idx_t index, duk_size_t *out_len) {
  11864. DUK_ASSERT(duk_is_valid_index(ctx, index)); /* checked by caller */
  11865. if (duk_is_buffer(ctx, index)) {
  11866. return (const duk_uint8_t *) duk_get_buffer(ctx, index, out_len);
  11867. } else {
  11868. return (const duk_uint8_t *) duk_to_lstring(ctx, index, out_len);
  11869. }
  11870. }
  11871. DUK_EXTERNAL const char *duk_base64_encode(duk_context *ctx, duk_idx_t index) {
  11872. duk_hthread *thr = (duk_hthread *) ctx;
  11873. duk_uint8_t *src;
  11874. duk_size_t srclen;
  11875. duk_size_t dstlen;
  11876. duk_uint8_t *dst;
  11877. const char *ret;
  11878. /* XXX: optimize for string inputs: no need to coerce to a buffer
  11879. * which makes a copy of the input.
  11880. */
  11881. index = duk_require_normalize_index(ctx, index);
  11882. src = (duk_uint8_t *) duk_to_buffer(ctx, index, &srclen);
  11883. /* Note: for srclen=0, src may be NULL */
  11884. /* Computation must not wrap; this limit works for 32-bit size_t:
  11885. * >>> srclen = 3221225469
  11886. * >>> '%x' % ((srclen + 2) / 3 * 4)
  11887. * 'fffffffc'
  11888. */
  11889. if (srclen > 3221225469UL) {
  11890. goto type_error;
  11891. }
  11892. dstlen = (srclen + 2) / 3 * 4;
  11893. dst = (duk_uint8_t *) duk_push_fixed_buffer(ctx, dstlen);
  11894. duk__base64_encode_helper((const duk_uint8_t *) src, (const duk_uint8_t *) (src + srclen),
  11895. dst, (dst + dstlen));
  11896. ret = duk_to_string(ctx, -1);
  11897. duk_replace(ctx, index);
  11898. return ret;
  11899. type_error:
  11900. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_BASE64_ENCODE_FAILED);
  11901. return NULL; /* never here */
  11902. }
  11903. DUK_EXTERNAL void duk_base64_decode(duk_context *ctx, duk_idx_t index) {
  11904. duk_hthread *thr = (duk_hthread *) ctx;
  11905. const duk_uint8_t *src;
  11906. duk_size_t srclen;
  11907. duk_size_t dstlen;
  11908. duk_uint8_t *dst;
  11909. duk_uint8_t *dst_final;
  11910. duk_bool_t retval;
  11911. /* XXX: optimize for buffer inputs: no need to coerce to a string
  11912. * which causes an unnecessary interning.
  11913. */
  11914. index = duk_require_normalize_index(ctx, index);
  11915. src = (const duk_uint8_t *) duk_to_lstring(ctx, index, &srclen);
  11916. /* Computation must not wrap, only srclen + 3 is at risk of
  11917. * wrapping because after that the number gets smaller.
  11918. * This limit works for 32-bit size_t:
  11919. * 0x100000000 - 3 - 1 = 4294967292
  11920. */
  11921. if (srclen > 4294967292UL) {
  11922. goto type_error;
  11923. }
  11924. dstlen = (srclen + 3) / 4 * 3; /* upper limit */
  11925. dst = (duk_uint8_t *) duk_push_dynamic_buffer(ctx, dstlen);
  11926. /* Note: for dstlen=0, dst may be NULL */
  11927. retval = duk__base64_decode_helper((const duk_uint8_t *) src, (const duk_uint8_t *) (src + srclen),
  11928. dst, dst + dstlen, &dst_final);
  11929. if (!retval) {
  11930. goto type_error;
  11931. }
  11932. /* XXX: convert to fixed buffer? */
  11933. (void) duk_resize_buffer(ctx, -1, (duk_size_t) (dst_final - dst));
  11934. duk_replace(ctx, index);
  11935. return;
  11936. type_error:
  11937. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_BASE64_DECODE_FAILED);
  11938. }
  11939. DUK_EXTERNAL const char *duk_hex_encode(duk_context *ctx, duk_idx_t index) {
  11940. const duk_uint8_t *inp;
  11941. duk_size_t len;
  11942. duk_size_t i;
  11943. duk_small_uint_t t;
  11944. duk_uint8_t *buf;
  11945. const char *ret;
  11946. index = duk_require_normalize_index(ctx, index);
  11947. inp = duk__prep_codec_arg(ctx, index, &len);
  11948. DUK_ASSERT(inp != NULL || len == 0);
  11949. /* Fixed buffer, no zeroing because we'll fill all the data. */
  11950. buf = (duk_uint8_t *) duk_push_buffer_raw(ctx, len * 2, DUK_BUF_FLAG_NOZERO /*flags*/);
  11951. DUK_ASSERT(buf != NULL);
  11952. for (i = 0; i < len; i++) {
  11953. /* XXX: by using two 256-entry tables could avoid shifting and masking. */
  11954. t = (duk_small_uint_t) inp[i];
  11955. buf[i*2 + 0] = duk_lc_digits[t >> 4];
  11956. buf[i*2 + 1] = duk_lc_digits[t & 0x0f];
  11957. }
  11958. /* XXX: Using a string return value forces a string intern which is
  11959. * not always necessary. As a rough performance measure, hex encode
  11960. * time for perf-testcases/test-hex-encode.js dropped from ~35s to
  11961. * ~15s without string coercion. Change to returning a buffer and
  11962. * let the caller coerce to string if necessary?
  11963. */
  11964. ret = duk_to_string(ctx, -1);
  11965. duk_replace(ctx, index);
  11966. return ret;
  11967. }
  11968. DUK_EXTERNAL void duk_hex_decode(duk_context *ctx, duk_idx_t index) {
  11969. duk_hthread *thr = (duk_hthread *) ctx;
  11970. const duk_uint8_t *inp;
  11971. duk_size_t len;
  11972. duk_size_t i;
  11973. duk_small_int_t t;
  11974. duk_uint8_t *buf;
  11975. index = duk_require_normalize_index(ctx, index);
  11976. inp = duk__prep_codec_arg(ctx, index, &len);
  11977. DUK_ASSERT(inp != NULL || len == 0);
  11978. if (len & 0x01) {
  11979. goto type_error;
  11980. }
  11981. /* Fixed buffer, no zeroing because we'll fill all the data. */
  11982. buf = (duk_uint8_t *) duk_push_buffer_raw(ctx, len / 2, DUK_BUF_FLAG_NOZERO /*flags*/);
  11983. DUK_ASSERT(buf != NULL);
  11984. for (i = 0; i < len; i += 2) {
  11985. /* For invalid characters the value -1 gets extended to
  11986. * at least 16 bits. If either nybble is invalid, the
  11987. * resulting 't' will be < 0.
  11988. */
  11989. t = (((duk_small_int_t) duk_hex_dectab[inp[i]]) << 4) |
  11990. ((duk_small_int_t) duk_hex_dectab[inp[i + 1]]);
  11991. if (DUK_UNLIKELY(t < 0)) {
  11992. goto type_error;
  11993. }
  11994. buf[i >> 1] = (duk_uint8_t) t;
  11995. }
  11996. duk_replace(ctx, index);
  11997. return;
  11998. type_error:
  11999. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_HEX_DECODE_FAILED);
  12000. }
  12001. DUK_EXTERNAL const char *duk_json_encode(duk_context *ctx, duk_idx_t index) {
  12002. #ifdef DUK_USE_ASSERTIONS
  12003. duk_idx_t top_at_entry = duk_get_top(ctx);
  12004. #endif
  12005. const char *ret;
  12006. index = duk_require_normalize_index(ctx, index);
  12007. duk_bi_json_stringify_helper(ctx,
  12008. index /*idx_value*/,
  12009. DUK_INVALID_INDEX /*idx_replacer*/,
  12010. DUK_INVALID_INDEX /*idx_space*/,
  12011. 0 /*flags*/);
  12012. DUK_ASSERT(duk_is_string(ctx, -1));
  12013. duk_replace(ctx, index);
  12014. ret = duk_get_string(ctx, index);
  12015. DUK_ASSERT(duk_get_top(ctx) == top_at_entry);
  12016. return ret;
  12017. }
  12018. DUK_EXTERNAL void duk_json_decode(duk_context *ctx, duk_idx_t index) {
  12019. #ifdef DUK_USE_ASSERTIONS
  12020. duk_idx_t top_at_entry = duk_get_top(ctx);
  12021. #endif
  12022. index = duk_require_normalize_index(ctx, index);
  12023. duk_bi_json_parse_helper(ctx,
  12024. index /*idx_value*/,
  12025. DUK_INVALID_INDEX /*idx_reviver*/,
  12026. 0 /*flags*/);
  12027. duk_replace(ctx, index);
  12028. DUK_ASSERT(duk_get_top(ctx) == top_at_entry);
  12029. }
  12030. #line 1 "duk_api_compile.c"
  12031. /*
  12032. * Compilation and evaluation
  12033. */
  12034. /* include removed: duk_internal.h */
  12035. typedef struct duk__compile_raw_args duk__compile_raw_args;
  12036. struct duk__compile_raw_args {
  12037. duk_size_t src_length; /* should be first on 64-bit platforms */
  12038. const duk_uint8_t *src_buffer;
  12039. duk_uint_t flags;
  12040. };
  12041. /* Eval is just a wrapper now. */
  12042. DUK_EXTERNAL duk_int_t duk_eval_raw(duk_context *ctx, const char *src_buffer, duk_size_t src_length, duk_uint_t flags) {
  12043. duk_uint_t comp_flags;
  12044. duk_int_t rc;
  12045. /* Note: strictness is *not* inherited from the current Duktape/C.
  12046. * This would be confusing because the current strictness state
  12047. * depends on whether we're running inside a Duktape/C activation
  12048. * (= strict mode) or outside of any activation (= non-strict mode).
  12049. * See api-testcases/test-eval-strictness.c for more discussion.
  12050. */
  12051. /* [ ... source? filename ] (depends on flags) */
  12052. comp_flags = flags;
  12053. comp_flags |= DUK_COMPILE_EVAL;
  12054. rc = duk_compile_raw(ctx, src_buffer, src_length, comp_flags); /* may be safe, or non-safe depending on flags */
  12055. /* [ ... closure/error ] */
  12056. if (rc != DUK_EXEC_SUCCESS) {
  12057. rc = DUK_EXEC_ERROR;
  12058. goto got_rc;
  12059. }
  12060. if (flags & DUK_COMPILE_SAFE) {
  12061. rc = duk_pcall(ctx, 0);
  12062. } else {
  12063. duk_call(ctx, 0);
  12064. rc = DUK_EXEC_SUCCESS;
  12065. }
  12066. /* [ ... result/error ] */
  12067. got_rc:
  12068. if (flags & DUK_COMPILE_NORESULT) {
  12069. duk_pop(ctx);
  12070. }
  12071. return rc;
  12072. }
  12073. /* Helper which can be called both directly and with duk_safe_call(). */
  12074. DUK_LOCAL duk_ret_t duk__do_compile(duk_context *ctx) {
  12075. duk_hthread *thr = (duk_hthread *) ctx;
  12076. duk__compile_raw_args *comp_args;
  12077. duk_uint_t flags;
  12078. duk_small_uint_t comp_flags;
  12079. duk_hcompiledfunction *h_templ;
  12080. /* Note: strictness is not inherited from the current Duktape/C
  12081. * context. Otherwise it would not be possible to compile
  12082. * non-strict code inside a Duktape/C activation (which is
  12083. * always strict now). See api-testcases/test-eval-strictness.c
  12084. * for discussion.
  12085. */
  12086. /* [ ... source? filename &comp_args ] (depends on flags) */
  12087. comp_args = (duk__compile_raw_args *) duk_require_pointer(ctx, -1);
  12088. flags = comp_args->flags;
  12089. duk_pop(ctx);
  12090. /* [ ... source? filename ] */
  12091. if (!comp_args->src_buffer) {
  12092. duk_hstring *h_sourcecode;
  12093. h_sourcecode = duk_get_hstring(ctx, -2);
  12094. if ((flags & DUK_COMPILE_NOSOURCE) || /* args incorrect */
  12095. (h_sourcecode == NULL)) { /* e.g. duk_push_file_string_raw() pushed undefined */
  12096. /* XXX: when this error is caused by a nonexistent
  12097. * file given to duk_peval_file() or similar, the
  12098. * error message is not the best possible.
  12099. */
  12100. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_NO_SOURCECODE);
  12101. }
  12102. DUK_ASSERT(h_sourcecode != NULL);
  12103. comp_args->src_buffer = (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h_sourcecode);
  12104. comp_args->src_length = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h_sourcecode);
  12105. }
  12106. DUK_ASSERT(comp_args->src_buffer != NULL);
  12107. /* XXX: unnecessary translation of flags */
  12108. comp_flags = 0;
  12109. if (flags & DUK_COMPILE_EVAL) {
  12110. comp_flags |= DUK_JS_COMPILE_FLAG_EVAL;
  12111. }
  12112. if (flags & DUK_COMPILE_FUNCTION) {
  12113. comp_flags |= DUK_JS_COMPILE_FLAG_EVAL |
  12114. DUK_JS_COMPILE_FLAG_FUNCEXPR;
  12115. }
  12116. if (flags & DUK_COMPILE_STRICT) {
  12117. comp_flags |= DUK_JS_COMPILE_FLAG_STRICT;
  12118. }
  12119. /* [ ... source? filename ] */
  12120. duk_js_compile(thr, comp_args->src_buffer, comp_args->src_length, comp_flags);
  12121. /* [ ... source? func_template ] */
  12122. if (flags & DUK_COMPILE_NOSOURCE) {
  12123. ;
  12124. } else {
  12125. duk_remove(ctx, -2);
  12126. }
  12127. /* [ ... func_template ] */
  12128. h_templ = (duk_hcompiledfunction *) duk_get_hobject(ctx, -1);
  12129. DUK_ASSERT(h_templ != NULL);
  12130. duk_js_push_closure(thr,
  12131. h_templ,
  12132. thr->builtins[DUK_BIDX_GLOBAL_ENV],
  12133. thr->builtins[DUK_BIDX_GLOBAL_ENV]);
  12134. duk_remove(ctx, -2); /* -> [ ... closure ] */
  12135. /* [ ... closure ] */
  12136. return 1;
  12137. }
  12138. DUK_EXTERNAL duk_int_t duk_compile_raw(duk_context *ctx, const char *src_buffer, duk_size_t src_length, duk_uint_t flags) {
  12139. duk__compile_raw_args comp_args_alloc;
  12140. duk__compile_raw_args *comp_args = &comp_args_alloc;
  12141. if ((flags & DUK_COMPILE_STRLEN) && (src_buffer != NULL)) {
  12142. /* String length is computed here to avoid multiple evaluation
  12143. * of a macro argument in the calling side.
  12144. */
  12145. src_length = DUK_STRLEN(src_buffer);
  12146. }
  12147. comp_args->src_buffer = (const duk_uint8_t *) src_buffer;
  12148. comp_args->src_length = src_length;
  12149. comp_args->flags = flags;
  12150. duk_push_pointer(ctx, (void *) comp_args);
  12151. /* [ ... source? filename &comp_args ] (depends on flags) */
  12152. if (flags & DUK_COMPILE_SAFE) {
  12153. duk_int_t rc;
  12154. duk_int_t nargs;
  12155. duk_int_t nrets = 1;
  12156. /* Arguments are either: [ filename &comp_args ] or [ source filename &comp_args ] */
  12157. nargs = (flags & DUK_COMPILE_NOSOURCE) ? 2 : 3;
  12158. rc = duk_safe_call(ctx, duk__do_compile, nargs, nrets);
  12159. /* [ ... closure ] */
  12160. return rc;
  12161. }
  12162. (void) duk__do_compile(ctx);
  12163. /* [ ... closure ] */
  12164. return DUK_EXEC_SUCCESS;
  12165. }
  12166. #line 1 "duk_api_debug.c"
  12167. /*
  12168. * Debugging related API calls
  12169. */
  12170. /* include removed: duk_internal.h */
  12171. DUK_EXTERNAL void duk_push_context_dump(duk_context *ctx) {
  12172. duk_idx_t idx;
  12173. duk_idx_t top;
  12174. /* We don't duk_require_stack() here now, but rely on the caller having
  12175. * enough space.
  12176. */
  12177. top = duk_get_top(ctx);
  12178. duk_push_array(ctx);
  12179. for (idx = 0; idx < top; idx++) {
  12180. duk_dup(ctx, idx);
  12181. duk_put_prop_index(ctx, -2, idx);
  12182. }
  12183. /* XXX: conversion errors should not propagate outwards.
  12184. * Perhaps values need to be coerced individually?
  12185. */
  12186. duk_bi_json_stringify_helper(ctx,
  12187. duk_get_top_index(ctx), /*idx_value*/
  12188. DUK_INVALID_INDEX, /*idx_replacer*/
  12189. DUK_INVALID_INDEX, /*idx_space*/
  12190. DUK_JSON_FLAG_EXT_CUSTOM |
  12191. DUK_JSON_FLAG_ASCII_ONLY |
  12192. DUK_JSON_FLAG_AVOID_KEY_QUOTES /*flags*/);
  12193. duk_push_sprintf(ctx, "ctx: top=%ld, stack=%s", (long) top, (const char *) duk_safe_to_string(ctx, -1));
  12194. duk_replace(ctx, -3); /* [ ... arr jsonx(arr) res ] -> [ ... res jsonx(arr) ] */
  12195. duk_pop(ctx);
  12196. DUK_ASSERT(duk_is_string(ctx, -1));
  12197. }
  12198. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  12199. DUK_EXTERNAL void duk_debugger_attach(duk_context *ctx,
  12200. duk_debug_read_function read_cb,
  12201. duk_debug_write_function write_cb,
  12202. duk_debug_peek_function peek_cb,
  12203. duk_debug_read_flush_function read_flush_cb,
  12204. duk_debug_write_flush_function write_flush_cb,
  12205. duk_debug_detached_function detached_cb,
  12206. void *udata) {
  12207. duk_hthread *thr = (duk_hthread *) ctx;
  12208. duk_heap *heap;
  12209. const char *str;
  12210. duk_size_t len;
  12211. DUK_ASSERT(ctx != NULL);
  12212. DUK_ASSERT(read_cb != NULL);
  12213. DUK_ASSERT(write_cb != NULL);
  12214. /* Other callbacks are optional. */
  12215. heap = thr->heap;
  12216. heap->dbg_read_cb = read_cb;
  12217. heap->dbg_write_cb = write_cb;
  12218. heap->dbg_peek_cb = peek_cb;
  12219. heap->dbg_read_flush_cb = read_flush_cb;
  12220. heap->dbg_write_flush_cb = write_flush_cb;
  12221. heap->dbg_detached_cb = detached_cb;
  12222. heap->dbg_udata = udata;
  12223. /* Start in paused state. */
  12224. heap->dbg_processing = 0;
  12225. heap->dbg_paused = 1;
  12226. heap->dbg_state_dirty = 1;
  12227. heap->dbg_step_type = 0;
  12228. heap->dbg_step_thread = NULL;
  12229. heap->dbg_step_csindex = 0;
  12230. heap->dbg_step_startline = 0;
  12231. heap->dbg_exec_counter = 0;
  12232. heap->dbg_last_counter = 0;
  12233. heap->dbg_last_time = 0.0;
  12234. /* Send version identification and flush right afterwards. Note that
  12235. * we must write raw, unframed bytes here.
  12236. */
  12237. duk_push_sprintf(ctx, "%ld %ld %s %s\n",
  12238. (long) DUK_DEBUG_PROTOCOL_VERSION,
  12239. (long) DUK_VERSION,
  12240. (const char *) DUK_GIT_DESCRIBE,
  12241. (const char *) DUK_USE_TARGET_INFO);
  12242. str = duk_get_lstring(ctx, -1, &len);
  12243. DUK_ASSERT(str != NULL);
  12244. duk_debug_write_bytes(thr, (const duk_uint8_t *) str, len);
  12245. duk_debug_write_flush(thr);
  12246. duk_pop(ctx);
  12247. }
  12248. DUK_EXTERNAL void duk_debugger_detach(duk_context *ctx) {
  12249. duk_hthread *thr;
  12250. thr = (duk_hthread *) ctx;
  12251. DUK_ASSERT(ctx != NULL);
  12252. DUK_ASSERT(thr != NULL);
  12253. DUK_ASSERT(thr->heap != NULL);
  12254. /* Can be called muliple times with no harm. */
  12255. duk_debug_do_detach(thr->heap);
  12256. }
  12257. DUK_EXTERNAL void duk_debugger_cooperate(duk_context *ctx) {
  12258. duk_hthread *thr;
  12259. duk_bool_t processed_messages;
  12260. thr = (duk_hthread *) ctx;
  12261. DUK_ASSERT(ctx != NULL);
  12262. DUK_ASSERT(thr != NULL);
  12263. DUK_ASSERT(thr->heap != NULL);
  12264. if (!DUK_HEAP_IS_DEBUGGER_ATTACHED(thr->heap)) {
  12265. return;
  12266. }
  12267. if (thr->callstack_top > 0 || thr->heap->dbg_processing) {
  12268. /* Calling duk_debugger_cooperate() while Duktape is being
  12269. * called into is not supported. This is not a 100% check
  12270. * but prevents any damage in most cases.
  12271. */
  12272. return;
  12273. }
  12274. thr->heap->dbg_processing = 1;
  12275. processed_messages = duk_debug_process_messages(thr, 1 /*no_block*/);
  12276. thr->heap->dbg_processing = 0;
  12277. DUK_UNREF(processed_messages);
  12278. }
  12279. #else /* DUK_USE_DEBUGGER_SUPPORT */
  12280. DUK_EXTERNAL void duk_debugger_attach(duk_context *ctx,
  12281. duk_debug_read_function read_cb,
  12282. duk_debug_write_function write_cb,
  12283. duk_debug_peek_function peek_cb,
  12284. duk_debug_read_flush_function read_flush_cb,
  12285. duk_debug_write_flush_function write_flush_cb,
  12286. duk_debug_detached_function detached_cb,
  12287. void *udata) {
  12288. DUK_UNREF(read_cb);
  12289. DUK_UNREF(write_cb);
  12290. DUK_UNREF(peek_cb);
  12291. DUK_UNREF(read_flush_cb);
  12292. DUK_UNREF(write_flush_cb);
  12293. DUK_UNREF(detached_cb);
  12294. DUK_UNREF(udata);
  12295. duk_error(ctx, DUK_ERR_API_ERROR, "no debugger support");
  12296. }
  12297. DUK_EXTERNAL void duk_debugger_detach(duk_context *ctx) {
  12298. duk_error(ctx, DUK_ERR_API_ERROR, "no debugger support");
  12299. }
  12300. DUK_EXTERNAL void duk_debugger_cooperate(duk_context *ctx) {
  12301. /* nop */
  12302. DUK_UNREF(ctx);
  12303. }
  12304. #endif /* DUK_USE_DEBUGGER_SUPPORT */
  12305. #line 1 "duk_api_heap.c"
  12306. /*
  12307. * Heap creation and destruction
  12308. */
  12309. /* include removed: duk_internal.h */
  12310. DUK_EXTERNAL
  12311. duk_context *duk_create_heap(duk_alloc_function alloc_func,
  12312. duk_realloc_function realloc_func,
  12313. duk_free_function free_func,
  12314. void *heap_udata,
  12315. duk_fatal_function fatal_handler) {
  12316. duk_heap *heap = NULL;
  12317. duk_context *ctx;
  12318. /* Assume that either all memory funcs are NULL or non-NULL, mixed
  12319. * cases will now be unsafe.
  12320. */
  12321. /* XXX: just assert non-NULL values here and make caller arguments
  12322. * do the defaulting to the default implementations (smaller code)?
  12323. */
  12324. if (!alloc_func) {
  12325. DUK_ASSERT(realloc_func == NULL);
  12326. DUK_ASSERT(free_func == NULL);
  12327. alloc_func = duk_default_alloc_function;
  12328. realloc_func = duk_default_realloc_function;
  12329. free_func = duk_default_free_function;
  12330. } else {
  12331. DUK_ASSERT(realloc_func != NULL);
  12332. DUK_ASSERT(free_func != NULL);
  12333. }
  12334. if (!fatal_handler) {
  12335. fatal_handler = duk_default_fatal_handler;
  12336. }
  12337. DUK_ASSERT(alloc_func != NULL);
  12338. DUK_ASSERT(realloc_func != NULL);
  12339. DUK_ASSERT(free_func != NULL);
  12340. DUK_ASSERT(fatal_handler != NULL);
  12341. heap = duk_heap_alloc(alloc_func, realloc_func, free_func, heap_udata, fatal_handler);
  12342. if (!heap) {
  12343. return NULL;
  12344. }
  12345. ctx = (duk_context *) heap->heap_thread;
  12346. DUK_ASSERT(ctx != NULL);
  12347. DUK_ASSERT(((duk_hthread *) ctx)->heap != NULL);
  12348. return ctx;
  12349. }
  12350. DUK_EXTERNAL void duk_destroy_heap(duk_context *ctx) {
  12351. duk_hthread *thr = (duk_hthread *) ctx;
  12352. duk_heap *heap;
  12353. if (!ctx) {
  12354. return;
  12355. }
  12356. heap = thr->heap;
  12357. DUK_ASSERT(heap != NULL);
  12358. duk_heap_free(heap);
  12359. }
  12360. /* XXX: better place for this */
  12361. DUK_EXTERNAL void duk_set_global_object(duk_context *ctx) {
  12362. duk_hthread *thr = (duk_hthread *) ctx;
  12363. duk_hobject *h_glob;
  12364. duk_hobject *h_prev_glob;
  12365. duk_hobject *h_env;
  12366. duk_hobject *h_prev_env;
  12367. DUK_D(DUK_DPRINT("replace global object with: %!T", duk_get_tval(ctx, -1)));
  12368. h_glob = duk_require_hobject(ctx, -1);
  12369. DUK_ASSERT(h_glob != NULL);
  12370. /*
  12371. * Replace global object.
  12372. */
  12373. h_prev_glob = thr->builtins[DUK_BIDX_GLOBAL];
  12374. thr->builtins[DUK_BIDX_GLOBAL] = h_glob;
  12375. DUK_HOBJECT_INCREF(thr, h_glob);
  12376. DUK_HOBJECT_DECREF_ALLOWNULL(thr, h_prev_glob); /* side effects, in theory (referenced by global env) */
  12377. /*
  12378. * Replace lexical environment for global scope
  12379. *
  12380. * Create a new object environment for the global lexical scope.
  12381. * We can't just reset the _Target property of the current one,
  12382. * because the lexical scope is shared by other threads with the
  12383. * same (initial) built-ins.
  12384. */
  12385. (void) duk_push_object_helper(ctx,
  12386. DUK_HOBJECT_FLAG_EXTENSIBLE |
  12387. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJENV),
  12388. -1); /* no prototype, updated below */
  12389. duk_dup(ctx, -2);
  12390. duk_dup(ctx, -3);
  12391. /* [ ... new_glob new_env new_glob new_glob ] */
  12392. duk_xdef_prop_stridx(thr, -3, DUK_STRIDX_INT_TARGET, DUK_PROPDESC_FLAGS_NONE);
  12393. duk_xdef_prop_stridx(thr, -2, DUK_STRIDX_INT_THIS, DUK_PROPDESC_FLAGS_NONE);
  12394. /* [ ... new_glob new_env ] */
  12395. h_env = duk_get_hobject(ctx, -1);
  12396. DUK_ASSERT(h_env != NULL);
  12397. h_prev_env = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  12398. thr->builtins[DUK_BIDX_GLOBAL_ENV] = h_env;
  12399. DUK_HOBJECT_INCREF(thr, h_env);
  12400. DUK_HOBJECT_DECREF_ALLOWNULL(thr, h_prev_env); /* side effects */
  12401. DUK_UNREF(h_env); /* without refcounts */
  12402. DUK_UNREF(h_prev_env);
  12403. /* [ ... new_glob new_env ] */
  12404. duk_pop_2(ctx);
  12405. /* [ ... ] */
  12406. }
  12407. #line 1 "duk_api_logging.c"
  12408. /*
  12409. * Logging
  12410. *
  12411. * Current logging primitive is a sprintf-style log which is convenient
  12412. * for most C code. Another useful primitive would be to log N arguments
  12413. * from value stack (like the Ecmascript binding does).
  12414. */
  12415. /* include removed: duk_internal.h */
  12416. DUK_EXTERNAL void duk_log_va(duk_context *ctx, duk_int_t level, const char *fmt, va_list ap) {
  12417. /* stridx_logfunc[] must be static to allow initializer with old compilers like BCC */
  12418. static const duk_uint16_t stridx_logfunc[6] = {
  12419. DUK_STRIDX_LC_TRACE, DUK_STRIDX_LC_DEBUG, DUK_STRIDX_LC_INFO,
  12420. DUK_STRIDX_LC_WARN, DUK_STRIDX_LC_ERROR, DUK_STRIDX_LC_FATAL
  12421. };
  12422. if (level < 0) {
  12423. level = 0;
  12424. } else if (level > (int) (sizeof(stridx_logfunc) / sizeof(duk_uint16_t)) - 1) {
  12425. level = (int) (sizeof(stridx_logfunc) / sizeof(duk_uint16_t)) - 1;
  12426. }
  12427. duk_push_hobject_bidx(ctx, DUK_BIDX_LOGGER_CONSTRUCTOR);
  12428. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_CLOG);
  12429. duk_get_prop_stridx(ctx, -1, stridx_logfunc[level]);
  12430. duk_dup(ctx, -2);
  12431. /* [ ... Logger clog logfunc clog ] */
  12432. duk_push_vsprintf(ctx, fmt, ap);
  12433. /* [ ... Logger clog logfunc clog(=this) msg ] */
  12434. duk_call_method(ctx, 1 /*nargs*/);
  12435. /* [ ... Logger clog res ] */
  12436. duk_pop_3(ctx);
  12437. }
  12438. DUK_EXTERNAL void duk_log(duk_context *ctx, duk_int_t level, const char *fmt, ...) {
  12439. va_list ap;
  12440. va_start(ap, fmt);
  12441. duk_log_va(ctx, level, fmt, ap);
  12442. va_end(ap);
  12443. }
  12444. #line 1 "duk_api_memory.c"
  12445. /*
  12446. * Memory calls.
  12447. */
  12448. /* include removed: duk_internal.h */
  12449. DUK_EXTERNAL void *duk_alloc_raw(duk_context *ctx, duk_size_t size) {
  12450. duk_hthread *thr = (duk_hthread *) ctx;
  12451. DUK_ASSERT(ctx != NULL);
  12452. return DUK_ALLOC_RAW(thr->heap, size);
  12453. }
  12454. DUK_EXTERNAL void duk_free_raw(duk_context *ctx, void *ptr) {
  12455. duk_hthread *thr = (duk_hthread *) ctx;
  12456. DUK_ASSERT(ctx != NULL);
  12457. DUK_FREE_RAW(thr->heap, ptr);
  12458. }
  12459. DUK_EXTERNAL void *duk_realloc_raw(duk_context *ctx, void *ptr, duk_size_t size) {
  12460. duk_hthread *thr = (duk_hthread *) ctx;
  12461. DUK_ASSERT(ctx != NULL);
  12462. return DUK_REALLOC_RAW(thr->heap, ptr, size);
  12463. }
  12464. DUK_EXTERNAL void *duk_alloc(duk_context *ctx, duk_size_t size) {
  12465. duk_hthread *thr = (duk_hthread *) ctx;
  12466. DUK_ASSERT(ctx != NULL);
  12467. return DUK_ALLOC(thr->heap, size);
  12468. }
  12469. DUK_EXTERNAL void duk_free(duk_context *ctx, void *ptr) {
  12470. duk_hthread *thr = (duk_hthread *) ctx;
  12471. DUK_ASSERT(ctx != NULL);
  12472. DUK_FREE(thr->heap, ptr);
  12473. }
  12474. DUK_EXTERNAL void *duk_realloc(duk_context *ctx, void *ptr, duk_size_t size) {
  12475. duk_hthread *thr = (duk_hthread *) ctx;
  12476. DUK_ASSERT(ctx != NULL);
  12477. /*
  12478. * Note: since this is an exposed API call, there should be
  12479. * no way a mark-and-sweep could have a side effect on the
  12480. * memory allocation behind 'ptr'; the pointer should never
  12481. * be something that Duktape wants to change.
  12482. *
  12483. * Thus, no need to use DUK_REALLOC_INDIRECT (and we don't
  12484. * have the storage location here anyway).
  12485. */
  12486. return DUK_REALLOC(thr->heap, ptr, size);
  12487. }
  12488. DUK_EXTERNAL void duk_get_memory_functions(duk_context *ctx, duk_memory_functions *out_funcs) {
  12489. duk_hthread *thr = (duk_hthread *) ctx;
  12490. duk_heap *heap;
  12491. DUK_ASSERT(ctx != NULL);
  12492. DUK_ASSERT(out_funcs != NULL);
  12493. DUK_ASSERT(thr != NULL);
  12494. DUK_ASSERT(thr->heap != NULL);
  12495. heap = thr->heap;
  12496. out_funcs->alloc_func = heap->alloc_func;
  12497. out_funcs->realloc_func = heap->realloc_func;
  12498. out_funcs->free_func = heap->free_func;
  12499. out_funcs->udata = heap->heap_udata;
  12500. }
  12501. DUK_EXTERNAL void duk_gc(duk_context *ctx, duk_uint_t flags) {
  12502. #ifdef DUK_USE_MARK_AND_SWEEP
  12503. duk_hthread *thr = (duk_hthread *) ctx;
  12504. duk_heap *heap;
  12505. DUK_UNREF(flags);
  12506. if (!ctx) {
  12507. return;
  12508. }
  12509. heap = thr->heap;
  12510. DUK_ASSERT(heap != NULL);
  12511. DUK_D(DUK_DPRINT("mark-and-sweep requested by application"));
  12512. duk_heap_mark_and_sweep(heap, 0);
  12513. #else
  12514. DUK_D(DUK_DPRINT("mark-and-sweep requested by application but mark-and-sweep not enabled, ignoring"));
  12515. DUK_UNREF(ctx);
  12516. DUK_UNREF(flags);
  12517. #endif
  12518. }
  12519. #line 1 "duk_api_object.c"
  12520. /*
  12521. * Object handling: property access and other support functions.
  12522. */
  12523. /* include removed: duk_internal.h */
  12524. /*
  12525. * Property handling
  12526. *
  12527. * The API exposes only the most common property handling functions.
  12528. * The caller can invoke Ecmascript built-ins for full control (e.g.
  12529. * defineProperty, getOwnPropertyDescriptor).
  12530. */
  12531. DUK_EXTERNAL duk_bool_t duk_get_prop(duk_context *ctx, duk_idx_t obj_index) {
  12532. duk_hthread *thr = (duk_hthread *) ctx;
  12533. duk_tval *tv_obj;
  12534. duk_tval *tv_key;
  12535. duk_bool_t rc;
  12536. DUK_ASSERT(ctx != NULL);
  12537. /* Note: copying tv_obj and tv_key to locals to shield against a valstack
  12538. * resize is not necessary for a property get right now.
  12539. */
  12540. tv_obj = duk_require_tval(ctx, obj_index);
  12541. tv_key = duk_require_tval(ctx, -1);
  12542. rc = duk_hobject_getprop(thr, tv_obj, tv_key);
  12543. DUK_ASSERT(rc == 0 || rc == 1);
  12544. /* a value is left on stack regardless of rc */
  12545. duk_remove(ctx, -2); /* remove key */
  12546. return rc; /* 1 if property found, 0 otherwise */
  12547. }
  12548. DUK_EXTERNAL duk_bool_t duk_get_prop_string(duk_context *ctx, duk_idx_t obj_index, const char *key) {
  12549. DUK_ASSERT(ctx != NULL);
  12550. DUK_ASSERT(key != NULL);
  12551. obj_index = duk_require_normalize_index(ctx, obj_index);
  12552. duk_push_string(ctx, key);
  12553. return duk_get_prop(ctx, obj_index);
  12554. }
  12555. DUK_EXTERNAL duk_bool_t duk_get_prop_index(duk_context *ctx, duk_idx_t obj_index, duk_uarridx_t arr_index) {
  12556. DUK_ASSERT(ctx != NULL);
  12557. obj_index = duk_require_normalize_index(ctx, obj_index);
  12558. duk_push_uarridx(ctx, arr_index);
  12559. return duk_get_prop(ctx, obj_index);
  12560. }
  12561. DUK_INTERNAL duk_bool_t duk_get_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx) {
  12562. duk_hthread *thr = (duk_hthread *) ctx;
  12563. DUK_ASSERT(ctx != NULL);
  12564. DUK_ASSERT_DISABLE(stridx >= 0);
  12565. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  12566. obj_index = duk_require_normalize_index(ctx, obj_index);
  12567. duk_push_hstring(ctx, DUK_HTHREAD_GET_STRING(thr, stridx));
  12568. return duk_get_prop(ctx, obj_index);
  12569. }
  12570. DUK_INTERNAL duk_bool_t duk_get_prop_stridx_boolean(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_bool_t *out_has_prop) {
  12571. duk_bool_t rc;
  12572. DUK_ASSERT(ctx != NULL);
  12573. DUK_ASSERT_DISABLE(stridx >= 0);
  12574. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  12575. rc = duk_get_prop_stridx(ctx, obj_index, stridx);
  12576. if (out_has_prop) {
  12577. *out_has_prop = rc;
  12578. }
  12579. rc = duk_to_boolean(ctx, -1);
  12580. DUK_ASSERT(rc == 0 || rc == 1);
  12581. duk_pop(ctx);
  12582. return rc;
  12583. }
  12584. DUK_EXTERNAL duk_bool_t duk_put_prop(duk_context *ctx, duk_idx_t obj_index) {
  12585. duk_hthread *thr = (duk_hthread *) ctx;
  12586. duk_tval *tv_obj;
  12587. duk_tval *tv_key;
  12588. duk_tval *tv_val;
  12589. duk_small_int_t throw_flag;
  12590. duk_bool_t rc;
  12591. DUK_ASSERT(ctx != NULL);
  12592. /* Note: copying tv_obj and tv_key to locals to shield against a valstack
  12593. * resize is not necessary for a property put right now (putprop protects
  12594. * against it internally).
  12595. */
  12596. tv_obj = duk_require_tval(ctx, obj_index);
  12597. tv_key = duk_require_tval(ctx, -2);
  12598. tv_val = duk_require_tval(ctx, -1);
  12599. throw_flag = duk_is_strict_call(ctx);
  12600. rc = duk_hobject_putprop(thr, tv_obj, tv_key, tv_val, throw_flag);
  12601. DUK_ASSERT(rc == 0 || rc == 1);
  12602. duk_pop_2(ctx); /* remove key and value */
  12603. return rc; /* 1 if property found, 0 otherwise */
  12604. }
  12605. DUK_EXTERNAL duk_bool_t duk_put_prop_string(duk_context *ctx, duk_idx_t obj_index, const char *key) {
  12606. DUK_ASSERT(ctx != NULL);
  12607. DUK_ASSERT(key != NULL);
  12608. obj_index = duk_require_normalize_index(ctx, obj_index);
  12609. duk_push_string(ctx, key);
  12610. duk_swap_top(ctx, -2); /* [val key] -> [key val] */
  12611. return duk_put_prop(ctx, obj_index);
  12612. }
  12613. DUK_EXTERNAL duk_bool_t duk_put_prop_index(duk_context *ctx, duk_idx_t obj_index, duk_uarridx_t arr_index) {
  12614. DUK_ASSERT(ctx != NULL);
  12615. obj_index = duk_require_normalize_index(ctx, obj_index);
  12616. duk_push_uarridx(ctx, arr_index);
  12617. duk_swap_top(ctx, -2); /* [val key] -> [key val] */
  12618. return duk_put_prop(ctx, obj_index);
  12619. }
  12620. DUK_INTERNAL duk_bool_t duk_put_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx) {
  12621. duk_hthread *thr = (duk_hthread *) ctx;
  12622. DUK_ASSERT(ctx != NULL);
  12623. DUK_ASSERT_DISABLE(stridx >= 0);
  12624. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  12625. obj_index = duk_require_normalize_index(ctx, obj_index);
  12626. duk_push_hstring(ctx, DUK_HTHREAD_GET_STRING(thr, stridx));
  12627. duk_swap_top(ctx, -2); /* [val key] -> [key val] */
  12628. return duk_put_prop(ctx, obj_index);
  12629. }
  12630. DUK_EXTERNAL duk_bool_t duk_del_prop(duk_context *ctx, duk_idx_t obj_index) {
  12631. duk_hthread *thr = (duk_hthread *) ctx;
  12632. duk_tval *tv_obj;
  12633. duk_tval *tv_key;
  12634. duk_small_int_t throw_flag;
  12635. duk_bool_t rc;
  12636. DUK_ASSERT(ctx != NULL);
  12637. /* Note: copying tv_obj and tv_key to locals to shield against a valstack
  12638. * resize is not necessary for a property delete right now.
  12639. */
  12640. tv_obj = duk_require_tval(ctx, obj_index);
  12641. tv_key = duk_require_tval(ctx, -1);
  12642. throw_flag = duk_is_strict_call(ctx);
  12643. rc = duk_hobject_delprop(thr, tv_obj, tv_key, throw_flag);
  12644. DUK_ASSERT(rc == 0 || rc == 1);
  12645. duk_pop(ctx); /* remove key */
  12646. return rc;
  12647. }
  12648. DUK_EXTERNAL duk_bool_t duk_del_prop_string(duk_context *ctx, duk_idx_t obj_index, const char *key) {
  12649. DUK_ASSERT(ctx != NULL);
  12650. DUK_ASSERT(key != NULL);
  12651. obj_index = duk_require_normalize_index(ctx, obj_index);
  12652. duk_push_string(ctx, key);
  12653. return duk_del_prop(ctx, obj_index);
  12654. }
  12655. DUK_EXTERNAL duk_bool_t duk_del_prop_index(duk_context *ctx, duk_idx_t obj_index, duk_uarridx_t arr_index) {
  12656. DUK_ASSERT(ctx != NULL);
  12657. obj_index = duk_require_normalize_index(ctx, obj_index);
  12658. duk_push_uarridx(ctx, arr_index);
  12659. return duk_del_prop(ctx, obj_index);
  12660. }
  12661. DUK_INTERNAL duk_bool_t duk_del_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx) {
  12662. duk_hthread *thr = (duk_hthread *) ctx;
  12663. DUK_ASSERT(ctx != NULL);
  12664. DUK_ASSERT_DISABLE(stridx >= 0);
  12665. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  12666. obj_index = duk_require_normalize_index(ctx, obj_index);
  12667. duk_push_hstring(ctx, DUK_HTHREAD_GET_STRING(thr, stridx));
  12668. return duk_del_prop(ctx, obj_index);
  12669. }
  12670. DUK_EXTERNAL duk_bool_t duk_has_prop(duk_context *ctx, duk_idx_t obj_index) {
  12671. duk_hthread *thr = (duk_hthread *) ctx;
  12672. duk_tval *tv_obj;
  12673. duk_tval *tv_key;
  12674. duk_bool_t rc;
  12675. DUK_ASSERT(ctx != NULL);
  12676. /* Note: copying tv_obj and tv_key to locals to shield against a valstack
  12677. * resize is not necessary for a property existence check right now.
  12678. */
  12679. tv_obj = duk_require_tval(ctx, obj_index);
  12680. tv_key = duk_require_tval(ctx, -1);
  12681. rc = duk_hobject_hasprop(thr, tv_obj, tv_key);
  12682. DUK_ASSERT(rc == 0 || rc == 1);
  12683. duk_pop(ctx); /* remove key */
  12684. return rc; /* 1 if property found, 0 otherwise */
  12685. }
  12686. DUK_EXTERNAL duk_bool_t duk_has_prop_string(duk_context *ctx, duk_idx_t obj_index, const char *key) {
  12687. DUK_ASSERT(ctx != NULL);
  12688. DUK_ASSERT(key != NULL);
  12689. obj_index = duk_require_normalize_index(ctx, obj_index);
  12690. duk_push_string(ctx, key);
  12691. return duk_has_prop(ctx, obj_index);
  12692. }
  12693. DUK_EXTERNAL duk_bool_t duk_has_prop_index(duk_context *ctx, duk_idx_t obj_index, duk_uarridx_t arr_index) {
  12694. DUK_ASSERT(ctx != NULL);
  12695. obj_index = duk_require_normalize_index(ctx, obj_index);
  12696. duk_push_uarridx(ctx, arr_index);
  12697. return duk_has_prop(ctx, obj_index);
  12698. }
  12699. DUK_INTERNAL duk_bool_t duk_has_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx) {
  12700. duk_hthread *thr = (duk_hthread *) ctx;
  12701. DUK_ASSERT(ctx != NULL);
  12702. DUK_ASSERT_DISABLE(stridx >= 0);
  12703. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  12704. obj_index = duk_require_normalize_index(ctx, obj_index);
  12705. duk_push_hstring(ctx, DUK_HTHREAD_GET_STRING(thr, stridx));
  12706. return duk_has_prop(ctx, obj_index);
  12707. }
  12708. /* Define own property without inheritance looks and such. This differs from
  12709. * [[DefineOwnProperty]] because special behaviors (like Array 'length') are
  12710. * not invoked by this method. The caller must be careful to invoke any such
  12711. * behaviors if necessary.
  12712. */
  12713. DUK_INTERNAL void duk_xdef_prop(duk_context *ctx, duk_idx_t obj_index, duk_small_uint_t desc_flags) {
  12714. duk_hthread *thr = (duk_hthread *) ctx;
  12715. duk_hobject *obj;
  12716. duk_hstring *key;
  12717. DUK_ASSERT(ctx != NULL);
  12718. obj = duk_require_hobject(ctx, obj_index);
  12719. DUK_ASSERT(obj != NULL);
  12720. key = duk_to_hstring(ctx, -2);
  12721. DUK_ASSERT(key != NULL);
  12722. DUK_ASSERT(duk_require_tval(ctx, -1) != NULL);
  12723. duk_hobject_define_property_internal(thr, obj, key, desc_flags);
  12724. duk_pop(ctx); /* pop key */
  12725. }
  12726. DUK_INTERNAL void duk_xdef_prop_index(duk_context *ctx, duk_idx_t obj_index, duk_uarridx_t arr_index, duk_small_uint_t desc_flags) {
  12727. duk_hthread *thr = (duk_hthread *) ctx;
  12728. duk_hobject *obj;
  12729. DUK_ASSERT(ctx != NULL);
  12730. obj = duk_require_hobject(ctx, obj_index);
  12731. DUK_ASSERT(obj != NULL);
  12732. duk_hobject_define_property_internal_arridx(thr, obj, arr_index, desc_flags);
  12733. /* value popped by call */
  12734. }
  12735. DUK_INTERNAL void duk_xdef_prop_stridx(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_small_uint_t desc_flags) {
  12736. duk_hthread *thr = (duk_hthread *) ctx;
  12737. duk_hobject *obj;
  12738. duk_hstring *key;
  12739. DUK_ASSERT(ctx != NULL);
  12740. DUK_ASSERT_DISABLE(stridx >= 0);
  12741. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  12742. obj = duk_require_hobject(ctx, obj_index);
  12743. DUK_ASSERT(obj != NULL);
  12744. key = DUK_HTHREAD_GET_STRING(thr, stridx);
  12745. DUK_ASSERT(key != NULL);
  12746. DUK_ASSERT(duk_require_tval(ctx, -1) != NULL);
  12747. duk_hobject_define_property_internal(thr, obj, key, desc_flags);
  12748. /* value popped by call */
  12749. }
  12750. DUK_INTERNAL void duk_xdef_prop_stridx_builtin(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_small_int_t builtin_idx, duk_small_uint_t desc_flags) {
  12751. duk_hthread *thr = (duk_hthread *) ctx;
  12752. duk_hobject *obj;
  12753. duk_hstring *key;
  12754. DUK_ASSERT(ctx != NULL);
  12755. DUK_ASSERT_DISABLE(stridx >= 0);
  12756. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  12757. DUK_ASSERT_DISABLE(builtin_idx >= 0);
  12758. DUK_ASSERT(builtin_idx < DUK_NUM_BUILTINS);
  12759. obj = duk_require_hobject(ctx, obj_index);
  12760. DUK_ASSERT(obj != NULL);
  12761. key = DUK_HTHREAD_GET_STRING(thr, stridx);
  12762. DUK_ASSERT(key != NULL);
  12763. duk_push_hobject(ctx, thr->builtins[builtin_idx]);
  12764. duk_hobject_define_property_internal(thr, obj, key, desc_flags);
  12765. /* value popped by call */
  12766. }
  12767. /* This is a rare property helper; it sets the global thrower (E5 Section 13.2.3)
  12768. * setter/getter into an object property. This is needed by the 'arguments'
  12769. * object creation code, function instance creation code, and Function.prototype.bind().
  12770. */
  12771. DUK_INTERNAL void duk_xdef_prop_stridx_thrower(duk_context *ctx, duk_idx_t obj_index, duk_small_int_t stridx, duk_small_uint_t desc_flags) {
  12772. duk_hthread *thr = (duk_hthread *) ctx;
  12773. duk_hobject *obj = duk_require_hobject(ctx, obj_index);
  12774. duk_hobject *thrower = thr->builtins[DUK_BIDX_TYPE_ERROR_THROWER];
  12775. duk_hobject_define_accessor_internal(thr, obj, DUK_HTHREAD_GET_STRING(thr, stridx), thrower, thrower, desc_flags);
  12776. }
  12777. /* Object.defineProperty() equivalent C binding. */
  12778. DUK_EXTERNAL void duk_def_prop(duk_context *ctx, duk_idx_t obj_index, duk_uint_t flags) {
  12779. duk_hthread *thr = (duk_hthread *) ctx;
  12780. duk_idx_t idx_base;
  12781. duk_hobject *obj;
  12782. duk_hstring *key;
  12783. duk_idx_t idx_value;
  12784. duk_hobject *get;
  12785. duk_hobject *set;
  12786. duk_uint_t is_data_desc;
  12787. duk_uint_t is_acc_desc;
  12788. obj = duk_require_hobject(ctx, obj_index);
  12789. is_data_desc = flags & (DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE);
  12790. is_acc_desc = flags & (DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER);
  12791. if (is_data_desc && is_acc_desc) {
  12792. /* "Have" flags must not be conflicting so that they would
  12793. * apply to both a plain property and an accessor at the same
  12794. * time.
  12795. */
  12796. goto fail_invalid_desc;
  12797. }
  12798. idx_base = duk_get_top_index(ctx);
  12799. if (flags & DUK_DEFPROP_HAVE_SETTER) {
  12800. duk_require_type_mask(ctx, idx_base, DUK_TYPE_MASK_UNDEFINED |
  12801. DUK_TYPE_MASK_OBJECT |
  12802. DUK_TYPE_MASK_LIGHTFUNC);
  12803. set = duk_get_hobject_or_lfunc_coerce(ctx, idx_base);
  12804. if (set != NULL && !DUK_HOBJECT_IS_CALLABLE(set)) {
  12805. goto fail_not_callable;
  12806. }
  12807. idx_base--;
  12808. } else {
  12809. set = NULL;
  12810. }
  12811. if (flags & DUK_DEFPROP_HAVE_GETTER) {
  12812. duk_require_type_mask(ctx, idx_base, DUK_TYPE_MASK_UNDEFINED |
  12813. DUK_TYPE_MASK_OBJECT |
  12814. DUK_TYPE_MASK_LIGHTFUNC);
  12815. get = duk_get_hobject_or_lfunc_coerce(ctx, idx_base);
  12816. if (get != NULL && !DUK_HOBJECT_IS_CALLABLE(get)) {
  12817. goto fail_not_callable;
  12818. }
  12819. idx_base--;
  12820. } else {
  12821. get = NULL;
  12822. }
  12823. if (flags & DUK_DEFPROP_HAVE_VALUE) {
  12824. idx_value = idx_base;
  12825. idx_base--;
  12826. } else {
  12827. idx_value = (duk_idx_t) -1;
  12828. }
  12829. key = duk_require_hstring(ctx, idx_base);
  12830. duk_require_valid_index(ctx, idx_base);
  12831. duk_hobject_define_property_helper(ctx,
  12832. flags /*defprop_flags*/,
  12833. obj,
  12834. key,
  12835. idx_value,
  12836. get,
  12837. set);
  12838. /* Clean up stack */
  12839. duk_set_top(ctx, idx_base);
  12840. /* [ ... obj ... ] */
  12841. return;
  12842. fail_invalid_desc:
  12843. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INVALID_DESCRIPTOR);
  12844. return;
  12845. fail_not_callable:
  12846. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_CALLABLE);
  12847. return;
  12848. }
  12849. /*
  12850. * Object related
  12851. *
  12852. * Note: seal() and freeze() are accessible through Ecmascript bindings,
  12853. * and are not exposed through the API.
  12854. */
  12855. DUK_EXTERNAL void duk_compact(duk_context *ctx, duk_idx_t obj_index) {
  12856. duk_hthread *thr = (duk_hthread *) ctx;
  12857. duk_hobject *obj;
  12858. DUK_ASSERT(ctx != NULL);
  12859. obj = duk_get_hobject(ctx, obj_index);
  12860. if (obj) {
  12861. /* Note: this may fail, caller should protect the call if necessary */
  12862. duk_hobject_compact_props(thr, obj);
  12863. }
  12864. }
  12865. /* XXX: the duk_hobject_enum.c stack APIs should be reworked */
  12866. DUK_EXTERNAL void duk_enum(duk_context *ctx, duk_idx_t obj_index, duk_uint_t enum_flags) {
  12867. DUK_ASSERT(ctx != NULL);
  12868. duk_dup(ctx, obj_index);
  12869. duk_require_hobject_or_lfunc_coerce(ctx, -1);
  12870. duk_hobject_enumerator_create(ctx, enum_flags); /* [target] -> [enum] */
  12871. }
  12872. DUK_EXTERNAL duk_bool_t duk_next(duk_context *ctx, duk_idx_t enum_index, duk_bool_t get_value) {
  12873. DUK_ASSERT(ctx != NULL);
  12874. duk_require_hobject(ctx, enum_index);
  12875. duk_dup(ctx, enum_index);
  12876. return duk_hobject_enumerator_next(ctx, get_value);
  12877. }
  12878. /*
  12879. * Helpers for writing multiple properties
  12880. */
  12881. DUK_EXTERNAL void duk_put_function_list(duk_context *ctx, duk_idx_t obj_index, const duk_function_list_entry *funcs) {
  12882. const duk_function_list_entry *ent = funcs;
  12883. DUK_ASSERT(ctx != NULL);
  12884. obj_index = duk_require_normalize_index(ctx, obj_index);
  12885. if (ent != NULL) {
  12886. while (ent->key != NULL) {
  12887. duk_push_c_function(ctx, ent->value, ent->nargs);
  12888. duk_put_prop_string(ctx, obj_index, ent->key);
  12889. ent++;
  12890. }
  12891. }
  12892. }
  12893. DUK_EXTERNAL void duk_put_number_list(duk_context *ctx, duk_idx_t obj_index, const duk_number_list_entry *numbers) {
  12894. const duk_number_list_entry *ent = numbers;
  12895. DUK_ASSERT(ctx != NULL);
  12896. obj_index = duk_require_normalize_index(ctx, obj_index);
  12897. if (ent != NULL) {
  12898. while (ent->key != NULL) {
  12899. duk_push_number(ctx, ent->value);
  12900. duk_put_prop_string(ctx, obj_index, ent->key);
  12901. ent++;
  12902. }
  12903. }
  12904. }
  12905. /*
  12906. * Shortcut for accessing global object properties
  12907. */
  12908. DUK_EXTERNAL duk_bool_t duk_get_global_string(duk_context *ctx, const char *key) {
  12909. duk_hthread *thr = (duk_hthread *) ctx;
  12910. duk_bool_t ret;
  12911. DUK_ASSERT(ctx != NULL);
  12912. DUK_ASSERT(thr->builtins[DUK_BIDX_GLOBAL] != NULL);
  12913. /* XXX: direct implementation */
  12914. duk_push_hobject(ctx, thr->builtins[DUK_BIDX_GLOBAL]);
  12915. ret = duk_get_prop_string(ctx, -1, key);
  12916. duk_remove(ctx, -2);
  12917. return ret;
  12918. }
  12919. DUK_EXTERNAL duk_bool_t duk_put_global_string(duk_context *ctx, const char *key) {
  12920. duk_hthread *thr = (duk_hthread *) ctx;
  12921. duk_bool_t ret;
  12922. DUK_ASSERT(ctx != NULL);
  12923. DUK_ASSERT(thr->builtins[DUK_BIDX_GLOBAL] != NULL);
  12924. /* XXX: direct implementation */
  12925. duk_push_hobject(ctx, thr->builtins[DUK_BIDX_GLOBAL]);
  12926. duk_insert(ctx, -2);
  12927. ret = duk_put_prop_string(ctx, -2, key); /* [ ... global val ] -> [ ... global ] */
  12928. duk_pop(ctx);
  12929. return ret;
  12930. }
  12931. /*
  12932. * Object prototype
  12933. */
  12934. DUK_EXTERNAL void duk_get_prototype(duk_context *ctx, duk_idx_t index) {
  12935. duk_hthread *thr = (duk_hthread *) ctx;
  12936. duk_hobject *obj;
  12937. duk_hobject *proto;
  12938. DUK_ASSERT(ctx != NULL);
  12939. DUK_UNREF(thr);
  12940. obj = duk_require_hobject(ctx, index);
  12941. DUK_ASSERT(obj != NULL);
  12942. /* XXX: shared helper for duk_push_hobject_or_undefined()? */
  12943. proto = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, obj);
  12944. if (proto) {
  12945. duk_push_hobject(ctx, proto);
  12946. } else {
  12947. duk_push_undefined(ctx);
  12948. }
  12949. }
  12950. DUK_EXTERNAL void duk_set_prototype(duk_context *ctx, duk_idx_t index) {
  12951. duk_hthread *thr = (duk_hthread *) ctx;
  12952. duk_hobject *obj;
  12953. duk_hobject *proto;
  12954. DUK_ASSERT(ctx != NULL);
  12955. obj = duk_require_hobject(ctx, index);
  12956. DUK_ASSERT(obj != NULL);
  12957. duk_require_type_mask(ctx, -1, DUK_TYPE_MASK_UNDEFINED |
  12958. DUK_TYPE_MASK_OBJECT);
  12959. proto = duk_get_hobject(ctx, -1);
  12960. /* proto can also be NULL here (allowed explicitly) */
  12961. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, obj, proto);
  12962. duk_pop(ctx);
  12963. }
  12964. /*
  12965. * Object finalizer
  12966. */
  12967. /* XXX: these could be implemented as macros calling an internal function
  12968. * directly.
  12969. * XXX: same issue as with Duktape.fin: there's no way to delete the property
  12970. * now (just set it to undefined).
  12971. */
  12972. DUK_EXTERNAL void duk_get_finalizer(duk_context *ctx, duk_idx_t index) {
  12973. duk_get_prop_stridx(ctx, index, DUK_STRIDX_INT_FINALIZER);
  12974. }
  12975. DUK_EXTERNAL void duk_set_finalizer(duk_context *ctx, duk_idx_t index) {
  12976. duk_put_prop_stridx(ctx, index, DUK_STRIDX_INT_FINALIZER);
  12977. }
  12978. #line 1 "duk_api_stack.c"
  12979. /*
  12980. * API calls related to general value stack manipulation: resizing the value
  12981. * stack, pushing and popping values, type checking and reading values,
  12982. * coercing values, etc.
  12983. *
  12984. * Also contains internal functions (such as duk_get_tval()), defined
  12985. * in duk_api_internal.h, with semantics similar to the public API.
  12986. */
  12987. /* XXX: repetition of stack pre-checks -> helper or macro or inline */
  12988. /* XXX: shared api error strings, and perhaps even throw code for rare cases? */
  12989. /* include removed: duk_internal.h */
  12990. /*
  12991. * Forward declarations
  12992. */
  12993. DUK_LOCAL_DECL duk_idx_t duk__push_c_function_raw(duk_context *ctx, duk_c_function func, duk_idx_t nargs, duk_uint_t flags);
  12994. /*
  12995. * Global state for working around missing variadic macros
  12996. */
  12997. #ifndef DUK_USE_VARIADIC_MACROS
  12998. DUK_EXTERNAL const char *duk_api_global_filename = NULL;
  12999. DUK_EXTERNAL duk_int_t duk_api_global_line = 0;
  13000. #endif
  13001. /*
  13002. * Helpers
  13003. */
  13004. #if defined(DUK_USE_VALSTACK_UNSAFE)
  13005. /* Faster but value stack overruns are memory unsafe. */
  13006. #define DUK__CHECK_SPACE() do { \
  13007. DUK_ASSERT(!(thr->valstack_top >= thr->valstack_end)); \
  13008. } while (0)
  13009. #else
  13010. #define DUK__CHECK_SPACE() do { \
  13011. if (thr->valstack_top >= thr->valstack_end) { \
  13012. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK); \
  13013. } \
  13014. } while (0)
  13015. #endif
  13016. DUK_LOCAL duk_int_t duk__api_coerce_d2i(duk_context *ctx, duk_idx_t index, duk_bool_t require) {
  13017. duk_hthread *thr;
  13018. duk_tval *tv;
  13019. duk_small_int_t c;
  13020. duk_double_t d;
  13021. thr = (duk_hthread *) ctx;
  13022. tv = duk_get_tval(ctx, index);
  13023. if (tv == NULL) {
  13024. goto error_notnumber;
  13025. }
  13026. /*
  13027. * Special cases like NaN and +/- Infinity are handled explicitly
  13028. * because a plain C coercion from double to int handles these cases
  13029. * in undesirable ways. For instance, NaN may coerce to INT_MIN
  13030. * (not zero), and INT_MAX + 1 may coerce to INT_MIN (not INT_MAX).
  13031. *
  13032. * This double-to-int coercion differs from ToInteger() because it
  13033. * has a finite range (ToInteger() allows e.g. +/- Infinity). It
  13034. * also differs from ToInt32() because the INT_MIN/INT_MAX clamping
  13035. * depends on the size of the int type on the platform. In particular,
  13036. * on platforms with a 64-bit int type, the full range is allowed.
  13037. */
  13038. #if defined(DUK_USE_FASTINT)
  13039. if (DUK_TVAL_IS_FASTINT(tv)) {
  13040. duk_int64_t t = DUK_TVAL_GET_FASTINT(tv);
  13041. #if (DUK_INT_MAX <= 0x7fffffffL)
  13042. /* Clamping only necessary for 32-bit ints. */
  13043. if (t < DUK_INT_MIN) {
  13044. t = DUK_INT_MIN;
  13045. } else if (t > DUK_INT_MAX) {
  13046. t = DUK_INT_MAX;
  13047. }
  13048. #endif
  13049. return (duk_int_t) t;
  13050. }
  13051. #endif
  13052. if (DUK_TVAL_IS_NUMBER(tv)) {
  13053. d = DUK_TVAL_GET_NUMBER(tv);
  13054. c = (duk_small_int_t) DUK_FPCLASSIFY(d);
  13055. if (c == DUK_FP_NAN) {
  13056. return 0;
  13057. } else if (d < (duk_double_t) DUK_INT_MIN) {
  13058. /* covers -Infinity */
  13059. return DUK_INT_MIN;
  13060. } else if (d > (duk_double_t) DUK_INT_MAX) {
  13061. /* covers +Infinity */
  13062. return DUK_INT_MAX;
  13063. } else {
  13064. /* coerce towards zero */
  13065. return (duk_int_t) d;
  13066. }
  13067. }
  13068. error_notnumber:
  13069. if (require) {
  13070. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_NUMBER);
  13071. } else {
  13072. return 0;
  13073. }
  13074. }
  13075. DUK_LOCAL duk_uint_t duk__api_coerce_d2ui(duk_context *ctx, duk_idx_t index, duk_bool_t require) {
  13076. duk_hthread *thr;
  13077. duk_tval *tv;
  13078. duk_small_int_t c;
  13079. duk_double_t d;
  13080. /* Same as above but for unsigned int range. */
  13081. thr = (duk_hthread *) ctx;
  13082. tv = duk_get_tval(ctx, index);
  13083. if (tv == NULL) {
  13084. goto error_notnumber;
  13085. }
  13086. #if defined(DUK_USE_FASTINT)
  13087. if (DUK_TVAL_IS_FASTINT(tv)) {
  13088. duk_int64_t t = DUK_TVAL_GET_FASTINT(tv);
  13089. if (t < 0) {
  13090. t = 0;
  13091. }
  13092. #if (DUK_UINT_MAX <= 0xffffffffUL)
  13093. /* Clamping only necessary for 32-bit ints. */
  13094. else if (t > DUK_UINT_MAX) {
  13095. t = DUK_UINT_MAX;
  13096. }
  13097. #endif
  13098. return (duk_uint_t) t;
  13099. }
  13100. #endif
  13101. if (DUK_TVAL_IS_NUMBER(tv)) {
  13102. d = DUK_TVAL_GET_NUMBER(tv);
  13103. c = (duk_small_int_t) DUK_FPCLASSIFY(d);
  13104. if (c == DUK_FP_NAN) {
  13105. return 0;
  13106. } else if (d < 0.0) {
  13107. /* covers -Infinity */
  13108. return (duk_uint_t) 0;
  13109. } else if (d > (duk_double_t) DUK_UINT_MAX) {
  13110. /* covers +Infinity */
  13111. return (duk_uint_t) DUK_UINT_MAX;
  13112. } else {
  13113. /* coerce towards zero */
  13114. return (duk_uint_t) d;
  13115. }
  13116. }
  13117. error_notnumber:
  13118. if (require) {
  13119. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_NUMBER);
  13120. } else {
  13121. return 0;
  13122. }
  13123. }
  13124. /*
  13125. * Stack index validation/normalization and getting a stack duk_tval ptr.
  13126. *
  13127. * These are called by many API entrypoints so the implementations must be
  13128. * fast and "inlined".
  13129. *
  13130. * There's some repetition because of this; keep the functions in sync.
  13131. */
  13132. DUK_EXTERNAL duk_idx_t duk_normalize_index(duk_context *ctx, duk_idx_t index) {
  13133. duk_hthread *thr = (duk_hthread *) ctx;
  13134. duk_idx_t vs_size;
  13135. DUK_ASSERT(ctx != NULL);
  13136. DUK_ASSERT(DUK_INVALID_INDEX < 0);
  13137. /* Care must be taken to avoid pointer wrapping in the index
  13138. * validation. For instance, on a 32-bit platform with 8-byte
  13139. * duk_tval the index 0x20000000UL would wrap the memory space
  13140. * once.
  13141. */
  13142. /* Assume value stack sizes (in elements) fits into duk_idx_t. */
  13143. vs_size = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  13144. DUK_ASSERT(vs_size >= 0);
  13145. if (index < 0) {
  13146. index = vs_size + index;
  13147. if (DUK_UNLIKELY(index < 0)) {
  13148. /* Also catches index == DUK_INVALID_INDEX: vs_size >= 0
  13149. * so that vs_size + DUK_INVALID_INDEX cannot underflow
  13150. * and will always be negative.
  13151. */
  13152. return DUK_INVALID_INDEX;
  13153. }
  13154. } else {
  13155. /* since index non-negative */
  13156. DUK_ASSERT(index != DUK_INVALID_INDEX);
  13157. if (DUK_UNLIKELY(index >= vs_size)) {
  13158. return DUK_INVALID_INDEX;
  13159. }
  13160. }
  13161. DUK_ASSERT(index >= 0);
  13162. DUK_ASSERT(index < vs_size);
  13163. return index;
  13164. }
  13165. DUK_EXTERNAL duk_idx_t duk_require_normalize_index(duk_context *ctx, duk_idx_t index) {
  13166. duk_hthread *thr = (duk_hthread *) ctx;
  13167. duk_idx_t vs_size;
  13168. DUK_ASSERT(ctx != NULL);
  13169. DUK_ASSERT(DUK_INVALID_INDEX < 0);
  13170. vs_size = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  13171. DUK_ASSERT(vs_size >= 0);
  13172. if (index < 0) {
  13173. index = vs_size + index;
  13174. if (DUK_UNLIKELY(index < 0)) {
  13175. goto invalid_index;
  13176. }
  13177. } else {
  13178. DUK_ASSERT(index != DUK_INVALID_INDEX);
  13179. if (DUK_UNLIKELY(index >= vs_size)) {
  13180. goto invalid_index;
  13181. }
  13182. }
  13183. DUK_ASSERT(index >= 0);
  13184. DUK_ASSERT(index < vs_size);
  13185. return index;
  13186. invalid_index:
  13187. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_INDEX);
  13188. return 0; /* unreachable */
  13189. }
  13190. DUK_INTERNAL duk_tval *duk_get_tval(duk_context *ctx, duk_idx_t index) {
  13191. duk_hthread *thr = (duk_hthread *) ctx;
  13192. duk_idx_t vs_size;
  13193. DUK_ASSERT(ctx != NULL);
  13194. DUK_ASSERT(DUK_INVALID_INDEX < 0);
  13195. vs_size = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  13196. DUK_ASSERT(vs_size >= 0);
  13197. if (index < 0) {
  13198. index = vs_size + index;
  13199. if (DUK_UNLIKELY(index < 0)) {
  13200. return NULL;
  13201. }
  13202. } else {
  13203. DUK_ASSERT(index != DUK_INVALID_INDEX);
  13204. if (DUK_UNLIKELY(index >= vs_size)) {
  13205. return NULL;
  13206. }
  13207. }
  13208. DUK_ASSERT(index >= 0);
  13209. DUK_ASSERT(index < vs_size);
  13210. return thr->valstack_bottom + index;
  13211. }
  13212. DUK_INTERNAL duk_tval *duk_require_tval(duk_context *ctx, duk_idx_t index) {
  13213. duk_hthread *thr = (duk_hthread *) ctx;
  13214. duk_idx_t vs_size;
  13215. DUK_ASSERT(ctx != NULL);
  13216. DUK_ASSERT(DUK_INVALID_INDEX < 0);
  13217. vs_size = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  13218. DUK_ASSERT(vs_size >= 0);
  13219. if (index < 0) {
  13220. index = vs_size + index;
  13221. if (DUK_UNLIKELY(index < 0)) {
  13222. goto invalid_index;
  13223. }
  13224. } else {
  13225. DUK_ASSERT(index != DUK_INVALID_INDEX);
  13226. if (DUK_UNLIKELY(index >= vs_size)) {
  13227. goto invalid_index;
  13228. }
  13229. }
  13230. DUK_ASSERT(index >= 0);
  13231. DUK_ASSERT(index < vs_size);
  13232. return thr->valstack_bottom + index;
  13233. invalid_index:
  13234. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_INDEX);
  13235. return NULL;
  13236. }
  13237. /* Non-critical. */
  13238. DUK_EXTERNAL duk_bool_t duk_is_valid_index(duk_context *ctx, duk_idx_t index) {
  13239. DUK_ASSERT(DUK_INVALID_INDEX < 0);
  13240. return (duk_normalize_index(ctx, index) >= 0);
  13241. }
  13242. /* Non-critical. */
  13243. DUK_EXTERNAL void duk_require_valid_index(duk_context *ctx, duk_idx_t index) {
  13244. duk_hthread *thr = (duk_hthread *) ctx;
  13245. DUK_ASSERT(ctx != NULL);
  13246. DUK_ASSERT(DUK_INVALID_INDEX < 0);
  13247. if (duk_normalize_index(ctx, index) < 0) {
  13248. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_INDEX);
  13249. }
  13250. }
  13251. /*
  13252. * Value stack top handling
  13253. */
  13254. DUK_EXTERNAL duk_idx_t duk_get_top(duk_context *ctx) {
  13255. duk_hthread *thr = (duk_hthread *) ctx;
  13256. DUK_ASSERT(ctx != NULL);
  13257. return (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  13258. }
  13259. /* set stack top within currently allocated range, but don't reallocate */
  13260. DUK_EXTERNAL void duk_set_top(duk_context *ctx, duk_idx_t index) {
  13261. duk_hthread *thr = (duk_hthread *) ctx;
  13262. duk_idx_t vs_size;
  13263. duk_idx_t vs_limit;
  13264. duk_idx_t count;
  13265. duk_tval tv_tmp;
  13266. duk_tval *tv;
  13267. DUK_ASSERT(ctx != NULL);
  13268. DUK_ASSERT(DUK_INVALID_INDEX < 0);
  13269. vs_size = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  13270. vs_limit = (duk_idx_t) (thr->valstack_end - thr->valstack_bottom);
  13271. if (index < 0) {
  13272. /* Negative indices are always within allocated stack but
  13273. * must not go below zero index.
  13274. */
  13275. index = vs_size + index;
  13276. if (index < 0) {
  13277. /* Also catches index == DUK_INVALID_INDEX. */
  13278. goto invalid_index;
  13279. }
  13280. } else {
  13281. /* Positive index can be higher than valstack top but must
  13282. * not go above allocated stack (equality is OK).
  13283. */
  13284. if (index > vs_limit) {
  13285. goto invalid_index;
  13286. }
  13287. }
  13288. DUK_ASSERT(index >= 0);
  13289. DUK_ASSERT(index <= vs_limit);
  13290. if (index >= vs_size) {
  13291. /* Stack size increases or stays the same. Fill the new
  13292. * entries (if any) with undefined. No pointer stability
  13293. * issues here so we can use a running pointer.
  13294. */
  13295. tv = thr->valstack_top;
  13296. count = index - vs_size;
  13297. DUK_ASSERT(count >= 0);
  13298. while (count > 0) {
  13299. /* no need to decref previous or new value */
  13300. count--;
  13301. DUK_ASSERT(DUK_TVAL_IS_UNDEFINED_UNUSED(tv));
  13302. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv);
  13303. tv++;
  13304. }
  13305. thr->valstack_top = tv;
  13306. } else {
  13307. /* Stack size decreases, DECREF entries which are above the
  13308. * new top. Each DECREF potentially invalidates valstack
  13309. * pointers, so don't hold on to pointers. The valstack top
  13310. * must also be updated on every loop in case a GC is triggered.
  13311. */
  13312. /* XXX: Here it would be useful to have a DECREF macro which
  13313. * doesn't need a NULL check, and does refzero queueing without
  13314. * running the refzero algorithm. There would be no pointer
  13315. * instability in this case, and code could be inlined. After
  13316. * the loop, one call to refzero would be needed.
  13317. */
  13318. count = vs_size - index;
  13319. DUK_ASSERT(count > 0);
  13320. while (count > 0) {
  13321. count--;
  13322. tv = --thr->valstack_top; /* tv -> value just before prev top value */
  13323. DUK_ASSERT(tv >= thr->valstack_bottom);
  13324. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  13325. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  13326. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  13327. /* XXX: fast primitive to set a bunch of values to UNDEFINED_UNUSED */
  13328. }
  13329. }
  13330. return;
  13331. invalid_index:
  13332. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_INDEX);
  13333. }
  13334. DUK_EXTERNAL duk_idx_t duk_get_top_index(duk_context *ctx) {
  13335. duk_hthread *thr = (duk_hthread *) ctx;
  13336. duk_idx_t ret;
  13337. DUK_ASSERT(ctx != NULL);
  13338. ret = ((duk_idx_t) (thr->valstack_top - thr->valstack_bottom)) - 1;
  13339. if (DUK_UNLIKELY(ret < 0)) {
  13340. /* Return invalid index; if caller uses this without checking
  13341. * in another API call, the index won't map to a valid stack
  13342. * entry.
  13343. */
  13344. return DUK_INVALID_INDEX;
  13345. }
  13346. return ret;
  13347. }
  13348. DUK_EXTERNAL duk_idx_t duk_require_top_index(duk_context *ctx) {
  13349. duk_hthread *thr = (duk_hthread *) ctx;
  13350. duk_idx_t ret;
  13351. DUK_ASSERT(ctx != NULL);
  13352. ret = ((duk_idx_t) (thr->valstack_top - thr->valstack_bottom)) - 1;
  13353. if (DUK_UNLIKELY(ret < 0)) {
  13354. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_INDEX);
  13355. }
  13356. return ret;
  13357. }
  13358. /*
  13359. * Value stack resizing.
  13360. *
  13361. * This resizing happens above the current "top": the value stack can be
  13362. * grown or shrunk, but the "top" is not affected. The value stack cannot
  13363. * be resized to a size below the current "top".
  13364. *
  13365. * The low level reallocation primitive must carefully recompute all value
  13366. * stack pointers, and must also work if ALL pointers are NULL. The resize
  13367. * is quite tricky because the valstack realloc may cause a mark-and-sweep,
  13368. * which may run finalizers. Running finalizers may resize the valstack
  13369. * recursively (the same value stack we're working on). So, after realloc
  13370. * returns, we know that the valstack "top" should still be the same (there
  13371. * should not be live values above the "top"), but its underlying size and
  13372. * pointer may have changed.
  13373. */
  13374. /* XXX: perhaps refactor this to allow caller to specify some parameters, or
  13375. * at least a 'compact' flag which skips any spare or round-up .. useful for
  13376. * emergency gc.
  13377. */
  13378. DUK_LOCAL duk_bool_t duk__resize_valstack(duk_context *ctx, duk_size_t new_size) {
  13379. duk_hthread *thr = (duk_hthread *) ctx;
  13380. duk_ptrdiff_t old_bottom_offset;
  13381. duk_ptrdiff_t old_top_offset;
  13382. duk_ptrdiff_t old_end_offset_post;
  13383. #ifdef DUK_USE_DEBUG
  13384. duk_ptrdiff_t old_end_offset_pre;
  13385. duk_tval *old_valstack_pre;
  13386. duk_tval *old_valstack_post;
  13387. #endif
  13388. duk_tval *new_valstack;
  13389. duk_tval *p;
  13390. duk_size_t new_alloc_size;
  13391. DUK_ASSERT(ctx != NULL);
  13392. DUK_ASSERT(thr != NULL);
  13393. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  13394. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  13395. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  13396. DUK_ASSERT((duk_size_t) (thr->valstack_top - thr->valstack) <= new_size); /* can't resize below 'top' */
  13397. DUK_ASSERT(new_size <= thr->valstack_max); /* valstack limit caller has check, prevents wrapping */
  13398. DUK_ASSERT(new_size <= DUK_SIZE_MAX / sizeof(duk_tval)); /* specific assert for wrapping */
  13399. /* get pointer offsets for tweaking below */
  13400. old_bottom_offset = (((duk_uint8_t *) thr->valstack_bottom) - ((duk_uint8_t *) thr->valstack));
  13401. old_top_offset = (((duk_uint8_t *) thr->valstack_top) - ((duk_uint8_t *) thr->valstack));
  13402. #ifdef DUK_USE_DEBUG
  13403. old_end_offset_pre = (((duk_uint8_t *) thr->valstack_end) - ((duk_uint8_t *) thr->valstack)); /* not very useful, used for debugging */
  13404. old_valstack_pre = thr->valstack;
  13405. #endif
  13406. /* Allocate a new valstack.
  13407. *
  13408. * Note: cannot use a plain DUK_REALLOC() because a mark-and-sweep may
  13409. * invalidate the original thr->valstack base pointer inside the realloc
  13410. * process. See doc/memory-management.txt.
  13411. */
  13412. new_alloc_size = sizeof(duk_tval) * new_size;
  13413. new_valstack = (duk_tval *) DUK_REALLOC_INDIRECT(thr->heap, duk_hthread_get_valstack_ptr, (void *) thr, new_alloc_size);
  13414. if (!new_valstack) {
  13415. /* Because new_size != 0, if condition doesn't need to be
  13416. * (new_valstack != NULL || new_size == 0).
  13417. */
  13418. DUK_ASSERT(new_size != 0);
  13419. DUK_D(DUK_DPRINT("failed to resize valstack to %lu entries (%lu bytes)",
  13420. (unsigned long) new_size, (unsigned long) new_alloc_size));
  13421. return 0;
  13422. }
  13423. /* Note: the realloc may have triggered a mark-and-sweep which may
  13424. * have resized our valstack internally. However, the mark-and-sweep
  13425. * MUST NOT leave the stack bottom/top in a different state. Particular
  13426. * assumptions and facts:
  13427. *
  13428. * - The thr->valstack pointer may be different after realloc,
  13429. * and the offset between thr->valstack_end <-> thr->valstack
  13430. * may have changed.
  13431. * - The offset between thr->valstack_bottom <-> thr->valstack
  13432. * and thr->valstack_top <-> thr->valstack MUST NOT have changed,
  13433. * because mark-and-sweep must adhere to a strict stack policy.
  13434. * In other words, logical bottom and top MUST NOT have changed.
  13435. * - All values above the top are unreachable but are initialized
  13436. * to UNDEFINED_UNUSED, up to the post-realloc valstack_end.
  13437. * - 'old_end_offset' must be computed after realloc to be correct.
  13438. */
  13439. DUK_ASSERT((((duk_uint8_t *) thr->valstack_bottom) - ((duk_uint8_t *) thr->valstack)) == old_bottom_offset);
  13440. DUK_ASSERT((((duk_uint8_t *) thr->valstack_top) - ((duk_uint8_t *) thr->valstack)) == old_top_offset);
  13441. /* success, fixup pointers */
  13442. old_end_offset_post = (((duk_uint8_t *) thr->valstack_end) - ((duk_uint8_t *) thr->valstack)); /* must be computed after realloc */
  13443. #ifdef DUK_USE_DEBUG
  13444. old_valstack_post = thr->valstack;
  13445. #endif
  13446. thr->valstack = new_valstack;
  13447. thr->valstack_end = new_valstack + new_size;
  13448. thr->valstack_bottom = (duk_tval *) ((duk_uint8_t *) new_valstack + old_bottom_offset);
  13449. thr->valstack_top = (duk_tval *) ((duk_uint8_t *) new_valstack + old_top_offset);
  13450. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  13451. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  13452. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  13453. /* useful for debugging */
  13454. #ifdef DUK_USE_DEBUG
  13455. if (old_end_offset_pre != old_end_offset_post) {
  13456. DUK_D(DUK_DPRINT("valstack was resized during valstack_resize(), probably by mark-and-sweep; "
  13457. "end offset changed: %lu -> %lu",
  13458. (unsigned long) old_end_offset_pre,
  13459. (unsigned long) old_end_offset_post));
  13460. }
  13461. if (old_valstack_pre != old_valstack_post) {
  13462. DUK_D(DUK_DPRINT("valstack pointer changed during valstack_resize(), probably by mark-and-sweep: %p -> %p",
  13463. (void *) old_valstack_pre,
  13464. (void *) old_valstack_post));
  13465. }
  13466. #endif
  13467. DUK_DD(DUK_DDPRINT("resized valstack to %lu elements (%lu bytes), bottom=%ld, top=%ld, "
  13468. "new pointers: start=%p end=%p bottom=%p top=%p",
  13469. (unsigned long) new_size, (unsigned long) new_alloc_size,
  13470. (long) (thr->valstack_bottom - thr->valstack),
  13471. (long) (thr->valstack_top - thr->valstack),
  13472. (void *) thr->valstack, (void *) thr->valstack_end,
  13473. (void *) thr->valstack_bottom, (void *) thr->valstack_top));
  13474. /* init newly allocated slots (only) */
  13475. p = (duk_tval *) ((duk_uint8_t *) thr->valstack + old_end_offset_post);
  13476. while (p < thr->valstack_end) {
  13477. /* never executed if new size is smaller */
  13478. DUK_TVAL_SET_UNDEFINED_UNUSED(p);
  13479. p++;
  13480. }
  13481. /* assertion check: we maintain elements above top in known state */
  13482. #ifdef DUK_USE_ASSERTIONS
  13483. p = thr->valstack_top;
  13484. while (p < thr->valstack_end) {
  13485. /* everything above old valstack top should be preinitialized now */
  13486. DUK_ASSERT(DUK_TVAL_IS_UNDEFINED_UNUSED(p));
  13487. p++;
  13488. }
  13489. #endif
  13490. return 1;
  13491. }
  13492. DUK_INTERNAL
  13493. duk_bool_t duk_valstack_resize_raw(duk_context *ctx,
  13494. duk_size_t min_new_size,
  13495. duk_small_uint_t flags) {
  13496. duk_hthread *thr = (duk_hthread *) ctx;
  13497. duk_size_t old_size;
  13498. duk_size_t new_size;
  13499. duk_bool_t is_shrink = 0;
  13500. duk_small_uint_t shrink_flag = (flags & DUK_VSRESIZE_FLAG_SHRINK);
  13501. duk_small_uint_t compact_flag = (flags & DUK_VSRESIZE_FLAG_COMPACT);
  13502. duk_small_uint_t throw_flag = (flags & DUK_VSRESIZE_FLAG_THROW);
  13503. DUK_DDD(DUK_DDDPRINT("check valstack resize: min_new_size=%lu, curr_size=%ld, curr_top=%ld, "
  13504. "curr_bottom=%ld, shrink=%d, compact=%d, throw=%d",
  13505. (unsigned long) min_new_size,
  13506. (long) (thr->valstack_end - thr->valstack),
  13507. (long) (thr->valstack_top - thr->valstack),
  13508. (long) (thr->valstack_bottom - thr->valstack),
  13509. (int) shrink_flag, (int) compact_flag, (int) throw_flag));
  13510. DUK_ASSERT(ctx != NULL);
  13511. DUK_ASSERT(thr != NULL);
  13512. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  13513. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  13514. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  13515. old_size = (duk_size_t) (thr->valstack_end - thr->valstack);
  13516. if (min_new_size <= old_size) {
  13517. is_shrink = 1;
  13518. if (!shrink_flag ||
  13519. old_size - min_new_size < DUK_VALSTACK_SHRINK_THRESHOLD) {
  13520. DUK_DDD(DUK_DDDPRINT("no need to grow or shrink valstack"));
  13521. return 1;
  13522. }
  13523. }
  13524. new_size = min_new_size;
  13525. if (!compact_flag) {
  13526. if (is_shrink) {
  13527. /* shrink case; leave some spare */
  13528. new_size += DUK_VALSTACK_SHRINK_SPARE;
  13529. }
  13530. /* round up roughly to next 'grow step' */
  13531. new_size = (new_size / DUK_VALSTACK_GROW_STEP + 1) * DUK_VALSTACK_GROW_STEP;
  13532. }
  13533. DUK_DD(DUK_DDPRINT("want to %s valstack: %lu -> %lu elements (min_new_size %lu)",
  13534. (const char *) (new_size > old_size ? "grow" : "shrink"),
  13535. (unsigned long) old_size, (unsigned long) new_size,
  13536. (unsigned long) min_new_size));
  13537. if (new_size > thr->valstack_max) {
  13538. /* Note: may be triggered even if minimal new_size would not reach the limit,
  13539. * plan limit accordingly (taking DUK_VALSTACK_GROW_STEP into account).
  13540. */
  13541. if (throw_flag) {
  13542. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_VALSTACK_LIMIT);
  13543. } else {
  13544. return 0;
  13545. }
  13546. }
  13547. /*
  13548. * When resizing the valstack, a mark-and-sweep may be triggered for
  13549. * the allocation of the new valstack. If the mark-and-sweep needs
  13550. * to use our thread for something, it may cause *the same valstack*
  13551. * to be resized recursively. This happens e.g. when mark-and-sweep
  13552. * finalizers are called. This is taken into account carefully in
  13553. * duk__resize_valstack().
  13554. *
  13555. * 'new_size' is known to be <= valstack_max, which ensures that
  13556. * size_t and pointer arithmetic won't wrap in duk__resize_valstack().
  13557. */
  13558. if (!duk__resize_valstack(ctx, new_size)) {
  13559. if (is_shrink) {
  13560. DUK_DD(DUK_DDPRINT("valstack resize failed, but is a shrink, ignore"));
  13561. return 1;
  13562. }
  13563. DUK_DD(DUK_DDPRINT("valstack resize failed"));
  13564. if (throw_flag) {
  13565. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_FAILED_TO_EXTEND_VALSTACK);
  13566. } else {
  13567. return 0;
  13568. }
  13569. }
  13570. DUK_DDD(DUK_DDDPRINT("valstack resize successful"));
  13571. return 1;
  13572. }
  13573. DUK_EXTERNAL duk_bool_t duk_check_stack(duk_context *ctx, duk_idx_t extra) {
  13574. duk_hthread *thr = (duk_hthread *) ctx;
  13575. duk_size_t min_new_size;
  13576. DUK_ASSERT(ctx != NULL);
  13577. DUK_ASSERT(thr != NULL);
  13578. if (DUK_UNLIKELY(extra < 0)) {
  13579. /* Clamping to zero makes the API more robust to calling code
  13580. * calculation errors.
  13581. */
  13582. extra = 0;
  13583. }
  13584. min_new_size = (thr->valstack_top - thr->valstack) + extra + DUK_VALSTACK_INTERNAL_EXTRA;
  13585. return duk_valstack_resize_raw(ctx,
  13586. min_new_size, /* min_new_size */
  13587. 0 /* no shrink */ | /* flags */
  13588. 0 /* no compact */ |
  13589. 0 /* no throw */);
  13590. }
  13591. DUK_EXTERNAL void duk_require_stack(duk_context *ctx, duk_idx_t extra) {
  13592. duk_hthread *thr = (duk_hthread *) ctx;
  13593. duk_size_t min_new_size;
  13594. DUK_ASSERT(ctx != NULL);
  13595. DUK_ASSERT(thr != NULL);
  13596. if (DUK_UNLIKELY(extra < 0)) {
  13597. /* Clamping to zero makes the API more robust to calling code
  13598. * calculation errors.
  13599. */
  13600. extra = 0;
  13601. }
  13602. min_new_size = (thr->valstack_top - thr->valstack) + extra + DUK_VALSTACK_INTERNAL_EXTRA;
  13603. (void) duk_valstack_resize_raw(ctx,
  13604. min_new_size, /* min_new_size */
  13605. 0 /* no shrink */ | /* flags */
  13606. 0 /* no compact */ |
  13607. DUK_VSRESIZE_FLAG_THROW);
  13608. }
  13609. DUK_EXTERNAL duk_bool_t duk_check_stack_top(duk_context *ctx, duk_idx_t top) {
  13610. duk_size_t min_new_size;
  13611. DUK_ASSERT(ctx != NULL);
  13612. if (DUK_UNLIKELY(top < 0)) {
  13613. /* Clamping to zero makes the API more robust to calling code
  13614. * calculation errors.
  13615. */
  13616. top = 0;
  13617. }
  13618. min_new_size = top + DUK_VALSTACK_INTERNAL_EXTRA;
  13619. return duk_valstack_resize_raw(ctx,
  13620. min_new_size, /* min_new_size */
  13621. 0 /* no shrink */ | /* flags */
  13622. 0 /* no compact */ |
  13623. 0 /* no throw */);
  13624. }
  13625. DUK_EXTERNAL void duk_require_stack_top(duk_context *ctx, duk_idx_t top) {
  13626. duk_size_t min_new_size;
  13627. DUK_ASSERT(ctx != NULL);
  13628. if (DUK_UNLIKELY(top < 0)) {
  13629. /* Clamping to zero makes the API more robust to calling code
  13630. * calculation errors.
  13631. */
  13632. top = 0;
  13633. }
  13634. min_new_size = top + DUK_VALSTACK_INTERNAL_EXTRA;
  13635. (void) duk_valstack_resize_raw(ctx,
  13636. min_new_size, /* min_new_size */
  13637. 0 /* no shrink */ | /* flags */
  13638. 0 /* no compact */ |
  13639. DUK_VSRESIZE_FLAG_THROW);
  13640. }
  13641. /*
  13642. * Basic stack manipulation: swap, dup, insert, replace, etc
  13643. */
  13644. DUK_EXTERNAL void duk_swap(duk_context *ctx, duk_idx_t index1, duk_idx_t index2) {
  13645. duk_tval *tv1;
  13646. duk_tval *tv2;
  13647. duk_tval tv_tmp;
  13648. DUK_ASSERT(ctx != NULL);
  13649. tv1 = duk_require_tval(ctx, index1);
  13650. DUK_ASSERT(tv1 != NULL);
  13651. tv2 = duk_require_tval(ctx, index2);
  13652. DUK_ASSERT(tv2 != NULL);
  13653. /* If tv1==tv2 this is a NOP, no check is needed */
  13654. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  13655. DUK_TVAL_SET_TVAL(tv1, tv2);
  13656. DUK_TVAL_SET_TVAL(tv2, &tv_tmp);
  13657. }
  13658. DUK_EXTERNAL void duk_swap_top(duk_context *ctx, duk_idx_t index) {
  13659. DUK_ASSERT(ctx != NULL);
  13660. duk_swap(ctx, index, -1);
  13661. }
  13662. DUK_EXTERNAL void duk_dup(duk_context *ctx, duk_idx_t from_index) {
  13663. duk_hthread *thr;
  13664. duk_tval *tv_from;
  13665. duk_tval *tv_to;
  13666. DUK_ASSERT(ctx != NULL);
  13667. thr = (duk_hthread *) ctx;
  13668. DUK__CHECK_SPACE();
  13669. tv_from = duk_require_tval(ctx, from_index);
  13670. tv_to = thr->valstack_top++;
  13671. DUK_ASSERT(tv_from != NULL);
  13672. DUK_ASSERT(tv_to != NULL);
  13673. DUK_TVAL_SET_TVAL(tv_to, tv_from);
  13674. DUK_TVAL_INCREF(thr, tv_to); /* no side effects */
  13675. }
  13676. DUK_EXTERNAL void duk_dup_top(duk_context *ctx) {
  13677. duk_hthread *thr;
  13678. duk_tval *tv_from;
  13679. duk_tval *tv_to;
  13680. DUK_ASSERT(ctx != NULL);
  13681. thr = (duk_hthread *) ctx;
  13682. DUK__CHECK_SPACE();
  13683. if (thr->valstack_top - thr->valstack_bottom <= 0) {
  13684. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_INDEX);
  13685. }
  13686. tv_from = thr->valstack_top - 1;
  13687. tv_to = thr->valstack_top++;
  13688. DUK_ASSERT(tv_from != NULL);
  13689. DUK_ASSERT(tv_to != NULL);
  13690. DUK_TVAL_SET_TVAL(tv_to, tv_from);
  13691. DUK_TVAL_INCREF(thr, tv_to); /* no side effects */
  13692. }
  13693. DUK_EXTERNAL void duk_insert(duk_context *ctx, duk_idx_t to_index) {
  13694. duk_tval *p;
  13695. duk_tval *q;
  13696. duk_tval tv_tmp;
  13697. duk_size_t nbytes;
  13698. DUK_ASSERT(ctx != NULL);
  13699. p = duk_require_tval(ctx, to_index);
  13700. DUK_ASSERT(p != NULL);
  13701. q = duk_require_tval(ctx, -1);
  13702. DUK_ASSERT(q != NULL);
  13703. DUK_ASSERT(q >= p);
  13704. /* nbytes
  13705. * <--------->
  13706. * [ ... | p | x | x | q ]
  13707. * => [ ... | q | p | x | x ]
  13708. */
  13709. nbytes = (duk_size_t) (((duk_uint8_t *) q) - ((duk_uint8_t *) p)); /* Note: 'q' is top-1 */
  13710. DUK_DDD(DUK_DDDPRINT("duk_insert: to_index=%ld, p=%p, q=%p, nbytes=%lu",
  13711. (long) to_index, (void *) p, (void *) q, (unsigned long) nbytes));
  13712. /* No net refcount changes. */
  13713. if (nbytes > 0) {
  13714. DUK_TVAL_SET_TVAL(&tv_tmp, q);
  13715. DUK_ASSERT(nbytes > 0);
  13716. DUK_MEMMOVE((void *) (p + 1), (void *) p, nbytes);
  13717. DUK_TVAL_SET_TVAL(p, &tv_tmp);
  13718. } else {
  13719. /* nop: insert top to top */
  13720. DUK_ASSERT(nbytes == 0);
  13721. DUK_ASSERT(p == q);
  13722. }
  13723. }
  13724. DUK_EXTERNAL void duk_replace(duk_context *ctx, duk_idx_t to_index) {
  13725. duk_hthread *thr = (duk_hthread *) ctx;
  13726. duk_tval *tv1;
  13727. duk_tval *tv2;
  13728. duk_tval tv_tmp;
  13729. DUK_ASSERT(ctx != NULL);
  13730. tv1 = duk_require_tval(ctx, -1);
  13731. DUK_ASSERT(tv1 != NULL);
  13732. tv2 = duk_require_tval(ctx, to_index);
  13733. DUK_ASSERT(tv2 != NULL);
  13734. /* For tv1 == tv2, both pointing to stack top, the end result
  13735. * is same as duk_pop(ctx).
  13736. */
  13737. DUK_TVAL_SET_TVAL(&tv_tmp, tv2);
  13738. DUK_TVAL_SET_TVAL(tv2, tv1);
  13739. DUK_TVAL_SET_UNDEFINED_UNUSED(tv1);
  13740. thr->valstack_top--;
  13741. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  13742. }
  13743. DUK_EXTERNAL void duk_copy(duk_context *ctx, duk_idx_t from_index, duk_idx_t to_index) {
  13744. duk_hthread *thr = (duk_hthread *) ctx;
  13745. duk_tval *tv1;
  13746. duk_tval *tv2;
  13747. duk_tval tv_tmp;
  13748. DUK_UNREF(thr); /* w/o refcounting */
  13749. DUK_ASSERT(ctx != NULL);
  13750. tv1 = duk_require_tval(ctx, from_index);
  13751. DUK_ASSERT(tv1 != NULL);
  13752. tv2 = duk_require_tval(ctx, to_index);
  13753. DUK_ASSERT(tv2 != NULL);
  13754. /* For tv1 == tv2, this is a no-op (no explicit check needed). */
  13755. DUK_TVAL_SET_TVAL(&tv_tmp, tv2);
  13756. DUK_TVAL_SET_TVAL(tv2, tv1);
  13757. DUK_TVAL_INCREF(thr, tv2); /* no side effects */
  13758. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  13759. }
  13760. DUK_EXTERNAL void duk_remove(duk_context *ctx, duk_idx_t index) {
  13761. duk_hthread *thr = (duk_hthread *) ctx;
  13762. duk_tval *p;
  13763. duk_tval *q;
  13764. #ifdef DUK_USE_REFERENCE_COUNTING
  13765. duk_tval tv_tmp;
  13766. #endif
  13767. duk_size_t nbytes;
  13768. DUK_ASSERT(ctx != NULL);
  13769. p = duk_require_tval(ctx, index);
  13770. DUK_ASSERT(p != NULL);
  13771. q = duk_require_tval(ctx, -1);
  13772. DUK_ASSERT(q != NULL);
  13773. DUK_ASSERT(q >= p);
  13774. /* nbytes zero size case
  13775. * <--------->
  13776. * [ ... | p | x | x | q ] [ ... | p==q ]
  13777. * => [ ... | x | x | q ] [ ... ]
  13778. */
  13779. #ifdef DUK_USE_REFERENCE_COUNTING
  13780. /* use a temp: decref only when valstack reachable values are correct */
  13781. DUK_TVAL_SET_TVAL(&tv_tmp, p);
  13782. #endif
  13783. nbytes = (duk_size_t) (((duk_uint8_t *) q) - ((duk_uint8_t *) p)); /* Note: 'q' is top-1 */
  13784. DUK_MEMMOVE(p, p + 1, nbytes); /* zero size not an issue: pointers are valid */
  13785. DUK_TVAL_SET_UNDEFINED_UNUSED(q);
  13786. thr->valstack_top--;
  13787. #ifdef DUK_USE_REFERENCE_COUNTING
  13788. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  13789. #endif
  13790. }
  13791. /*
  13792. * Stack slice primitives
  13793. */
  13794. DUK_EXTERNAL void duk_xcopymove_raw(duk_context *to_ctx, duk_context *from_ctx, duk_idx_t count, duk_bool_t is_copy) {
  13795. duk_hthread *to_thr = (duk_hthread *) to_ctx;
  13796. duk_hthread *from_thr = (duk_hthread *) from_ctx;
  13797. void *src;
  13798. duk_size_t nbytes;
  13799. duk_tval *p;
  13800. duk_tval *q;
  13801. /* XXX: several pointer comparison issues here */
  13802. DUK_ASSERT(to_ctx != NULL);
  13803. DUK_ASSERT(from_ctx != NULL);
  13804. if (to_ctx == from_ctx) {
  13805. DUK_ERROR(to_thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CONTEXT);
  13806. return;
  13807. }
  13808. if ((count < 0) ||
  13809. (count > (duk_idx_t) to_thr->valstack_max)) {
  13810. /* Maximum value check ensures 'nbytes' won't wrap below. */
  13811. DUK_ERROR(to_thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_COUNT);
  13812. return;
  13813. }
  13814. nbytes = sizeof(duk_tval) * count;
  13815. if (nbytes == 0) {
  13816. return;
  13817. }
  13818. DUK_ASSERT(to_thr->valstack_top <= to_thr->valstack_end);
  13819. if ((duk_size_t) ((duk_uint8_t *) to_thr->valstack_end - (duk_uint8_t *) to_thr->valstack_top) < nbytes) {
  13820. DUK_ERROR(to_thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  13821. }
  13822. src = (void *) ((duk_uint8_t *) from_thr->valstack_top - nbytes);
  13823. if (src < (void *) from_thr->valstack_bottom) {
  13824. DUK_ERROR(to_thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_COUNT);
  13825. }
  13826. /* copy values (no overlap even if to_ctx == from_ctx; that's not
  13827. * allowed now anyway)
  13828. */
  13829. DUK_ASSERT(nbytes > 0);
  13830. DUK_MEMCPY((void *) to_thr->valstack_top, src, nbytes);
  13831. p = to_thr->valstack_top;
  13832. to_thr->valstack_top = (duk_tval *) (((duk_uint8_t *) p) + nbytes);
  13833. if (is_copy) {
  13834. /* incref copies, keep originals */
  13835. q = to_thr->valstack_top;
  13836. while (p < q) {
  13837. DUK_TVAL_INCREF(to_thr, p); /* no side effects */
  13838. p++;
  13839. }
  13840. } else {
  13841. /* no net refcount change */
  13842. p = from_thr->valstack_top;
  13843. q = (duk_tval *) (((duk_uint8_t *) p) - nbytes);
  13844. from_thr->valstack_top = q;
  13845. /* elements above stack top are kept UNUSED */
  13846. while (p > q) {
  13847. p--;
  13848. DUK_TVAL_SET_UNDEFINED_UNUSED(p);
  13849. /* XXX: fast primitive to set a bunch of values to UNDEFINED_UNUSED */
  13850. }
  13851. }
  13852. }
  13853. /*
  13854. * Get/require
  13855. */
  13856. DUK_EXTERNAL void duk_require_undefined(duk_context *ctx, duk_idx_t index) {
  13857. duk_hthread *thr = (duk_hthread *) ctx;
  13858. duk_tval *tv;
  13859. DUK_ASSERT(ctx != NULL);
  13860. tv = duk_get_tval(ctx, index);
  13861. if (tv && DUK_TVAL_IS_UNDEFINED(tv)) {
  13862. /* Note: accept both 'actual' and 'unused' undefined */
  13863. return;
  13864. }
  13865. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_UNDEFINED);
  13866. }
  13867. DUK_EXTERNAL void duk_require_null(duk_context *ctx, duk_idx_t index) {
  13868. duk_hthread *thr = (duk_hthread *) ctx;
  13869. duk_tval *tv;
  13870. DUK_ASSERT(ctx != NULL);
  13871. tv = duk_get_tval(ctx, index);
  13872. if (tv && DUK_TVAL_IS_NULL(tv)) {
  13873. return;
  13874. }
  13875. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_NULL);
  13876. return; /* not reachable */
  13877. }
  13878. DUK_EXTERNAL duk_bool_t duk_get_boolean(duk_context *ctx, duk_idx_t index) {
  13879. duk_bool_t ret = 0; /* default: false */
  13880. duk_tval *tv;
  13881. DUK_ASSERT(ctx != NULL);
  13882. tv = duk_get_tval(ctx, index);
  13883. if (tv && DUK_TVAL_IS_BOOLEAN(tv)) {
  13884. ret = DUK_TVAL_GET_BOOLEAN(tv);
  13885. }
  13886. DUK_ASSERT(ret == 0 || ret == 1);
  13887. return ret;
  13888. }
  13889. DUK_EXTERNAL duk_bool_t duk_require_boolean(duk_context *ctx, duk_idx_t index) {
  13890. duk_hthread *thr = (duk_hthread *) ctx;
  13891. duk_tval *tv;
  13892. DUK_ASSERT(ctx != NULL);
  13893. tv = duk_get_tval(ctx, index);
  13894. if (tv && DUK_TVAL_IS_BOOLEAN(tv)) {
  13895. duk_bool_t ret = DUK_TVAL_GET_BOOLEAN(tv);
  13896. DUK_ASSERT(ret == 0 || ret == 1);
  13897. return ret;
  13898. }
  13899. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_BOOLEAN);
  13900. return 0; /* not reachable */
  13901. }
  13902. DUK_EXTERNAL duk_double_t duk_get_number(duk_context *ctx, duk_idx_t index) {
  13903. duk_double_union ret;
  13904. duk_tval *tv;
  13905. DUK_ASSERT(ctx != NULL);
  13906. ret.d = DUK_DOUBLE_NAN; /* default: NaN */
  13907. tv = duk_get_tval(ctx, index);
  13908. if (tv && DUK_TVAL_IS_NUMBER(tv)) {
  13909. ret.d = DUK_TVAL_GET_NUMBER(tv);
  13910. }
  13911. /*
  13912. * Number should already be in NaN-normalized form, but let's
  13913. * normalize anyway.
  13914. */
  13915. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&ret);
  13916. return ret.d;
  13917. }
  13918. DUK_EXTERNAL duk_double_t duk_require_number(duk_context *ctx, duk_idx_t index) {
  13919. duk_hthread *thr = (duk_hthread *) ctx;
  13920. duk_tval *tv;
  13921. DUK_ASSERT(ctx != NULL);
  13922. tv = duk_get_tval(ctx, index);
  13923. if (tv && DUK_TVAL_IS_NUMBER(tv)) {
  13924. duk_double_union ret;
  13925. ret.d = DUK_TVAL_GET_NUMBER(tv);
  13926. /*
  13927. * Number should already be in NaN-normalized form,
  13928. * but let's normalize anyway.
  13929. */
  13930. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&ret);
  13931. return ret.d;
  13932. }
  13933. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_NUMBER);
  13934. return DUK_DOUBLE_NAN; /* not reachable */
  13935. }
  13936. DUK_EXTERNAL duk_int_t duk_get_int(duk_context *ctx, duk_idx_t index) {
  13937. /* Custom coercion for API */
  13938. return (duk_int_t) duk__api_coerce_d2i(ctx, index, 0 /*require*/);
  13939. }
  13940. DUK_EXTERNAL duk_uint_t duk_get_uint(duk_context *ctx, duk_idx_t index) {
  13941. /* Custom coercion for API */
  13942. return (duk_uint_t) duk__api_coerce_d2ui(ctx, index, 0 /*require*/);
  13943. }
  13944. DUK_EXTERNAL duk_int_t duk_require_int(duk_context *ctx, duk_idx_t index) {
  13945. /* Custom coercion for API */
  13946. return (duk_int_t) duk__api_coerce_d2i(ctx, index, 1 /*require*/);
  13947. }
  13948. DUK_EXTERNAL duk_uint_t duk_require_uint(duk_context *ctx, duk_idx_t index) {
  13949. /* Custom coercion for API */
  13950. return (duk_uint_t) duk__api_coerce_d2ui(ctx, index, 1 /*require*/);
  13951. }
  13952. DUK_EXTERNAL const char *duk_get_lstring(duk_context *ctx, duk_idx_t index, duk_size_t *out_len) {
  13953. const char *ret;
  13954. duk_tval *tv;
  13955. DUK_ASSERT(ctx != NULL);
  13956. /* default: NULL, length 0 */
  13957. ret = NULL;
  13958. if (out_len) {
  13959. *out_len = 0;
  13960. }
  13961. tv = duk_get_tval(ctx, index);
  13962. if (tv && DUK_TVAL_IS_STRING(tv)) {
  13963. /* Here we rely on duk_hstring instances always being zero
  13964. * terminated even if the actual string is not.
  13965. */
  13966. duk_hstring *h = DUK_TVAL_GET_STRING(tv);
  13967. DUK_ASSERT(h != NULL);
  13968. ret = (const char *) DUK_HSTRING_GET_DATA(h);
  13969. if (out_len) {
  13970. *out_len = DUK_HSTRING_GET_BYTELEN(h);
  13971. }
  13972. }
  13973. return ret;
  13974. }
  13975. DUK_EXTERNAL const char *duk_require_lstring(duk_context *ctx, duk_idx_t index, duk_size_t *out_len) {
  13976. duk_hthread *thr = (duk_hthread *) ctx;
  13977. const char *ret;
  13978. DUK_ASSERT(ctx != NULL);
  13979. /* Note: this check relies on the fact that even a zero-size string
  13980. * has a non-NULL pointer.
  13981. */
  13982. ret = duk_get_lstring(ctx, index, out_len);
  13983. if (ret) {
  13984. return ret;
  13985. }
  13986. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_STRING);
  13987. return NULL; /* not reachable */
  13988. }
  13989. DUK_EXTERNAL const char *duk_get_string(duk_context *ctx, duk_idx_t index) {
  13990. DUK_ASSERT(ctx != NULL);
  13991. return duk_get_lstring(ctx, index, NULL);
  13992. }
  13993. DUK_EXTERNAL const char *duk_require_string(duk_context *ctx, duk_idx_t index) {
  13994. DUK_ASSERT(ctx != NULL);
  13995. return duk_require_lstring(ctx, index, NULL);
  13996. }
  13997. DUK_EXTERNAL void *duk_get_pointer(duk_context *ctx, duk_idx_t index) {
  13998. duk_tval *tv;
  13999. DUK_ASSERT(ctx != NULL);
  14000. tv = duk_get_tval(ctx, index);
  14001. if (tv && DUK_TVAL_IS_POINTER(tv)) {
  14002. void *p = DUK_TVAL_GET_POINTER(tv); /* may be NULL */
  14003. return (void *) p;
  14004. }
  14005. return NULL;
  14006. }
  14007. DUK_EXTERNAL void *duk_require_pointer(duk_context *ctx, duk_idx_t index) {
  14008. duk_hthread *thr = (duk_hthread *) ctx;
  14009. duk_tval *tv;
  14010. DUK_ASSERT(ctx != NULL);
  14011. /* Note: here we must be wary of the fact that a pointer may be
  14012. * valid and be a NULL.
  14013. */
  14014. tv = duk_get_tval(ctx, index);
  14015. if (tv && DUK_TVAL_IS_POINTER(tv)) {
  14016. void *p = DUK_TVAL_GET_POINTER(tv); /* may be NULL */
  14017. return (void *) p;
  14018. }
  14019. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_POINTER);
  14020. return NULL; /* not reachable */
  14021. }
  14022. #if 0 /*unused*/
  14023. DUK_INTERNAL void *duk_get_voidptr(duk_context *ctx, duk_idx_t index) {
  14024. duk_tval *tv;
  14025. DUK_ASSERT(ctx != NULL);
  14026. tv = duk_get_tval(ctx, index);
  14027. if (tv && DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  14028. duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
  14029. DUK_ASSERT(h != NULL);
  14030. return (void *) h;
  14031. }
  14032. return NULL;
  14033. }
  14034. #endif
  14035. DUK_EXTERNAL void *duk_get_buffer(duk_context *ctx, duk_idx_t index, duk_size_t *out_size) {
  14036. duk_hthread *thr = (duk_hthread *) ctx;
  14037. duk_tval *tv;
  14038. DUK_ASSERT(ctx != NULL);
  14039. DUK_UNREF(thr);
  14040. if (out_size != NULL) {
  14041. *out_size = 0;
  14042. }
  14043. tv = duk_get_tval(ctx, index);
  14044. if (tv && DUK_TVAL_IS_BUFFER(tv)) {
  14045. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  14046. DUK_ASSERT(h != NULL);
  14047. if (out_size) {
  14048. *out_size = DUK_HBUFFER_GET_SIZE(h);
  14049. }
  14050. return (void *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h); /* may be NULL (but only if size is 0) */
  14051. }
  14052. return NULL;
  14053. }
  14054. DUK_EXTERNAL void *duk_require_buffer(duk_context *ctx, duk_idx_t index, duk_size_t *out_size) {
  14055. duk_hthread *thr = (duk_hthread *) ctx;
  14056. duk_tval *tv;
  14057. DUK_ASSERT(ctx != NULL);
  14058. if (out_size != NULL) {
  14059. *out_size = 0;
  14060. }
  14061. /* Note: here we must be wary of the fact that a data pointer may
  14062. * be a NULL for a zero-size buffer.
  14063. */
  14064. tv = duk_get_tval(ctx, index);
  14065. if (tv && DUK_TVAL_IS_BUFFER(tv)) {
  14066. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  14067. DUK_ASSERT(h != NULL);
  14068. if (out_size) {
  14069. *out_size = DUK_HBUFFER_GET_SIZE(h);
  14070. }
  14071. return (void *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h); /* may be NULL (but only if size is 0) */
  14072. }
  14073. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_BUFFER);
  14074. return NULL; /* not reachable */
  14075. }
  14076. /* Raw helper for getting a value from the stack, checking its tag, and possible its object class.
  14077. * The tag cannot be a number because numbers don't have an internal tag in the packed representation.
  14078. */
  14079. DUK_INTERNAL duk_heaphdr *duk_get_tagged_heaphdr_raw(duk_context *ctx, duk_idx_t index, duk_uint_t flags_and_tag) {
  14080. duk_hthread *thr = (duk_hthread *) ctx;
  14081. duk_tval *tv;
  14082. duk_small_uint_t tag = flags_and_tag & 0xffffU; /* tags can be up to 16 bits */
  14083. DUK_ASSERT(ctx != NULL);
  14084. tv = duk_get_tval(ctx, index);
  14085. if (tv && (DUK_TVAL_GET_TAG(tv) == tag)) {
  14086. duk_heaphdr *ret;
  14087. /* Note: tag comparison in general doesn't work for numbers,
  14088. * but it does work for everything else (heap objects here).
  14089. */
  14090. ret = DUK_TVAL_GET_HEAPHDR(tv);
  14091. DUK_ASSERT(ret != NULL); /* tagged null pointers should never occur */
  14092. /* If class check has been requested, tag must also be DUK_TAG_OBJECT.
  14093. * This allows us to just check the class check flag without checking
  14094. * the tag also.
  14095. */
  14096. DUK_ASSERT((flags_and_tag & DUK_GETTAGGED_FLAG_CHECK_CLASS) == 0 ||
  14097. tag == DUK_TAG_OBJECT);
  14098. if ((flags_and_tag & DUK_GETTAGGED_FLAG_CHECK_CLASS) == 0 || /* no class check */
  14099. (duk_int_t) DUK_HOBJECT_GET_CLASS_NUMBER((duk_hobject *) ret) == /* or class check matches */
  14100. (duk_int_t) ((flags_and_tag >> DUK_GETTAGGED_CLASS_SHIFT) & 0xff)) {
  14101. return ret;
  14102. }
  14103. }
  14104. if (flags_and_tag & DUK_GETTAGGED_FLAG_ALLOW_NULL) {
  14105. return (duk_heaphdr *) NULL;
  14106. }
  14107. /* Formatting the tag number here is not very useful: the tag value
  14108. * is Duktape internal (not the same as DUK_TYPE_xxx) and even depends
  14109. * on the duk_tval layout. If anything, add a human readable type here.
  14110. */
  14111. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_UNEXPECTED_TYPE);
  14112. return NULL; /* not reachable */
  14113. }
  14114. DUK_INTERNAL duk_hstring *duk_get_hstring(duk_context *ctx, duk_idx_t index) {
  14115. return (duk_hstring *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_STRING | DUK_GETTAGGED_FLAG_ALLOW_NULL);
  14116. }
  14117. DUK_INTERNAL duk_hstring *duk_require_hstring(duk_context *ctx, duk_idx_t index) {
  14118. return (duk_hstring *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_STRING);
  14119. }
  14120. DUK_INTERNAL duk_hobject *duk_get_hobject(duk_context *ctx, duk_idx_t index) {
  14121. return (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT | DUK_GETTAGGED_FLAG_ALLOW_NULL);
  14122. }
  14123. DUK_INTERNAL duk_hobject *duk_require_hobject(duk_context *ctx, duk_idx_t index) {
  14124. return (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT);
  14125. }
  14126. DUK_INTERNAL duk_hbuffer *duk_get_hbuffer(duk_context *ctx, duk_idx_t index) {
  14127. return (duk_hbuffer *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_BUFFER | DUK_GETTAGGED_FLAG_ALLOW_NULL);
  14128. }
  14129. DUK_INTERNAL duk_hbuffer *duk_require_hbuffer(duk_context *ctx, duk_idx_t index) {
  14130. return (duk_hbuffer *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_BUFFER);
  14131. }
  14132. DUK_INTERNAL duk_hthread *duk_get_hthread(duk_context *ctx, duk_idx_t index) {
  14133. duk_hobject *h = (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT | DUK_GETTAGGED_FLAG_ALLOW_NULL);
  14134. if (h != NULL && !DUK_HOBJECT_IS_THREAD(h)) {
  14135. h = NULL;
  14136. }
  14137. return (duk_hthread *) h;
  14138. }
  14139. DUK_INTERNAL duk_hthread *duk_require_hthread(duk_context *ctx, duk_idx_t index) {
  14140. duk_hthread *thr = (duk_hthread *) ctx;
  14141. duk_hobject *h = (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT);
  14142. DUK_ASSERT(h != NULL);
  14143. if (!DUK_HOBJECT_IS_THREAD(h)) {
  14144. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_THREAD);
  14145. }
  14146. return (duk_hthread *) h;
  14147. }
  14148. DUK_INTERNAL duk_hcompiledfunction *duk_get_hcompiledfunction(duk_context *ctx, duk_idx_t index) {
  14149. duk_hobject *h = (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT | DUK_GETTAGGED_FLAG_ALLOW_NULL);
  14150. if (h != NULL && !DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
  14151. h = NULL;
  14152. }
  14153. return (duk_hcompiledfunction *) h;
  14154. }
  14155. #if 0 /*unused*/
  14156. DUK_INTERNAL duk_hcompiledfunction *duk_require_hcompiledfunction(duk_context *ctx, duk_idx_t index) {
  14157. duk_hthread *thr = (duk_hthread *) ctx;
  14158. duk_hobject *h = (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT);
  14159. DUK_ASSERT(h != NULL);
  14160. if (!DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
  14161. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_COMPILEDFUNCTION);
  14162. }
  14163. return (duk_hcompiledfunction *) h;
  14164. }
  14165. #endif
  14166. DUK_INTERNAL duk_hnativefunction *duk_get_hnativefunction(duk_context *ctx, duk_idx_t index) {
  14167. duk_hobject *h = (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT | DUK_GETTAGGED_FLAG_ALLOW_NULL);
  14168. if (h != NULL && !DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  14169. h = NULL;
  14170. }
  14171. return (duk_hnativefunction *) h;
  14172. }
  14173. DUK_INTERNAL duk_hnativefunction *duk_require_hnativefunction(duk_context *ctx, duk_idx_t index) {
  14174. duk_hthread *thr = (duk_hthread *) ctx;
  14175. duk_hobject *h = (duk_hobject *) duk_get_tagged_heaphdr_raw(ctx, index, DUK_TAG_OBJECT);
  14176. DUK_ASSERT(h != NULL);
  14177. if (!DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  14178. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_NATIVEFUNCTION);
  14179. }
  14180. return (duk_hnativefunction *) h;
  14181. }
  14182. DUK_EXTERNAL duk_c_function duk_get_c_function(duk_context *ctx, duk_idx_t index) {
  14183. duk_tval *tv;
  14184. duk_hobject *h;
  14185. duk_hnativefunction *f;
  14186. DUK_ASSERT(ctx != NULL);
  14187. tv = duk_get_tval(ctx, index);
  14188. if (!tv) {
  14189. return NULL;
  14190. }
  14191. if (!DUK_TVAL_IS_OBJECT(tv)) {
  14192. return NULL;
  14193. }
  14194. h = DUK_TVAL_GET_OBJECT(tv);
  14195. DUK_ASSERT(h != NULL);
  14196. if (!DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  14197. return NULL;
  14198. }
  14199. DUK_ASSERT(DUK_HOBJECT_HAS_NATIVEFUNCTION(h));
  14200. f = (duk_hnativefunction *) h;
  14201. return f->func;
  14202. }
  14203. DUK_EXTERNAL duk_c_function duk_require_c_function(duk_context *ctx, duk_idx_t index) {
  14204. duk_hthread *thr = (duk_hthread *) ctx;
  14205. duk_c_function ret;
  14206. DUK_ASSERT(ctx != NULL);
  14207. ret = duk_get_c_function(ctx, index);
  14208. if (!ret) {
  14209. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_C_FUNCTION);
  14210. }
  14211. return ret;
  14212. }
  14213. DUK_EXTERNAL duk_context *duk_get_context(duk_context *ctx, duk_idx_t index) {
  14214. return (duk_context *) duk_get_hthread(ctx, index);
  14215. }
  14216. DUK_EXTERNAL duk_context *duk_require_context(duk_context *ctx, duk_idx_t index) {
  14217. return (duk_context *) duk_require_hthread(ctx, index);
  14218. }
  14219. DUK_EXTERNAL void *duk_get_heapptr(duk_context *ctx, duk_idx_t index) {
  14220. duk_tval *tv;
  14221. void *ret;
  14222. DUK_ASSERT(ctx != NULL);
  14223. tv = duk_get_tval(ctx, index);
  14224. if (tv && DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  14225. ret = (void *) DUK_TVAL_GET_HEAPHDR(tv);
  14226. DUK_ASSERT(ret != NULL);
  14227. return ret;
  14228. }
  14229. return (void *) NULL;
  14230. }
  14231. DUK_EXTERNAL void *duk_require_heapptr(duk_context *ctx, duk_idx_t index) {
  14232. duk_hthread *thr = (duk_hthread *) ctx;
  14233. duk_tval *tv;
  14234. void *ret;
  14235. DUK_ASSERT(ctx != NULL);
  14236. tv = duk_require_tval(ctx, index);
  14237. DUK_ASSERT(tv != NULL);
  14238. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  14239. ret = (void *) DUK_TVAL_GET_HEAPHDR(tv);
  14240. DUK_ASSERT(ret != NULL);
  14241. return ret;
  14242. }
  14243. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_UNEXPECTED_TYPE);
  14244. return (void *) NULL; /* not reachable */
  14245. }
  14246. #if 0
  14247. /* This would be pointless: we'd return NULL for both lightfuncs and
  14248. * unexpected types.
  14249. */
  14250. duk_hobject *duk_get_hobject_or_lfunc(duk_context *ctx, duk_idx_t index) {
  14251. }
  14252. #endif
  14253. /* Useful for internal call sites where we either expect an object (function)
  14254. * or a lightfunc. Accepts an object (returned as is) or a lightfunc (coerced
  14255. * to an object). Return value is NULL if value is neither an object nor a
  14256. * lightfunc.
  14257. */
  14258. duk_hobject *duk_get_hobject_or_lfunc_coerce(duk_context *ctx, duk_idx_t index) {
  14259. duk_tval *tv;
  14260. DUK_ASSERT(ctx != NULL);
  14261. tv = duk_require_tval(ctx, index);
  14262. DUK_ASSERT(tv != NULL);
  14263. if (DUK_TVAL_IS_OBJECT(tv)) {
  14264. return DUK_TVAL_GET_OBJECT(tv);
  14265. } else if (DUK_TVAL_IS_LIGHTFUNC(tv)) {
  14266. duk_to_object(ctx, index);
  14267. return duk_require_hobject(ctx, index);
  14268. }
  14269. return NULL;
  14270. }
  14271. /* Useful for internal call sites where we either expect an object (function)
  14272. * or a lightfunc. Returns NULL for a lightfunc.
  14273. */
  14274. DUK_INTERNAL duk_hobject *duk_require_hobject_or_lfunc(duk_context *ctx, duk_idx_t index) {
  14275. duk_hthread *thr = (duk_hthread *) ctx;
  14276. duk_tval *tv;
  14277. DUK_ASSERT(ctx != NULL);
  14278. tv = duk_require_tval(ctx, index);
  14279. DUK_ASSERT(tv != NULL);
  14280. if (DUK_TVAL_IS_OBJECT(tv)) {
  14281. return DUK_TVAL_GET_OBJECT(tv);
  14282. } else if (DUK_TVAL_IS_LIGHTFUNC(tv)) {
  14283. return NULL;
  14284. }
  14285. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_UNEXPECTED_TYPE);
  14286. return NULL; /* not reachable */
  14287. }
  14288. /* Useful for internal call sites where we either expect an object (function)
  14289. * or a lightfunc. Accepts an object (returned as is) or a lightfunc (coerced
  14290. * to an object). Return value is never NULL.
  14291. */
  14292. DUK_INTERNAL duk_hobject *duk_require_hobject_or_lfunc_coerce(duk_context *ctx, duk_idx_t index) {
  14293. duk_hthread *thr = (duk_hthread *) ctx;
  14294. duk_tval *tv;
  14295. DUK_ASSERT(ctx != NULL);
  14296. tv = duk_require_tval(ctx, index);
  14297. if (DUK_TVAL_IS_OBJECT(tv)) {
  14298. return DUK_TVAL_GET_OBJECT(tv);
  14299. } else if (DUK_TVAL_IS_LIGHTFUNC(tv)) {
  14300. duk_to_object(ctx, index);
  14301. return duk_require_hobject(ctx, index);
  14302. }
  14303. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_UNEXPECTED_TYPE);
  14304. return NULL; /* not reachable */
  14305. }
  14306. DUK_EXTERNAL duk_size_t duk_get_length(duk_context *ctx, duk_idx_t index) {
  14307. duk_tval *tv;
  14308. DUK_ASSERT(ctx != NULL);
  14309. tv = duk_get_tval(ctx, index);
  14310. if (!tv) {
  14311. return 0;
  14312. }
  14313. switch (DUK_TVAL_GET_TAG(tv)) {
  14314. case DUK_TAG_UNDEFINED:
  14315. case DUK_TAG_NULL:
  14316. case DUK_TAG_BOOLEAN:
  14317. case DUK_TAG_POINTER:
  14318. return 0;
  14319. case DUK_TAG_STRING: {
  14320. duk_hstring *h = DUK_TVAL_GET_STRING(tv);
  14321. DUK_ASSERT(h != NULL);
  14322. return (duk_size_t) DUK_HSTRING_GET_CHARLEN(h);
  14323. }
  14324. case DUK_TAG_OBJECT: {
  14325. duk_hobject *h = DUK_TVAL_GET_OBJECT(tv);
  14326. DUK_ASSERT(h != NULL);
  14327. return (duk_size_t) duk_hobject_get_length((duk_hthread *) ctx, h);
  14328. }
  14329. case DUK_TAG_BUFFER: {
  14330. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  14331. DUK_ASSERT(h != NULL);
  14332. return (duk_size_t) DUK_HBUFFER_GET_SIZE(h);
  14333. }
  14334. case DUK_TAG_LIGHTFUNC: {
  14335. duk_small_uint_t lf_flags;
  14336. lf_flags = DUK_TVAL_GET_LIGHTFUNC_FLAGS(tv);
  14337. return (duk_size_t) DUK_LFUNC_FLAGS_GET_LENGTH(lf_flags);
  14338. }
  14339. #if defined(DUK_USE_FASTINT)
  14340. case DUK_TAG_FASTINT:
  14341. #endif
  14342. default:
  14343. /* number */
  14344. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  14345. return 0;
  14346. }
  14347. DUK_UNREACHABLE();
  14348. }
  14349. DUK_INTERNAL void duk_set_length(duk_context *ctx, duk_idx_t index, duk_size_t length) {
  14350. duk_hthread *thr = (duk_hthread *) ctx;
  14351. duk_hobject *h;
  14352. DUK_ASSERT(ctx != NULL);
  14353. h = duk_get_hobject(ctx, index);
  14354. if (!h) {
  14355. return;
  14356. }
  14357. duk_hobject_set_length(thr, h, (duk_uint32_t) length); /* XXX: typing */
  14358. }
  14359. /*
  14360. * Conversions and coercions
  14361. *
  14362. * The conversion/coercions are in-place operations on the value stack.
  14363. * Some operations are implemented here directly, while others call a
  14364. * helper in duk_js_ops.c after validating arguments.
  14365. */
  14366. /* E5 Section 8.12.8 */
  14367. DUK_LOCAL duk_bool_t duk__defaultvalue_coerce_attempt(duk_context *ctx, duk_idx_t index, duk_small_int_t func_stridx) {
  14368. if (duk_get_prop_stridx(ctx, index, func_stridx)) {
  14369. /* [ ... func ] */
  14370. if (duk_is_callable(ctx, -1)) {
  14371. duk_dup(ctx, index); /* -> [ ... func this ] */
  14372. duk_call_method(ctx, 0); /* -> [ ... retval ] */
  14373. if (duk_is_primitive(ctx, -1)) {
  14374. duk_replace(ctx, index);
  14375. return 1;
  14376. }
  14377. /* [ ... retval ]; popped below */
  14378. }
  14379. }
  14380. duk_pop(ctx); /* [ ... func/retval ] -> [ ... ] */
  14381. return 0;
  14382. }
  14383. DUK_EXTERNAL void duk_to_defaultvalue(duk_context *ctx, duk_idx_t index, duk_int_t hint) {
  14384. duk_hthread *thr = (duk_hthread *) ctx;
  14385. duk_hobject *obj;
  14386. /* inline initializer for coercers[] is not allowed by old compilers like BCC */
  14387. duk_small_int_t coercers[2];
  14388. DUK_ASSERT(ctx != NULL);
  14389. DUK_ASSERT(thr != NULL);
  14390. coercers[0] = DUK_STRIDX_VALUE_OF;
  14391. coercers[1] = DUK_STRIDX_TO_STRING;
  14392. index = duk_require_normalize_index(ctx, index);
  14393. obj = duk_require_hobject_or_lfunc(ctx, index);
  14394. if (hint == DUK_HINT_NONE) {
  14395. if (obj != NULL && DUK_HOBJECT_GET_CLASS_NUMBER(obj) == DUK_HOBJECT_CLASS_DATE) {
  14396. hint = DUK_HINT_STRING;
  14397. } else {
  14398. hint = DUK_HINT_NUMBER;
  14399. }
  14400. }
  14401. if (hint == DUK_HINT_STRING) {
  14402. coercers[0] = DUK_STRIDX_TO_STRING;
  14403. coercers[1] = DUK_STRIDX_VALUE_OF;
  14404. }
  14405. if (duk__defaultvalue_coerce_attempt(ctx, index, coercers[0])) {
  14406. return;
  14407. }
  14408. if (duk__defaultvalue_coerce_attempt(ctx, index, coercers[1])) {
  14409. return;
  14410. }
  14411. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_DEFAULTVALUE_COERCE_FAILED);
  14412. }
  14413. DUK_EXTERNAL void duk_to_undefined(duk_context *ctx, duk_idx_t index) {
  14414. duk_hthread *thr = (duk_hthread *) ctx;
  14415. duk_tval *tv;
  14416. duk_tval tv_tmp;
  14417. DUK_ASSERT(ctx != NULL);
  14418. DUK_UNREF(thr);
  14419. tv = duk_require_tval(ctx, index);
  14420. DUK_ASSERT(tv != NULL);
  14421. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14422. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv); /* no need to incref */
  14423. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14424. }
  14425. DUK_EXTERNAL void duk_to_null(duk_context *ctx, duk_idx_t index) {
  14426. duk_hthread *thr = (duk_hthread *) ctx;
  14427. duk_tval *tv;
  14428. duk_tval tv_tmp;
  14429. DUK_ASSERT(ctx != NULL);
  14430. DUK_UNREF(thr);
  14431. tv = duk_require_tval(ctx, index);
  14432. DUK_ASSERT(tv != NULL);
  14433. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14434. DUK_TVAL_SET_NULL(tv); /* no need to incref */
  14435. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14436. }
  14437. /* E5 Section 9.1 */
  14438. DUK_EXTERNAL void duk_to_primitive(duk_context *ctx, duk_idx_t index, duk_int_t hint) {
  14439. DUK_ASSERT(ctx != NULL);
  14440. DUK_ASSERT(hint == DUK_HINT_NONE || hint == DUK_HINT_NUMBER || hint == DUK_HINT_STRING);
  14441. index = duk_require_normalize_index(ctx, index);
  14442. if (!duk_check_type_mask(ctx, index, DUK_TYPE_MASK_OBJECT |
  14443. DUK_TYPE_MASK_LIGHTFUNC)) {
  14444. /* everything except object stay as is */
  14445. return;
  14446. }
  14447. duk_to_defaultvalue(ctx, index, hint);
  14448. }
  14449. /* E5 Section 9.2 */
  14450. DUK_EXTERNAL duk_bool_t duk_to_boolean(duk_context *ctx, duk_idx_t index) {
  14451. duk_hthread *thr = (duk_hthread *) ctx;
  14452. duk_tval *tv;
  14453. duk_tval tv_tmp;
  14454. duk_bool_t val;
  14455. DUK_ASSERT(ctx != NULL);
  14456. DUK_UNREF(thr);
  14457. index = duk_require_normalize_index(ctx, index);
  14458. tv = duk_require_tval(ctx, index);
  14459. DUK_ASSERT(tv != NULL);
  14460. val = duk_js_toboolean(tv);
  14461. DUK_ASSERT(val == 0 || val == 1);
  14462. /* Note: no need to re-lookup tv, conversion is side effect free */
  14463. DUK_ASSERT(tv != NULL);
  14464. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14465. DUK_TVAL_SET_BOOLEAN(tv, val); /* no need to incref */
  14466. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14467. return val;
  14468. }
  14469. DUK_EXTERNAL duk_double_t duk_to_number(duk_context *ctx, duk_idx_t index) {
  14470. duk_hthread *thr = (duk_hthread *) ctx;
  14471. duk_tval *tv;
  14472. duk_tval tv_tmp;
  14473. duk_double_t d;
  14474. DUK_ASSERT(ctx != NULL);
  14475. tv = duk_require_tval(ctx, index);
  14476. DUK_ASSERT(tv != NULL);
  14477. /* XXX: fastint? */
  14478. d = duk_js_tonumber(thr, tv);
  14479. /* Note: need to re-lookup because ToNumber() may have side effects */
  14480. tv = duk_require_tval(ctx, index);
  14481. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14482. DUK_TVAL_SET_NUMBER(tv, d); /* no need to incref */
  14483. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14484. return d;
  14485. }
  14486. /* XXX: combine all the integer conversions: they share everything
  14487. * but the helper function for coercion.
  14488. */
  14489. typedef duk_double_t (*duk__toint_coercer)(duk_hthread *thr, duk_tval *tv);
  14490. DUK_LOCAL duk_double_t duk__to_int_uint_helper(duk_context *ctx, duk_idx_t index, duk__toint_coercer coerce_func) {
  14491. duk_hthread *thr = (duk_hthread *) ctx;
  14492. duk_tval *tv;
  14493. duk_tval tv_tmp;
  14494. duk_double_t d;
  14495. DUK_ASSERT(ctx != NULL);
  14496. tv = duk_require_tval(ctx, index);
  14497. DUK_ASSERT(tv != NULL);
  14498. d = coerce_func(thr, tv);
  14499. /* XXX: fastint? */
  14500. /* Relookup in case coerce_func() has side effects, e.g. ends up coercing an object */
  14501. tv = duk_require_tval(ctx, index);
  14502. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14503. DUK_TVAL_SET_NUMBER(tv, d); /* no need to incref */
  14504. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14505. return d;
  14506. }
  14507. DUK_EXTERNAL duk_int_t duk_to_int(duk_context *ctx, duk_idx_t index) {
  14508. /* Value coercion (in stack): ToInteger(), E5 Section 9.4
  14509. * API return value coercion: custom
  14510. */
  14511. (void) duk__to_int_uint_helper(ctx, index, duk_js_tointeger);
  14512. return (duk_int_t) duk__api_coerce_d2i(ctx, index, 0 /*require*/);
  14513. }
  14514. DUK_EXTERNAL duk_uint_t duk_to_uint(duk_context *ctx, duk_idx_t index) {
  14515. /* Value coercion (in stack): ToInteger(), E5 Section 9.4
  14516. * API return value coercion: custom
  14517. */
  14518. (void) duk__to_int_uint_helper(ctx, index, duk_js_tointeger);
  14519. return (duk_uint_t) duk__api_coerce_d2ui(ctx, index, 0 /*require*/);
  14520. }
  14521. DUK_EXTERNAL duk_int32_t duk_to_int32(duk_context *ctx, duk_idx_t index) {
  14522. duk_hthread *thr = (duk_hthread *) ctx;
  14523. duk_tval *tv;
  14524. duk_tval tv_tmp;
  14525. duk_int32_t ret;
  14526. DUK_ASSERT(ctx != NULL);
  14527. tv = duk_require_tval(ctx, index);
  14528. DUK_ASSERT(tv != NULL);
  14529. ret = duk_js_toint32(thr, tv);
  14530. /* Relookup in case coerce_func() has side effects, e.g. ends up coercing an object */
  14531. tv = duk_require_tval(ctx, index);
  14532. #if defined(DUK_USE_FASTINT)
  14533. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14534. DUK_TVAL_SET_FASTINT_I32(tv, ret); /* no need to incref */
  14535. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14536. return ret;
  14537. #else
  14538. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14539. DUK_TVAL_SET_NUMBER(tv, (duk_double_t) ret); /* no need to incref */
  14540. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14541. return ret;
  14542. #endif
  14543. }
  14544. DUK_EXTERNAL duk_uint32_t duk_to_uint32(duk_context *ctx, duk_idx_t index) {
  14545. duk_hthread *thr = (duk_hthread *) ctx;
  14546. duk_tval *tv;
  14547. duk_tval tv_tmp;
  14548. duk_uint32_t ret;
  14549. DUK_ASSERT(ctx != NULL);
  14550. tv = duk_require_tval(ctx, index);
  14551. DUK_ASSERT(tv != NULL);
  14552. ret = duk_js_touint32(thr, tv);
  14553. /* Relookup in case coerce_func() has side effects, e.g. ends up coercing an object */
  14554. tv = duk_require_tval(ctx, index);
  14555. #if defined(DUK_USE_FASTINT)
  14556. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14557. DUK_TVAL_SET_FASTINT_U32(tv, ret); /* no need to incref */
  14558. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14559. return ret;
  14560. #else
  14561. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14562. DUK_TVAL_SET_NUMBER(tv, (duk_double_t) ret); /* no need to incref */
  14563. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14564. #endif
  14565. return ret;
  14566. }
  14567. DUK_EXTERNAL duk_uint16_t duk_to_uint16(duk_context *ctx, duk_idx_t index) {
  14568. duk_hthread *thr = (duk_hthread *) ctx;
  14569. duk_tval *tv;
  14570. duk_tval tv_tmp;
  14571. duk_uint16_t ret;
  14572. DUK_ASSERT(ctx != NULL);
  14573. tv = duk_require_tval(ctx, index);
  14574. DUK_ASSERT(tv != NULL);
  14575. ret = duk_js_touint16(thr, tv);
  14576. /* Relookup in case coerce_func() has side effects, e.g. ends up coercing an object */
  14577. tv = duk_require_tval(ctx, index);
  14578. #if defined(DUK_USE_FASTINT)
  14579. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14580. DUK_TVAL_SET_FASTINT_U32(tv, ret); /* no need to incref */
  14581. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14582. return ret;
  14583. #else
  14584. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14585. DUK_TVAL_SET_NUMBER(tv, (duk_double_t) ret); /* no need to incref */
  14586. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14587. #endif
  14588. return ret;
  14589. }
  14590. DUK_EXTERNAL const char *duk_to_lstring(duk_context *ctx, duk_idx_t index, duk_size_t *out_len) {
  14591. (void) duk_to_string(ctx, index);
  14592. return duk_require_lstring(ctx, index, out_len);
  14593. }
  14594. DUK_LOCAL duk_ret_t duk__safe_to_string_raw(duk_context *ctx) {
  14595. duk_to_string(ctx, -1);
  14596. return 1;
  14597. }
  14598. DUK_EXTERNAL const char *duk_safe_to_lstring(duk_context *ctx, duk_idx_t index, duk_size_t *out_len) {
  14599. index = duk_require_normalize_index(ctx, index);
  14600. /* We intentionally ignore the duk_safe_call() return value and only
  14601. * check the output type. This way we don't also need to check that
  14602. * the returned value is indeed a string in the success case.
  14603. */
  14604. duk_dup(ctx, index);
  14605. (void) duk_safe_call(ctx, duk__safe_to_string_raw, 1 /*nargs*/, 1 /*nrets*/);
  14606. if (!duk_is_string(ctx, -1)) {
  14607. /* Error: try coercing error to string once. */
  14608. (void) duk_safe_call(ctx, duk__safe_to_string_raw, 1 /*nargs*/, 1 /*nrets*/);
  14609. if (!duk_is_string(ctx, -1)) {
  14610. /* Double error */
  14611. duk_pop(ctx);
  14612. duk_push_hstring_stridx(ctx, DUK_STRIDX_UC_ERROR);
  14613. } else {
  14614. ;
  14615. }
  14616. } else {
  14617. ;
  14618. }
  14619. DUK_ASSERT(duk_is_string(ctx, -1));
  14620. duk_replace(ctx, index);
  14621. return duk_require_lstring(ctx, index, out_len);
  14622. }
  14623. /* XXX: other variants like uint, u32 etc */
  14624. DUK_INTERNAL duk_int_t duk_to_int_clamped_raw(duk_context *ctx, duk_idx_t index, duk_int_t minval, duk_int_t maxval, duk_bool_t *out_clamped) {
  14625. duk_hthread *thr = (duk_hthread *) ctx;
  14626. duk_tval *tv;
  14627. duk_tval tv_tmp;
  14628. duk_double_t d, dmin, dmax;
  14629. duk_int_t res;
  14630. duk_bool_t clamped = 0;
  14631. DUK_ASSERT(ctx != NULL);
  14632. tv = duk_require_tval(ctx, index);
  14633. DUK_ASSERT(tv != NULL);
  14634. d = duk_js_tointeger(thr, tv); /* E5 Section 9.4, ToInteger() */
  14635. dmin = (duk_double_t) minval;
  14636. dmax = (duk_double_t) maxval;
  14637. if (d < dmin) {
  14638. clamped = 1;
  14639. res = minval;
  14640. d = dmin;
  14641. } else if (d > dmax) {
  14642. clamped = 1;
  14643. res = maxval;
  14644. d = dmax;
  14645. } else {
  14646. res = (duk_int_t) d;
  14647. }
  14648. /* 'd' and 'res' agree here */
  14649. /* Relookup in case duk_js_tointeger() ends up e.g. coercing an object. */
  14650. tv = duk_require_tval(ctx, index);
  14651. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  14652. #if defined(DUK_USE_FASTINT)
  14653. #if (DUK_INT_MAX <= 0x7fffffffL)
  14654. DUK_TVAL_SET_FASTINT_I32(tv, res);
  14655. #else
  14656. /* Clamping needed if duk_int_t is 64 bits. */
  14657. if (res >= DUK_FASTINT_MIN && res <= DUK_FASTINT_MAX) {
  14658. DUK_TVAL_SET_FASTINT(tv, res);
  14659. } else {
  14660. DUK_TVAL_SET_NUMBER(tv, d);
  14661. }
  14662. #endif
  14663. #else
  14664. DUK_TVAL_SET_NUMBER(tv, d); /* no need to incref */
  14665. #endif
  14666. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  14667. if (out_clamped) {
  14668. *out_clamped = clamped;
  14669. } else {
  14670. /* coerced value is updated to value stack even when RangeError thrown */
  14671. if (clamped) {
  14672. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_NUMBER_OUTSIDE_RANGE);
  14673. }
  14674. }
  14675. return res;
  14676. }
  14677. DUK_INTERNAL duk_int_t duk_to_int_clamped(duk_context *ctx, duk_idx_t index, duk_idx_t minval, duk_idx_t maxval) {
  14678. duk_bool_t dummy;
  14679. return duk_to_int_clamped_raw(ctx, index, minval, maxval, &dummy);
  14680. }
  14681. DUK_INTERNAL duk_int_t duk_to_int_check_range(duk_context *ctx, duk_idx_t index, duk_int_t minval, duk_int_t maxval) {
  14682. return duk_to_int_clamped_raw(ctx, index, minval, maxval, NULL); /* out_clamped==NULL -> RangeError if outside range */
  14683. }
  14684. DUK_EXTERNAL const char *duk_to_string(duk_context *ctx, duk_idx_t index) {
  14685. duk_hthread *thr = (duk_hthread *) ctx;
  14686. duk_tval *tv;
  14687. DUK_ASSERT(ctx != NULL);
  14688. DUK_UNREF(thr);
  14689. index = duk_require_normalize_index(ctx, index);
  14690. tv = duk_require_tval(ctx, index);
  14691. DUK_ASSERT(tv != NULL);
  14692. switch (DUK_TVAL_GET_TAG(tv)) {
  14693. case DUK_TAG_UNDEFINED: {
  14694. duk_push_hstring_stridx(ctx, DUK_STRIDX_LC_UNDEFINED);
  14695. break;
  14696. }
  14697. case DUK_TAG_NULL: {
  14698. duk_push_hstring_stridx(ctx, DUK_STRIDX_LC_NULL);
  14699. break;
  14700. }
  14701. case DUK_TAG_BOOLEAN: {
  14702. if (DUK_TVAL_GET_BOOLEAN(tv)) {
  14703. duk_push_hstring_stridx(ctx, DUK_STRIDX_TRUE);
  14704. } else {
  14705. duk_push_hstring_stridx(ctx, DUK_STRIDX_FALSE);
  14706. }
  14707. break;
  14708. }
  14709. case DUK_TAG_STRING: {
  14710. /* nop */
  14711. goto skip_replace;
  14712. }
  14713. case DUK_TAG_OBJECT: {
  14714. duk_to_primitive(ctx, index, DUK_HINT_STRING);
  14715. return duk_to_string(ctx, index); /* Note: recursive call */
  14716. }
  14717. case DUK_TAG_BUFFER: {
  14718. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  14719. /* Note: this allows creation of internal strings. */
  14720. DUK_ASSERT(h != NULL);
  14721. duk_push_lstring(ctx,
  14722. (const char *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h),
  14723. (duk_size_t) DUK_HBUFFER_GET_SIZE(h));
  14724. break;
  14725. }
  14726. case DUK_TAG_POINTER: {
  14727. void *ptr = DUK_TVAL_GET_POINTER(tv);
  14728. if (ptr != NULL) {
  14729. duk_push_sprintf(ctx, DUK_STR_FMT_PTR, (void *) ptr);
  14730. } else {
  14731. /* Represent a null pointer as 'null' to be consistent with
  14732. * the JX format variant. Native '%p' format for a NULL
  14733. * pointer may be e.g. '(nil)'.
  14734. */
  14735. duk_push_hstring_stridx(ctx, DUK_STRIDX_LC_NULL);
  14736. }
  14737. break;
  14738. }
  14739. case DUK_TAG_LIGHTFUNC: {
  14740. /* Should match Function.prototype.toString() */
  14741. duk_push_lightfunc_tostring(ctx, tv);
  14742. break;
  14743. }
  14744. #if defined(DUK_USE_FASTINT)
  14745. case DUK_TAG_FASTINT:
  14746. #endif
  14747. default: {
  14748. /* number */
  14749. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  14750. duk_push_tval(ctx, tv);
  14751. duk_numconv_stringify(ctx,
  14752. 10 /*radix*/,
  14753. 0 /*precision:shortest*/,
  14754. 0 /*force_exponential*/);
  14755. break;
  14756. }
  14757. }
  14758. duk_replace(ctx, index);
  14759. skip_replace:
  14760. return duk_require_string(ctx, index);
  14761. }
  14762. DUK_INTERNAL duk_hstring *duk_to_hstring(duk_context *ctx, duk_idx_t index) {
  14763. duk_hstring *ret;
  14764. DUK_ASSERT(ctx != NULL);
  14765. duk_to_string(ctx, index);
  14766. ret = duk_get_hstring(ctx, index);
  14767. DUK_ASSERT(ret != NULL);
  14768. return ret;
  14769. }
  14770. DUK_EXTERNAL void *duk_to_buffer_raw(duk_context *ctx, duk_idx_t index, duk_size_t *out_size, duk_uint_t mode) {
  14771. duk_hthread *thr = (duk_hthread *) ctx;
  14772. duk_hbuffer *h_buf;
  14773. const duk_uint8_t *src_data;
  14774. duk_size_t src_size;
  14775. duk_uint8_t *dst_data;
  14776. DUK_UNREF(thr);
  14777. index = duk_require_normalize_index(ctx, index);
  14778. h_buf = duk_get_hbuffer(ctx, index);
  14779. if (h_buf != NULL) {
  14780. /* Buffer is kept as is, with the fixed/dynamic nature of the
  14781. * buffer only changed if requested.
  14782. */
  14783. duk_uint_t tmp;
  14784. src_data = (const duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h_buf);
  14785. src_size = DUK_HBUFFER_GET_SIZE(h_buf);
  14786. tmp = (DUK_HBUFFER_HAS_DYNAMIC(h_buf) ? DUK_BUF_MODE_DYNAMIC : DUK_BUF_MODE_FIXED);
  14787. if (tmp == mode || mode == DUK_BUF_MODE_DONTCARE) {
  14788. /* Note: src_data may be NULL if input is a zero-size
  14789. * dynamic buffer.
  14790. */
  14791. dst_data = (duk_uint8_t *) src_data;
  14792. goto skip_copy;
  14793. }
  14794. } else {
  14795. /* Non-buffer value is first ToString() coerced, then converted
  14796. * to a buffer (fixed buffer is used unless a dynamic buffer is
  14797. * explicitly requested).
  14798. */
  14799. src_data = (const duk_uint8_t *) duk_to_lstring(ctx, index, &src_size);
  14800. }
  14801. dst_data = (duk_uint8_t *) duk_push_buffer(ctx, src_size, (mode == DUK_BUF_MODE_DYNAMIC) /*dynamic*/);
  14802. if (DUK_LIKELY(src_size > 0)) {
  14803. /* When src_size == 0, src_data may be NULL (if source
  14804. * buffer is dynamic), and dst_data may be NULL (if
  14805. * target buffer is dynamic). Avoid zero-size memcpy()
  14806. * with an invalid pointer.
  14807. */
  14808. DUK_MEMCPY(dst_data, src_data, src_size);
  14809. }
  14810. duk_replace(ctx, index);
  14811. skip_copy:
  14812. if (out_size) {
  14813. *out_size = src_size;
  14814. }
  14815. return dst_data;
  14816. }
  14817. DUK_EXTERNAL void *duk_to_pointer(duk_context *ctx, duk_idx_t index) {
  14818. duk_tval *tv;
  14819. void *res;
  14820. DUK_ASSERT(ctx != NULL);
  14821. index = duk_require_normalize_index(ctx, index);
  14822. tv = duk_require_tval(ctx, index);
  14823. DUK_ASSERT(tv != NULL);
  14824. switch (DUK_TVAL_GET_TAG(tv)) {
  14825. case DUK_TAG_UNDEFINED:
  14826. case DUK_TAG_NULL:
  14827. case DUK_TAG_BOOLEAN:
  14828. res = NULL;
  14829. break;
  14830. case DUK_TAG_POINTER:
  14831. res = DUK_TVAL_GET_POINTER(tv);
  14832. break;
  14833. case DUK_TAG_STRING:
  14834. case DUK_TAG_OBJECT:
  14835. case DUK_TAG_BUFFER:
  14836. /* Heap allocated: return heap pointer which is NOT useful
  14837. * for the caller, except for debugging.
  14838. */
  14839. res = (void *) DUK_TVAL_GET_HEAPHDR(tv);
  14840. break;
  14841. case DUK_TAG_LIGHTFUNC:
  14842. /* Function pointers do not always cast correctly to void *
  14843. * (depends on memory and segmentation model for instance),
  14844. * so they coerce to NULL.
  14845. */
  14846. res = NULL;
  14847. break;
  14848. #if defined(DUK_USE_FASTINT)
  14849. case DUK_TAG_FASTINT:
  14850. #endif
  14851. default:
  14852. /* number */
  14853. res = NULL;
  14854. break;
  14855. }
  14856. duk_push_pointer(ctx, res);
  14857. duk_replace(ctx, index);
  14858. return res;
  14859. }
  14860. DUK_EXTERNAL void duk_to_object(duk_context *ctx, duk_idx_t index) {
  14861. duk_hthread *thr = (duk_hthread *) ctx;
  14862. duk_tval *tv;
  14863. duk_uint_t flags = 0; /* shared flags for a subset of types */
  14864. duk_small_int_t proto = 0;
  14865. DUK_ASSERT(ctx != NULL);
  14866. index = duk_require_normalize_index(ctx, index);
  14867. tv = duk_require_tval(ctx, index);
  14868. DUK_ASSERT(tv != NULL);
  14869. switch (DUK_TVAL_GET_TAG(tv)) {
  14870. case DUK_TAG_UNDEFINED:
  14871. case DUK_TAG_NULL: {
  14872. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_OBJECT_COERCIBLE);
  14873. break;
  14874. }
  14875. case DUK_TAG_BOOLEAN: {
  14876. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  14877. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_BOOLEAN);
  14878. proto = DUK_BIDX_BOOLEAN_PROTOTYPE;
  14879. goto create_object;
  14880. }
  14881. case DUK_TAG_STRING: {
  14882. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  14883. DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ |
  14884. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_STRING);
  14885. proto = DUK_BIDX_STRING_PROTOTYPE;
  14886. goto create_object;
  14887. }
  14888. case DUK_TAG_OBJECT: {
  14889. /* nop */
  14890. break;
  14891. }
  14892. case DUK_TAG_BUFFER: {
  14893. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  14894. DUK_HOBJECT_FLAG_EXOTIC_BUFFEROBJ |
  14895. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_BUFFER);
  14896. proto = DUK_BIDX_BUFFER_PROTOTYPE;
  14897. goto create_object;
  14898. }
  14899. case DUK_TAG_POINTER: {
  14900. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  14901. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_POINTER);
  14902. proto = DUK_BIDX_POINTER_PROTOTYPE;
  14903. goto create_object;
  14904. }
  14905. case DUK_TAG_LIGHTFUNC: {
  14906. /* Lightfunc coerces to a Function instance with concrete
  14907. * properties. Since 'length' is virtual for Duktape/C
  14908. * functions, don't need to define that.
  14909. *
  14910. * The result is made extensible to mimic what happens to
  14911. * strings:
  14912. * > Object.isExtensible(Object('foo'))
  14913. * true
  14914. */
  14915. duk_small_uint_t lf_flags;
  14916. duk_small_uint_t nargs;
  14917. duk_small_uint_t lf_len;
  14918. duk_c_function func;
  14919. duk_hnativefunction *nf;
  14920. DUK_TVAL_GET_LIGHTFUNC(tv, func, lf_flags);
  14921. nargs = DUK_LFUNC_FLAGS_GET_NARGS(lf_flags);
  14922. if (nargs == DUK_LFUNC_NARGS_VARARGS) {
  14923. nargs = DUK_VARARGS;
  14924. }
  14925. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  14926. DUK_HOBJECT_FLAG_CONSTRUCTABLE |
  14927. DUK_HOBJECT_FLAG_NATIVEFUNCTION |
  14928. DUK_HOBJECT_FLAG_NEWENV |
  14929. DUK_HOBJECT_FLAG_STRICT |
  14930. DUK_HOBJECT_FLAG_NOTAIL |
  14931. /* DUK_HOBJECT_FLAG_EXOTIC_DUKFUNC: omitted here intentionally */
  14932. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_FUNCTION);
  14933. (void) duk__push_c_function_raw(ctx, func, (duk_idx_t) nargs, flags);
  14934. lf_len = DUK_LFUNC_FLAGS_GET_LENGTH(lf_flags);
  14935. if (lf_len != nargs) {
  14936. /* Explicit length is only needed if it differs from 'nargs'. */
  14937. duk_push_int(ctx, (duk_int_t) lf_len);
  14938. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_NONE);
  14939. }
  14940. duk_push_lightfunc_name(ctx, tv);
  14941. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_NAME, DUK_PROPDESC_FLAGS_NONE);
  14942. nf = duk_get_hnativefunction(ctx, -1);
  14943. DUK_ASSERT(nf != NULL);
  14944. nf->magic = (duk_int16_t) DUK_LFUNC_FLAGS_GET_MAGIC(lf_flags);
  14945. /* Enable DUKFUNC exotic behavior once properties are set up. */
  14946. DUK_HOBJECT_SET_EXOTIC_DUKFUNC((duk_hobject *) nf);
  14947. goto replace_value;
  14948. }
  14949. #if defined(DUK_USE_FASTINT)
  14950. case DUK_TAG_FASTINT:
  14951. #endif
  14952. default: {
  14953. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  14954. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_NUMBER);
  14955. proto = DUK_BIDX_NUMBER_PROTOTYPE;
  14956. goto create_object;
  14957. }
  14958. }
  14959. return;
  14960. create_object:
  14961. (void) duk_push_object_helper(ctx, flags, proto);
  14962. /* Note: Boolean prototype's internal value property is not writable,
  14963. * but duk_xdef_prop_stridx() disregards the write protection. Boolean
  14964. * instances are immutable.
  14965. *
  14966. * String and buffer special behaviors are already enabled which is not
  14967. * ideal, but a write to the internal value is not affected by them.
  14968. */
  14969. duk_dup(ctx, index);
  14970. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_NONE);
  14971. replace_value:
  14972. duk_replace(ctx, index);
  14973. }
  14974. /*
  14975. * Type checking
  14976. */
  14977. DUK_LOCAL duk_bool_t duk__tag_check(duk_context *ctx, duk_idx_t index, duk_small_uint_t tag) {
  14978. duk_tval *tv;
  14979. tv = duk_get_tval(ctx, index);
  14980. if (!tv) {
  14981. return 0;
  14982. }
  14983. return (DUK_TVAL_GET_TAG(tv) == tag);
  14984. }
  14985. DUK_LOCAL duk_bool_t duk__obj_flag_any_default_false(duk_context *ctx, duk_idx_t index, duk_uint_t flag_mask) {
  14986. duk_hobject *obj;
  14987. DUK_ASSERT(ctx != NULL);
  14988. obj = duk_get_hobject(ctx, index);
  14989. if (obj) {
  14990. return (DUK_HEAPHDR_CHECK_FLAG_BITS((duk_heaphdr *) obj, flag_mask) ? 1 : 0);
  14991. }
  14992. return 0;
  14993. }
  14994. DUK_EXTERNAL duk_int_t duk_get_type(duk_context *ctx, duk_idx_t index) {
  14995. duk_tval *tv;
  14996. tv = duk_get_tval(ctx, index);
  14997. if (!tv) {
  14998. return DUK_TYPE_NONE;
  14999. }
  15000. switch (DUK_TVAL_GET_TAG(tv)) {
  15001. case DUK_TAG_UNDEFINED:
  15002. return DUK_TYPE_UNDEFINED;
  15003. case DUK_TAG_NULL:
  15004. return DUK_TYPE_NULL;
  15005. case DUK_TAG_BOOLEAN:
  15006. return DUK_TYPE_BOOLEAN;
  15007. case DUK_TAG_STRING:
  15008. return DUK_TYPE_STRING;
  15009. case DUK_TAG_OBJECT:
  15010. return DUK_TYPE_OBJECT;
  15011. case DUK_TAG_BUFFER:
  15012. return DUK_TYPE_BUFFER;
  15013. case DUK_TAG_POINTER:
  15014. return DUK_TYPE_POINTER;
  15015. case DUK_TAG_LIGHTFUNC:
  15016. return DUK_TYPE_LIGHTFUNC;
  15017. #if defined(DUK_USE_FASTINT)
  15018. case DUK_TAG_FASTINT:
  15019. #endif
  15020. default:
  15021. /* Note: number has no explicit tag (in 8-byte representation) */
  15022. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  15023. return DUK_TYPE_NUMBER;
  15024. }
  15025. DUK_UNREACHABLE();
  15026. }
  15027. DUK_EXTERNAL duk_bool_t duk_check_type(duk_context *ctx, duk_idx_t index, duk_int_t type) {
  15028. return (duk_get_type(ctx, index) == type) ? 1 : 0;
  15029. }
  15030. DUK_EXTERNAL duk_uint_t duk_get_type_mask(duk_context *ctx, duk_idx_t index) {
  15031. duk_tval *tv;
  15032. tv = duk_get_tval(ctx, index);
  15033. if (!tv) {
  15034. return DUK_TYPE_MASK_NONE;
  15035. }
  15036. switch (DUK_TVAL_GET_TAG(tv)) {
  15037. case DUK_TAG_UNDEFINED:
  15038. return DUK_TYPE_MASK_UNDEFINED;
  15039. case DUK_TAG_NULL:
  15040. return DUK_TYPE_MASK_NULL;
  15041. case DUK_TAG_BOOLEAN:
  15042. return DUK_TYPE_MASK_BOOLEAN;
  15043. case DUK_TAG_STRING:
  15044. return DUK_TYPE_MASK_STRING;
  15045. case DUK_TAG_OBJECT:
  15046. return DUK_TYPE_MASK_OBJECT;
  15047. case DUK_TAG_BUFFER:
  15048. return DUK_TYPE_MASK_BUFFER;
  15049. case DUK_TAG_POINTER:
  15050. return DUK_TYPE_MASK_POINTER;
  15051. case DUK_TAG_LIGHTFUNC:
  15052. return DUK_TYPE_MASK_LIGHTFUNC;
  15053. #if defined(DUK_USE_FASTINT)
  15054. case DUK_TAG_FASTINT:
  15055. #endif
  15056. default:
  15057. /* Note: number has no explicit tag (in 8-byte representation) */
  15058. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  15059. return DUK_TYPE_MASK_NUMBER;
  15060. }
  15061. DUK_UNREACHABLE();
  15062. }
  15063. DUK_EXTERNAL duk_bool_t duk_check_type_mask(duk_context *ctx, duk_idx_t index, duk_uint_t mask) {
  15064. duk_hthread *thr = (duk_hthread *) ctx;
  15065. DUK_ASSERT(ctx != NULL);
  15066. if (duk_get_type_mask(ctx, index) & mask) {
  15067. return 1;
  15068. }
  15069. if (mask & DUK_TYPE_MASK_THROW) {
  15070. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_UNEXPECTED_TYPE);
  15071. DUK_UNREACHABLE();
  15072. }
  15073. return 0;
  15074. }
  15075. DUK_EXTERNAL duk_bool_t duk_is_undefined(duk_context *ctx, duk_idx_t index) {
  15076. DUK_ASSERT(ctx != NULL);
  15077. return duk__tag_check(ctx, index, DUK_TAG_UNDEFINED);
  15078. }
  15079. DUK_EXTERNAL duk_bool_t duk_is_null(duk_context *ctx, duk_idx_t index) {
  15080. DUK_ASSERT(ctx != NULL);
  15081. return duk__tag_check(ctx, index, DUK_TAG_NULL);
  15082. }
  15083. DUK_EXTERNAL duk_bool_t duk_is_null_or_undefined(duk_context *ctx, duk_idx_t index) {
  15084. duk_tval *tv;
  15085. duk_small_uint_t tag;
  15086. tv = duk_get_tval(ctx, index);
  15087. if (!tv) {
  15088. return 0;
  15089. }
  15090. tag = DUK_TVAL_GET_TAG(tv);
  15091. return (tag == DUK_TAG_UNDEFINED) || (tag == DUK_TAG_NULL);
  15092. }
  15093. DUK_EXTERNAL duk_bool_t duk_is_boolean(duk_context *ctx, duk_idx_t index) {
  15094. DUK_ASSERT(ctx != NULL);
  15095. return duk__tag_check(ctx, index, DUK_TAG_BOOLEAN);
  15096. }
  15097. DUK_EXTERNAL duk_bool_t duk_is_number(duk_context *ctx, duk_idx_t index) {
  15098. duk_tval *tv;
  15099. DUK_ASSERT(ctx != NULL);
  15100. /*
  15101. * Number is special because it doesn't have a specific
  15102. * tag in the 8-byte representation.
  15103. */
  15104. /* XXX: shorter version for 12-byte representation? */
  15105. tv = duk_get_tval(ctx, index);
  15106. if (!tv) {
  15107. return 0;
  15108. }
  15109. return DUK_TVAL_IS_NUMBER(tv);
  15110. }
  15111. DUK_EXTERNAL duk_bool_t duk_is_nan(duk_context *ctx, duk_idx_t index) {
  15112. /* XXX: This will now return false for non-numbers, even though they would
  15113. * coerce to NaN (as a general rule). In particular, duk_get_number()
  15114. * returns a NaN for non-numbers, so should this function also return
  15115. * true for non-numbers?
  15116. */
  15117. duk_tval *tv;
  15118. tv = duk_get_tval(ctx, index);
  15119. if (!tv || !DUK_TVAL_IS_NUMBER(tv)) {
  15120. return 0;
  15121. }
  15122. return DUK_ISNAN(DUK_TVAL_GET_NUMBER(tv));
  15123. }
  15124. DUK_EXTERNAL duk_bool_t duk_is_string(duk_context *ctx, duk_idx_t index) {
  15125. DUK_ASSERT(ctx != NULL);
  15126. return duk__tag_check(ctx, index, DUK_TAG_STRING);
  15127. }
  15128. DUK_EXTERNAL duk_bool_t duk_is_object(duk_context *ctx, duk_idx_t index) {
  15129. DUK_ASSERT(ctx != NULL);
  15130. return duk__tag_check(ctx, index, DUK_TAG_OBJECT);
  15131. }
  15132. DUK_EXTERNAL duk_bool_t duk_is_buffer(duk_context *ctx, duk_idx_t index) {
  15133. DUK_ASSERT(ctx != NULL);
  15134. return duk__tag_check(ctx, index, DUK_TAG_BUFFER);
  15135. }
  15136. DUK_EXTERNAL duk_bool_t duk_is_pointer(duk_context *ctx, duk_idx_t index) {
  15137. DUK_ASSERT(ctx != NULL);
  15138. return duk__tag_check(ctx, index, DUK_TAG_POINTER);
  15139. }
  15140. DUK_EXTERNAL duk_bool_t duk_is_lightfunc(duk_context *ctx, duk_idx_t index) {
  15141. DUK_ASSERT(ctx != NULL);
  15142. return duk__tag_check(ctx, index, DUK_TAG_LIGHTFUNC);
  15143. }
  15144. DUK_EXTERNAL duk_bool_t duk_is_array(duk_context *ctx, duk_idx_t index) {
  15145. duk_hobject *obj;
  15146. DUK_ASSERT(ctx != NULL);
  15147. obj = duk_get_hobject(ctx, index);
  15148. if (obj) {
  15149. return (DUK_HOBJECT_GET_CLASS_NUMBER(obj) == DUK_HOBJECT_CLASS_ARRAY ? 1 : 0);
  15150. }
  15151. return 0;
  15152. }
  15153. DUK_EXTERNAL duk_bool_t duk_is_function(duk_context *ctx, duk_idx_t index) {
  15154. duk_tval *tv = duk_get_tval(ctx, index);
  15155. if (tv && DUK_TVAL_IS_LIGHTFUNC(tv)) {
  15156. return 1;
  15157. }
  15158. return duk__obj_flag_any_default_false(ctx,
  15159. index,
  15160. DUK_HOBJECT_FLAG_COMPILEDFUNCTION |
  15161. DUK_HOBJECT_FLAG_NATIVEFUNCTION |
  15162. DUK_HOBJECT_FLAG_BOUND);
  15163. }
  15164. DUK_EXTERNAL duk_bool_t duk_is_c_function(duk_context *ctx, duk_idx_t index) {
  15165. return duk__obj_flag_any_default_false(ctx,
  15166. index,
  15167. DUK_HOBJECT_FLAG_NATIVEFUNCTION);
  15168. }
  15169. DUK_EXTERNAL duk_bool_t duk_is_ecmascript_function(duk_context *ctx, duk_idx_t index) {
  15170. return duk__obj_flag_any_default_false(ctx,
  15171. index,
  15172. DUK_HOBJECT_FLAG_COMPILEDFUNCTION);
  15173. }
  15174. DUK_EXTERNAL duk_bool_t duk_is_bound_function(duk_context *ctx, duk_idx_t index) {
  15175. return duk__obj_flag_any_default_false(ctx,
  15176. index,
  15177. DUK_HOBJECT_FLAG_BOUND);
  15178. }
  15179. DUK_EXTERNAL duk_bool_t duk_is_thread(duk_context *ctx, duk_idx_t index) {
  15180. return duk__obj_flag_any_default_false(ctx,
  15181. index,
  15182. DUK_HOBJECT_FLAG_THREAD);
  15183. }
  15184. DUK_EXTERNAL duk_bool_t duk_is_callable(duk_context *ctx, duk_idx_t index) {
  15185. /* XXX: currently same as duk_is_function() */
  15186. return duk_is_function(ctx, index);
  15187. }
  15188. DUK_EXTERNAL duk_bool_t duk_is_dynamic_buffer(duk_context *ctx, duk_idx_t index) {
  15189. duk_tval *tv;
  15190. DUK_ASSERT(ctx != NULL);
  15191. tv = duk_get_tval(ctx, index);
  15192. if (tv && DUK_TVAL_IS_BUFFER(tv)) {
  15193. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  15194. DUK_ASSERT(h != NULL);
  15195. return (DUK_HBUFFER_HAS_DYNAMIC(h) ? 1 : 0);
  15196. }
  15197. return 0;
  15198. }
  15199. DUK_EXTERNAL duk_bool_t duk_is_fixed_buffer(duk_context *ctx, duk_idx_t index) {
  15200. duk_tval *tv;
  15201. DUK_ASSERT(ctx != NULL);
  15202. tv = duk_get_tval(ctx, index);
  15203. if (tv && DUK_TVAL_IS_BUFFER(tv)) {
  15204. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  15205. DUK_ASSERT(h != NULL);
  15206. return (DUK_HBUFFER_HAS_DYNAMIC(h) ? 0 : 1);
  15207. }
  15208. return 0;
  15209. }
  15210. /* XXX: make macro in API */
  15211. DUK_EXTERNAL duk_bool_t duk_is_primitive(duk_context *ctx, duk_idx_t index) {
  15212. DUK_ASSERT(ctx != NULL);
  15213. return !duk_is_object(ctx, index);
  15214. }
  15215. DUK_EXTERNAL duk_errcode_t duk_get_error_code(duk_context *ctx, duk_idx_t index) {
  15216. duk_hthread *thr = (duk_hthread *) ctx;
  15217. duk_hobject *h;
  15218. duk_uint_t sanity;
  15219. DUK_ASSERT(ctx != NULL);
  15220. h = duk_get_hobject(ctx, index);
  15221. sanity = DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY;
  15222. do {
  15223. if (!h) {
  15224. return DUK_ERR_NONE;
  15225. }
  15226. if (h == thr->builtins[DUK_BIDX_EVAL_ERROR_PROTOTYPE]) {
  15227. return DUK_ERR_EVAL_ERROR;
  15228. }
  15229. if (h == thr->builtins[DUK_BIDX_RANGE_ERROR_PROTOTYPE]) {
  15230. return DUK_ERR_RANGE_ERROR;
  15231. }
  15232. if (h == thr->builtins[DUK_BIDX_REFERENCE_ERROR_PROTOTYPE]) {
  15233. return DUK_ERR_REFERENCE_ERROR;
  15234. }
  15235. if (h == thr->builtins[DUK_BIDX_SYNTAX_ERROR_PROTOTYPE]) {
  15236. return DUK_ERR_SYNTAX_ERROR;
  15237. }
  15238. if (h == thr->builtins[DUK_BIDX_TYPE_ERROR_PROTOTYPE]) {
  15239. return DUK_ERR_TYPE_ERROR;
  15240. }
  15241. if (h == thr->builtins[DUK_BIDX_URI_ERROR_PROTOTYPE]) {
  15242. return DUK_ERR_URI_ERROR;
  15243. }
  15244. if (h == thr->builtins[DUK_BIDX_ERROR_PROTOTYPE]) {
  15245. return DUK_ERR_ERROR;
  15246. }
  15247. h = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h);
  15248. } while (--sanity > 0);
  15249. return DUK_ERR_NONE;
  15250. }
  15251. /*
  15252. * Pushers
  15253. */
  15254. DUK_INTERNAL void duk_push_tval(duk_context *ctx, duk_tval *tv) {
  15255. duk_hthread *thr;
  15256. duk_tval *tv_slot;
  15257. DUK_ASSERT(ctx != NULL);
  15258. DUK_ASSERT(tv != NULL);
  15259. thr = (duk_hthread *) ctx;
  15260. DUK__CHECK_SPACE();
  15261. tv_slot = thr->valstack_top++;
  15262. DUK_TVAL_SET_TVAL(tv_slot, tv);
  15263. DUK_TVAL_INCREF(thr, tv); /* no side effects */
  15264. }
  15265. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  15266. /* Right now only needed by the debugger. */
  15267. DUK_INTERNAL void duk_push_unused(duk_context *ctx) {
  15268. duk_hthread *thr;
  15269. duk_tval *tv_slot;
  15270. DUK_ASSERT(ctx != NULL);
  15271. thr = (duk_hthread *) ctx;
  15272. DUK__CHECK_SPACE();
  15273. tv_slot = thr->valstack_top++;
  15274. DUK_TVAL_SET_UNDEFINED_UNUSED(tv_slot);
  15275. }
  15276. #endif
  15277. DUK_EXTERNAL void duk_push_undefined(duk_context *ctx) {
  15278. duk_hthread *thr;
  15279. duk_tval *tv_slot;
  15280. DUK_ASSERT(ctx != NULL);
  15281. thr = (duk_hthread *) ctx;
  15282. DUK__CHECK_SPACE();
  15283. tv_slot = thr->valstack_top++;
  15284. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv_slot);
  15285. }
  15286. DUK_EXTERNAL void duk_push_null(duk_context *ctx) {
  15287. duk_hthread *thr;
  15288. duk_tval *tv_slot;
  15289. DUK_ASSERT(ctx != NULL);
  15290. thr = (duk_hthread *) ctx;
  15291. DUK__CHECK_SPACE();
  15292. tv_slot = thr->valstack_top++;
  15293. DUK_TVAL_SET_NULL(tv_slot);
  15294. }
  15295. DUK_EXTERNAL void duk_push_boolean(duk_context *ctx, duk_bool_t val) {
  15296. duk_hthread *thr;
  15297. duk_tval *tv_slot;
  15298. duk_small_int_t b;
  15299. DUK_ASSERT(ctx != NULL);
  15300. thr = (duk_hthread *) ctx;
  15301. DUK__CHECK_SPACE();
  15302. b = (val ? 1 : 0); /* ensure value is 1 or 0 (not other non-zero) */
  15303. tv_slot = thr->valstack_top++;
  15304. DUK_TVAL_SET_BOOLEAN(tv_slot, b);
  15305. }
  15306. DUK_EXTERNAL void duk_push_true(duk_context *ctx) {
  15307. duk_hthread *thr;
  15308. duk_tval *tv_slot;
  15309. DUK_ASSERT(ctx != NULL);
  15310. thr = (duk_hthread *) ctx;
  15311. DUK__CHECK_SPACE();
  15312. tv_slot = thr->valstack_top++;
  15313. DUK_TVAL_SET_BOOLEAN_TRUE(tv_slot);
  15314. }
  15315. DUK_EXTERNAL void duk_push_false(duk_context *ctx) {
  15316. duk_hthread *thr;
  15317. duk_tval *tv_slot;
  15318. DUK_ASSERT(ctx != NULL);
  15319. thr = (duk_hthread *) ctx;
  15320. DUK__CHECK_SPACE();
  15321. tv_slot = thr->valstack_top++;
  15322. DUK_TVAL_SET_BOOLEAN_FALSE(tv_slot);
  15323. }
  15324. /* normalize NaN which may not match our canonical internal NaN */
  15325. DUK_EXTERNAL void duk_push_number(duk_context *ctx, duk_double_t val) {
  15326. duk_hthread *thr;
  15327. duk_tval *tv_slot;
  15328. duk_double_union du;
  15329. DUK_ASSERT(ctx != NULL);
  15330. thr = (duk_hthread *) ctx;
  15331. DUK__CHECK_SPACE();
  15332. du.d = val;
  15333. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&du);
  15334. tv_slot = thr->valstack_top++;
  15335. DUK_TVAL_SET_NUMBER(tv_slot, du.d);
  15336. }
  15337. DUK_EXTERNAL void duk_push_int(duk_context *ctx, duk_int_t val) {
  15338. #if defined(DUK_USE_FASTINT)
  15339. duk_hthread *thr;
  15340. duk_tval *tv_slot;
  15341. DUK_ASSERT(ctx != NULL);
  15342. thr = (duk_hthread *) ctx;
  15343. DUK__CHECK_SPACE();
  15344. tv_slot = thr->valstack_top++;
  15345. #if DUK_INT_MAX <= 0x7fffffffL
  15346. DUK_TVAL_SET_FASTINT_I32(tv_slot, (duk_int32_t) val);
  15347. #else
  15348. if (val >= DUK_FASTINT_MIN && val <= DUK_FASTINT_MAX) {
  15349. DUK_TVAL_SET_FASTINT(tv_slot, (duk_int64_t) val);
  15350. } else {
  15351. duk_double_t = (duk_double_t) val;
  15352. DUK_TVAL_SET_NUMBER(tv_slot, d);
  15353. }
  15354. #endif
  15355. #else /* DUK_USE_FASTINT */
  15356. duk_hthread *thr;
  15357. duk_tval *tv_slot;
  15358. duk_double_t d;
  15359. DUK_ASSERT(ctx != NULL);
  15360. thr = (duk_hthread *) ctx;
  15361. DUK__CHECK_SPACE();
  15362. d = (duk_double_t) val;
  15363. tv_slot = thr->valstack_top++;
  15364. DUK_TVAL_SET_NUMBER(tv_slot, d);
  15365. #endif /* DUK_USE_FASTINT */
  15366. }
  15367. DUK_EXTERNAL void duk_push_uint(duk_context *ctx, duk_uint_t val) {
  15368. #if defined(DUK_USE_FASTINT)
  15369. duk_hthread *thr;
  15370. duk_tval *tv_slot;
  15371. DUK_ASSERT(ctx != NULL);
  15372. thr = (duk_hthread *) ctx;
  15373. DUK__CHECK_SPACE();
  15374. tv_slot = thr->valstack_top++;
  15375. #if DUK_UINT_MAX <= 0xffffffffUL
  15376. DUK_TVAL_SET_FASTINT_U32(tv_slot, (duk_uint32_t) val);
  15377. #else
  15378. if (val <= DUK_FASTINT_MAX) { /* val is unsigned so >= 0 */
  15379. /* XXX: take advantage of val being unsigned, no need to mask */
  15380. DUK_TVAL_SET_FASTINT(tv_slot, (duk_int64_t) val);
  15381. } else {
  15382. duk_double_t = (duk_double_t) val;
  15383. DUK_TVAL_SET_NUMBER(tv_slot, d);
  15384. }
  15385. #endif
  15386. #else /* DUK_USE_FASTINT */
  15387. duk_hthread *thr;
  15388. duk_tval *tv_slot;
  15389. duk_double_t d;
  15390. DUK_ASSERT(ctx != NULL);
  15391. thr = (duk_hthread *) ctx;
  15392. DUK__CHECK_SPACE();
  15393. d = (duk_double_t) val;
  15394. tv_slot = thr->valstack_top++;
  15395. DUK_TVAL_SET_NUMBER(tv_slot, d);
  15396. #endif /* DUK_USE_FASTINT */
  15397. }
  15398. DUK_EXTERNAL void duk_push_nan(duk_context *ctx) {
  15399. duk_hthread *thr;
  15400. duk_tval *tv_slot;
  15401. duk_double_union du;
  15402. DUK_ASSERT(ctx != NULL);
  15403. thr = (duk_hthread *) ctx;
  15404. DUK__CHECK_SPACE();
  15405. DUK_DBLUNION_SET_NAN(&du);
  15406. DUK_ASSERT(DUK_DBLUNION_IS_NORMALIZED(&du));
  15407. tv_slot = thr->valstack_top++;
  15408. DUK_TVAL_SET_NUMBER(tv_slot, du.d);
  15409. }
  15410. DUK_EXTERNAL const char *duk_push_lstring(duk_context *ctx, const char *str, duk_size_t len) {
  15411. duk_hthread *thr = (duk_hthread *) ctx;
  15412. duk_hstring *h;
  15413. duk_tval *tv_slot;
  15414. DUK_ASSERT(ctx != NULL);
  15415. /* check stack before interning (avoid hanging temp) */
  15416. if (thr->valstack_top >= thr->valstack_end) {
  15417. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  15418. }
  15419. /* NULL with zero length represents an empty string; NULL with higher
  15420. * length is also now trated like an empty string although it is
  15421. * a bit dubious. This is unlike duk_push_string() which pushes a
  15422. * 'null' if the input string is a NULL.
  15423. */
  15424. if (!str) {
  15425. len = 0;
  15426. }
  15427. /* Check for maximum string length */
  15428. if (len > DUK_HSTRING_MAX_BYTELEN) {
  15429. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_STRING_TOO_LONG);
  15430. }
  15431. h = duk_heap_string_intern_checked(thr, (duk_uint8_t *) str, (duk_uint32_t) len);
  15432. DUK_ASSERT(h != NULL);
  15433. tv_slot = thr->valstack_top++;
  15434. DUK_TVAL_SET_STRING(tv_slot, h);
  15435. DUK_HSTRING_INCREF(thr, h); /* no side effects */
  15436. return (const char *) DUK_HSTRING_GET_DATA(h);
  15437. }
  15438. DUK_EXTERNAL const char *duk_push_string(duk_context *ctx, const char *str) {
  15439. DUK_ASSERT(ctx != NULL);
  15440. if (str) {
  15441. return duk_push_lstring(ctx, str, DUK_STRLEN(str));
  15442. } else {
  15443. duk_push_null(ctx);
  15444. return NULL;
  15445. }
  15446. }
  15447. #ifdef DUK_USE_FILE_IO
  15448. /* This is a bit clunky because it is ANSI C portable. Should perhaps
  15449. * relocate to another file because this is potentially platform
  15450. * dependent.
  15451. */
  15452. DUK_EXTERNAL const char *duk_push_string_file_raw(duk_context *ctx, const char *path, duk_uint_t flags) {
  15453. duk_hthread *thr = (duk_hthread *) ctx;
  15454. duk_file *f = NULL;
  15455. char *buf;
  15456. long sz; /* ANSI C typing */
  15457. DUK_ASSERT(ctx != NULL);
  15458. if (!path) {
  15459. goto fail;
  15460. }
  15461. f = DUK_FOPEN(path, "rb");
  15462. if (!f) {
  15463. goto fail;
  15464. }
  15465. if (DUK_FSEEK(f, 0, SEEK_END) < 0) {
  15466. goto fail;
  15467. }
  15468. sz = DUK_FTELL(f);
  15469. if (sz < 0) {
  15470. goto fail;
  15471. }
  15472. if (DUK_FSEEK(f, 0, SEEK_SET) < 0) {
  15473. goto fail;
  15474. }
  15475. buf = (char *) duk_push_fixed_buffer(ctx, (duk_size_t) sz);
  15476. DUK_ASSERT(buf != NULL);
  15477. if ((duk_size_t) DUK_FREAD(buf, 1, (size_t) sz, f) != (duk_size_t) sz) {
  15478. goto fail;
  15479. }
  15480. (void) DUK_FCLOSE(f); /* ignore fclose() error */
  15481. f = NULL;
  15482. return duk_to_string(ctx, -1);
  15483. fail:
  15484. if (f) {
  15485. DUK_FCLOSE(f);
  15486. }
  15487. if (flags != 0) {
  15488. DUK_ASSERT(flags == DUK_STRING_PUSH_SAFE); /* only flag now */
  15489. duk_push_undefined(ctx);
  15490. } else {
  15491. /* XXX: string not shared because it is conditional */
  15492. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "read file error");
  15493. }
  15494. return NULL;
  15495. }
  15496. #else
  15497. DUK_EXTERNAL const char *duk_push_string_file_raw(duk_context *ctx, const char *path, duk_uint_t flags) {
  15498. duk_hthread *thr = (duk_hthread *) ctx;
  15499. DUK_ASSERT(ctx != NULL);
  15500. DUK_UNREF(path);
  15501. if (flags != 0) {
  15502. DUK_ASSERT(flags == DUK_STRING_PUSH_SAFE); /* only flag now */
  15503. duk_push_undefined(ctx);
  15504. } else {
  15505. /* XXX: string not shared because it is conditional */
  15506. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "file I/O disabled");
  15507. }
  15508. return NULL;
  15509. }
  15510. #endif /* DUK_USE_FILE_IO */
  15511. DUK_EXTERNAL void duk_push_pointer(duk_context *ctx, void *val) {
  15512. duk_hthread *thr;
  15513. duk_tval *tv_slot;
  15514. DUK_ASSERT(ctx != NULL);
  15515. thr = (duk_hthread *) ctx;
  15516. DUK__CHECK_SPACE();
  15517. tv_slot = thr->valstack_top++;
  15518. DUK_TVAL_SET_POINTER(tv_slot, val);
  15519. }
  15520. #define DUK__PUSH_THIS_FLAG_CHECK_COERC (1 << 0)
  15521. #define DUK__PUSH_THIS_FLAG_TO_OBJECT (1 << 1)
  15522. #define DUK__PUSH_THIS_FLAG_TO_STRING (1 << 2)
  15523. DUK_LOCAL void duk__push_this_helper(duk_context *ctx, duk_small_uint_t flags) {
  15524. duk_hthread *thr = (duk_hthread *) ctx;
  15525. DUK_ASSERT(thr != NULL);
  15526. DUK_ASSERT(ctx != NULL);
  15527. DUK_ASSERT_DISABLE(thr->callstack_top >= 0); /* avoid warning (unsigned) */
  15528. DUK_ASSERT(thr->callstack_top <= thr->callstack_size);
  15529. if (thr->callstack_top == 0) {
  15530. if (flags & DUK__PUSH_THIS_FLAG_CHECK_COERC) {
  15531. goto type_error;
  15532. }
  15533. duk_push_undefined(ctx);
  15534. } else {
  15535. duk_tval tv_tmp;
  15536. duk_tval *tv;
  15537. /* 'this' binding is just before current activation's bottom */
  15538. DUK_ASSERT(thr->valstack_bottom > thr->valstack);
  15539. tv = thr->valstack_bottom - 1;
  15540. if (flags & DUK__PUSH_THIS_FLAG_CHECK_COERC) {
  15541. if (DUK_TVAL_IS_UNDEFINED(tv) || DUK_TVAL_IS_NULL(tv)) {
  15542. goto type_error;
  15543. }
  15544. }
  15545. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  15546. duk_push_tval(ctx, &tv_tmp);
  15547. }
  15548. if (flags & DUK__PUSH_THIS_FLAG_TO_OBJECT) {
  15549. duk_to_object(ctx, -1);
  15550. } else if (flags & DUK__PUSH_THIS_FLAG_TO_STRING) {
  15551. duk_to_string(ctx, -1);
  15552. }
  15553. return;
  15554. type_error:
  15555. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_OBJECT_COERCIBLE);
  15556. }
  15557. DUK_EXTERNAL void duk_push_this(duk_context *ctx) {
  15558. duk__push_this_helper(ctx, 0 /*flags*/);
  15559. }
  15560. DUK_INTERNAL void duk_push_this_check_object_coercible(duk_context *ctx) {
  15561. duk__push_this_helper(ctx, DUK__PUSH_THIS_FLAG_CHECK_COERC /*flags*/);
  15562. }
  15563. DUK_INTERNAL duk_hobject *duk_push_this_coercible_to_object(duk_context *ctx) {
  15564. duk_hobject *h;
  15565. duk__push_this_helper(ctx, DUK__PUSH_THIS_FLAG_CHECK_COERC |
  15566. DUK__PUSH_THIS_FLAG_TO_OBJECT /*flags*/);
  15567. h = duk_get_hobject(ctx, -1);
  15568. DUK_ASSERT(h != NULL);
  15569. return h;
  15570. }
  15571. DUK_INTERNAL duk_hstring *duk_push_this_coercible_to_string(duk_context *ctx) {
  15572. duk_hstring *h;
  15573. duk__push_this_helper(ctx, DUK__PUSH_THIS_FLAG_CHECK_COERC |
  15574. DUK__PUSH_THIS_FLAG_TO_STRING /*flags*/);
  15575. h = duk_get_hstring(ctx, -1);
  15576. DUK_ASSERT(h != NULL);
  15577. return h;
  15578. }
  15579. DUK_EXTERNAL void duk_push_current_function(duk_context *ctx) {
  15580. duk_hthread *thr = (duk_hthread *) ctx;
  15581. duk_activation *act;
  15582. DUK_ASSERT(thr != NULL);
  15583. DUK_ASSERT(ctx != NULL);
  15584. DUK_ASSERT_DISABLE(thr->callstack_top >= 0);
  15585. DUK_ASSERT(thr->callstack_top <= thr->callstack_size);
  15586. act = duk_hthread_get_current_activation(thr);
  15587. if (act) {
  15588. duk_push_tval(ctx, &act->tv_func);
  15589. } else {
  15590. duk_push_undefined(ctx);
  15591. }
  15592. }
  15593. DUK_EXTERNAL void duk_push_current_thread(duk_context *ctx) {
  15594. duk_hthread *thr = (duk_hthread *) ctx;
  15595. DUK_ASSERT(thr != NULL);
  15596. DUK_ASSERT(ctx != NULL);
  15597. if (thr->heap->curr_thread) {
  15598. duk_push_hobject(ctx, (duk_hobject *) thr->heap->curr_thread);
  15599. } else {
  15600. duk_push_undefined(ctx);
  15601. }
  15602. }
  15603. DUK_EXTERNAL void duk_push_global_object(duk_context *ctx) {
  15604. DUK_ASSERT(ctx != NULL);
  15605. duk_push_hobject_bidx(ctx, DUK_BIDX_GLOBAL);
  15606. }
  15607. /* XXX: size optimize */
  15608. DUK_LOCAL void duk__push_stash(duk_context *ctx) {
  15609. DUK_ASSERT(ctx != NULL);
  15610. if (!duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE)) {
  15611. DUK_DDD(DUK_DDDPRINT("creating heap/global/thread stash on first use"));
  15612. duk_pop(ctx);
  15613. duk_push_object_internal(ctx);
  15614. duk_dup_top(ctx);
  15615. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_C); /* [ ... parent stash stash ] -> [ ... parent stash ] */
  15616. }
  15617. duk_remove(ctx, -2);
  15618. }
  15619. DUK_EXTERNAL void duk_push_heap_stash(duk_context *ctx) {
  15620. duk_hthread *thr = (duk_hthread *) ctx;
  15621. duk_heap *heap;
  15622. DUK_ASSERT(ctx != NULL);
  15623. heap = thr->heap;
  15624. DUK_ASSERT(heap->heap_object != NULL);
  15625. duk_push_hobject(ctx, heap->heap_object);
  15626. duk__push_stash(ctx);
  15627. }
  15628. DUK_EXTERNAL void duk_push_global_stash(duk_context *ctx) {
  15629. DUK_ASSERT(ctx != NULL);
  15630. duk_push_global_object(ctx);
  15631. duk__push_stash(ctx);
  15632. }
  15633. DUK_EXTERNAL void duk_push_thread_stash(duk_context *ctx, duk_context *target_ctx) {
  15634. duk_hthread *thr = (duk_hthread *) ctx;
  15635. DUK_ASSERT(ctx != NULL);
  15636. if (!target_ctx) {
  15637. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  15638. return; /* not reached */
  15639. }
  15640. duk_push_hobject(ctx, (duk_hobject *) target_ctx);
  15641. duk__push_stash(ctx);
  15642. }
  15643. /* XXX: duk_ssize_t would be useful here */
  15644. DUK_LOCAL duk_int_t duk__try_push_vsprintf(duk_context *ctx, void *buf, duk_size_t sz, const char *fmt, va_list ap) {
  15645. duk_int_t len;
  15646. DUK_UNREF(ctx);
  15647. /* NUL terminator handling doesn't matter here */
  15648. len = DUK_VSNPRINTF((char *) buf, sz, fmt, ap);
  15649. if (len < (duk_int_t) sz) {
  15650. /* Return value of 'sz' or more indicates output was (potentially)
  15651. * truncated.
  15652. */
  15653. return (duk_int_t) len;
  15654. }
  15655. return -1;
  15656. }
  15657. DUK_EXTERNAL const char *duk_push_vsprintf(duk_context *ctx, const char *fmt, va_list ap) {
  15658. duk_hthread *thr = (duk_hthread *) ctx;
  15659. duk_uint8_t stack_buf[DUK_PUSH_SPRINTF_INITIAL_SIZE];
  15660. duk_size_t sz = DUK_PUSH_SPRINTF_INITIAL_SIZE;
  15661. duk_bool_t pushed_buf = 0;
  15662. void *buf;
  15663. duk_int_t len; /* XXX: duk_ssize_t */
  15664. const char *res;
  15665. DUK_ASSERT(ctx != NULL);
  15666. /* special handling of fmt==NULL */
  15667. if (!fmt) {
  15668. duk_hstring *h_str;
  15669. duk_push_hstring_stridx(ctx, DUK_STRIDX_EMPTY_STRING);
  15670. h_str = DUK_HTHREAD_STRING_EMPTY_STRING(thr); /* rely on interning, must be this string */
  15671. return (const char *) DUK_HSTRING_GET_DATA(h_str);
  15672. }
  15673. /* initial estimate based on format string */
  15674. sz = DUK_STRLEN(fmt) + 16; /* format plus something to avoid just missing */
  15675. if (sz < DUK_PUSH_SPRINTF_INITIAL_SIZE) {
  15676. sz = DUK_PUSH_SPRINTF_INITIAL_SIZE;
  15677. }
  15678. DUK_ASSERT(sz > 0);
  15679. /* Try to make do with a stack buffer to avoid allocating a temporary buffer.
  15680. * This works 99% of the time which is quite nice.
  15681. */
  15682. for (;;) {
  15683. va_list ap_copy; /* copied so that 'ap' can be reused */
  15684. if (sz <= sizeof(stack_buf)) {
  15685. buf = stack_buf;
  15686. } else if (!pushed_buf) {
  15687. pushed_buf = 1;
  15688. buf = duk_push_dynamic_buffer(ctx, sz);
  15689. } else {
  15690. buf = duk_resize_buffer(ctx, -1, sz);
  15691. }
  15692. DUK_ASSERT(buf != NULL);
  15693. DUK_VA_COPY(ap_copy, ap);
  15694. len = duk__try_push_vsprintf(ctx, buf, sz, fmt, ap_copy);
  15695. va_end(ap_copy);
  15696. if (len >= 0) {
  15697. break;
  15698. }
  15699. /* failed, resize and try again */
  15700. sz = sz * 2;
  15701. if (sz >= DUK_PUSH_SPRINTF_SANITY_LIMIT) {
  15702. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_SPRINTF_TOO_LONG);
  15703. }
  15704. }
  15705. /* Cannot use duk_to_string() on the buffer because it is usually
  15706. * larger than 'len'. Also, 'buf' is usually a stack buffer.
  15707. */
  15708. res = duk_push_lstring(ctx, (const char *) buf, (duk_size_t) len); /* [ buf? res ] */
  15709. if (pushed_buf) {
  15710. duk_remove(ctx, -2);
  15711. }
  15712. return res;
  15713. }
  15714. DUK_EXTERNAL const char *duk_push_sprintf(duk_context *ctx, const char *fmt, ...) {
  15715. va_list ap;
  15716. const char *ret;
  15717. /* allow fmt==NULL */
  15718. va_start(ap, fmt);
  15719. ret = duk_push_vsprintf(ctx, fmt, ap);
  15720. va_end(ap);
  15721. return ret;
  15722. }
  15723. DUK_INTERNAL duk_idx_t duk_push_object_helper(duk_context *ctx, duk_uint_t hobject_flags_and_class, duk_small_int_t prototype_bidx) {
  15724. duk_hthread *thr = (duk_hthread *) ctx;
  15725. duk_tval *tv_slot;
  15726. duk_hobject *h;
  15727. duk_idx_t ret;
  15728. DUK_ASSERT(ctx != NULL);
  15729. DUK_ASSERT(prototype_bidx == -1 ||
  15730. (prototype_bidx >= 0 && prototype_bidx < DUK_NUM_BUILTINS));
  15731. /* check stack first */
  15732. if (thr->valstack_top >= thr->valstack_end) {
  15733. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  15734. }
  15735. h = duk_hobject_alloc(thr->heap, hobject_flags_and_class);
  15736. if (!h) {
  15737. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_OBJECT_ALLOC_FAILED);
  15738. }
  15739. DUK_DDD(DUK_DDDPRINT("created object with flags: 0x%08lx", (unsigned long) h->hdr.h_flags));
  15740. tv_slot = thr->valstack_top;
  15741. DUK_TVAL_SET_OBJECT(tv_slot, h);
  15742. DUK_HOBJECT_INCREF(thr, h); /* no side effects */
  15743. ret = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  15744. thr->valstack_top++;
  15745. /* object is now reachable */
  15746. if (prototype_bidx >= 0) {
  15747. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, h, thr->builtins[prototype_bidx]);
  15748. } else {
  15749. DUK_ASSERT(prototype_bidx == -1);
  15750. DUK_ASSERT(DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h) == NULL);
  15751. }
  15752. return ret;
  15753. }
  15754. DUK_INTERNAL duk_idx_t duk_push_object_helper_proto(duk_context *ctx, duk_uint_t hobject_flags_and_class, duk_hobject *proto) {
  15755. duk_hthread *thr = (duk_hthread *) ctx;
  15756. duk_idx_t ret;
  15757. duk_hobject *h;
  15758. ret = duk_push_object_helper(ctx, hobject_flags_and_class, -1);
  15759. h = duk_get_hobject(ctx, -1);
  15760. DUK_ASSERT(h != NULL);
  15761. DUK_ASSERT(DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h) == NULL);
  15762. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, h, proto);
  15763. return ret;
  15764. }
  15765. DUK_EXTERNAL duk_idx_t duk_push_object(duk_context *ctx) {
  15766. return duk_push_object_helper(ctx,
  15767. DUK_HOBJECT_FLAG_EXTENSIBLE |
  15768. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT),
  15769. DUK_BIDX_OBJECT_PROTOTYPE);
  15770. }
  15771. DUK_EXTERNAL duk_idx_t duk_push_array(duk_context *ctx) {
  15772. duk_hthread *thr = (duk_hthread *) ctx;
  15773. duk_hobject *obj;
  15774. duk_idx_t ret;
  15775. ret = duk_push_object_helper(ctx,
  15776. DUK_HOBJECT_FLAG_EXTENSIBLE |
  15777. DUK_HOBJECT_FLAG_ARRAY_PART |
  15778. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_ARRAY),
  15779. DUK_BIDX_ARRAY_PROTOTYPE);
  15780. obj = duk_require_hobject(ctx, ret);
  15781. /*
  15782. * An array must have a 'length' property (E5 Section 15.4.5.2).
  15783. * The special array behavior flag must only be enabled once the
  15784. * length property has been added.
  15785. *
  15786. * The internal property must be a number (and preferably a
  15787. * fastint if fastint support is enabled).
  15788. */
  15789. duk_push_int(ctx, 0);
  15790. #if defined(DUK_USE_FASTINT)
  15791. DUK_ASSERT(DUK_TVAL_IS_FASTINT(duk_require_tval(ctx, -1)));
  15792. #endif
  15793. duk_hobject_define_property_internal(thr,
  15794. obj,
  15795. DUK_HTHREAD_STRING_LENGTH(thr),
  15796. DUK_PROPDESC_FLAGS_W);
  15797. DUK_HOBJECT_SET_EXOTIC_ARRAY(obj);
  15798. return ret;
  15799. }
  15800. DUK_EXTERNAL duk_idx_t duk_push_thread_raw(duk_context *ctx, duk_uint_t flags) {
  15801. duk_hthread *thr = (duk_hthread *) ctx;
  15802. duk_hthread *obj;
  15803. duk_idx_t ret;
  15804. duk_tval *tv_slot;
  15805. DUK_ASSERT(ctx != NULL);
  15806. /* check stack first */
  15807. if (thr->valstack_top >= thr->valstack_end) {
  15808. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  15809. }
  15810. obj = duk_hthread_alloc(thr->heap,
  15811. DUK_HOBJECT_FLAG_EXTENSIBLE |
  15812. DUK_HOBJECT_FLAG_THREAD |
  15813. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_THREAD));
  15814. if (!obj) {
  15815. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_THREAD_ALLOC_FAILED);
  15816. }
  15817. obj->state = DUK_HTHREAD_STATE_INACTIVE;
  15818. #if defined(DUK_USE_HEAPPTR16)
  15819. obj->strs16 = thr->strs16;
  15820. #else
  15821. obj->strs = thr->strs;
  15822. #endif
  15823. DUK_DDD(DUK_DDDPRINT("created thread object with flags: 0x%08lx", (unsigned long) obj->obj.hdr.h_flags));
  15824. /* make the new thread reachable */
  15825. tv_slot = thr->valstack_top;
  15826. DUK_TVAL_SET_OBJECT(tv_slot, (duk_hobject *) obj);
  15827. DUK_HTHREAD_INCREF(thr, obj);
  15828. ret = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  15829. thr->valstack_top++;
  15830. /* important to do this *after* pushing, to make the thread reachable for gc */
  15831. if (!duk_hthread_init_stacks(thr->heap, obj)) {
  15832. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_THREAD_ALLOC_FAILED);
  15833. }
  15834. /* initialize built-ins - either by copying or creating new ones */
  15835. if (flags & DUK_THREAD_NEW_GLOBAL_ENV) {
  15836. duk_hthread_create_builtin_objects(obj);
  15837. } else {
  15838. duk_hthread_copy_builtin_objects(thr, obj);
  15839. }
  15840. /* default prototype (Note: 'obj' must be reachable) */
  15841. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, (duk_hobject *) obj, obj->builtins[DUK_BIDX_THREAD_PROTOTYPE]);
  15842. /* Initial stack size satisfies the stack spare constraints so there
  15843. * is no need to require stack here.
  15844. */
  15845. DUK_ASSERT(DUK_VALSTACK_INITIAL_SIZE >=
  15846. DUK_VALSTACK_API_ENTRY_MINIMUM + DUK_VALSTACK_INTERNAL_EXTRA);
  15847. return ret;
  15848. }
  15849. DUK_INTERNAL duk_idx_t duk_push_compiledfunction(duk_context *ctx) {
  15850. duk_hthread *thr = (duk_hthread *) ctx;
  15851. duk_hcompiledfunction *obj;
  15852. duk_idx_t ret;
  15853. duk_tval *tv_slot;
  15854. DUK_ASSERT(ctx != NULL);
  15855. /* check stack first */
  15856. if (thr->valstack_top >= thr->valstack_end) {
  15857. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  15858. }
  15859. /* Template functions are not strictly constructable (they don't
  15860. * have a "prototype" property for instance), so leave the
  15861. * DUK_HOBJECT_FLAG_CONSRUCTABLE flag cleared here.
  15862. */
  15863. obj = duk_hcompiledfunction_alloc(thr->heap,
  15864. DUK_HOBJECT_FLAG_EXTENSIBLE |
  15865. DUK_HOBJECT_FLAG_COMPILEDFUNCTION |
  15866. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_FUNCTION));
  15867. if (!obj) {
  15868. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_FUNC_ALLOC_FAILED);
  15869. }
  15870. DUK_DDD(DUK_DDDPRINT("created compiled function object with flags: 0x%08lx", (unsigned long) obj->obj.hdr.h_flags));
  15871. tv_slot = thr->valstack_top;
  15872. DUK_TVAL_SET_OBJECT(tv_slot, (duk_hobject *) obj);
  15873. DUK_HOBJECT_INCREF(thr, obj);
  15874. ret = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  15875. thr->valstack_top++;
  15876. /* default prototype (Note: 'obj' must be reachable) */
  15877. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, (duk_hobject *) obj, thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE]);
  15878. return ret;
  15879. }
  15880. DUK_LOCAL duk_idx_t duk__push_c_function_raw(duk_context *ctx, duk_c_function func, duk_idx_t nargs, duk_uint_t flags) {
  15881. duk_hthread *thr = (duk_hthread *) ctx;
  15882. duk_hnativefunction *obj;
  15883. duk_idx_t ret;
  15884. duk_tval *tv_slot;
  15885. duk_uint16_t func_nargs;
  15886. DUK_ASSERT(ctx != NULL);
  15887. /* check stack first */
  15888. if (thr->valstack_top >= thr->valstack_end) {
  15889. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  15890. }
  15891. if (func == NULL) {
  15892. goto api_error;
  15893. }
  15894. if (nargs >= 0 && nargs < DUK_HNATIVEFUNCTION_NARGS_MAX) {
  15895. func_nargs = (duk_uint16_t) nargs;
  15896. } else if (nargs == DUK_VARARGS) {
  15897. func_nargs = DUK_HNATIVEFUNCTION_NARGS_VARARGS;
  15898. } else {
  15899. goto api_error;
  15900. }
  15901. obj = duk_hnativefunction_alloc(thr->heap, flags);
  15902. if (!obj) {
  15903. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_FUNC_ALLOC_FAILED);
  15904. }
  15905. obj->func = func;
  15906. obj->nargs = func_nargs;
  15907. DUK_DDD(DUK_DDDPRINT("created native function object with flags: 0x%08lx, nargs=%ld",
  15908. (unsigned long) obj->obj.hdr.h_flags, (long) obj->nargs));
  15909. tv_slot = thr->valstack_top;
  15910. DUK_TVAL_SET_OBJECT(tv_slot, (duk_hobject *) obj);
  15911. DUK_HOBJECT_INCREF(thr, obj);
  15912. ret = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  15913. thr->valstack_top++;
  15914. /* default prototype (Note: 'obj' must be reachable) */
  15915. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, (duk_hobject *) obj, thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE]);
  15916. return ret;
  15917. api_error:
  15918. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  15919. return 0; /* not reached */
  15920. }
  15921. DUK_EXTERNAL duk_idx_t duk_push_c_function(duk_context *ctx, duk_c_function func, duk_int_t nargs) {
  15922. duk_uint_t flags;
  15923. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  15924. DUK_HOBJECT_FLAG_CONSTRUCTABLE |
  15925. DUK_HOBJECT_FLAG_NATIVEFUNCTION |
  15926. DUK_HOBJECT_FLAG_NEWENV |
  15927. DUK_HOBJECT_FLAG_STRICT |
  15928. DUK_HOBJECT_FLAG_NOTAIL |
  15929. DUK_HOBJECT_FLAG_EXOTIC_DUKFUNC |
  15930. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_FUNCTION);
  15931. return duk__push_c_function_raw(ctx, func, nargs, flags);
  15932. }
  15933. DUK_INTERNAL void duk_push_c_function_noexotic(duk_context *ctx, duk_c_function func, duk_int_t nargs) {
  15934. duk_uint_t flags;
  15935. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  15936. DUK_HOBJECT_FLAG_CONSTRUCTABLE |
  15937. DUK_HOBJECT_FLAG_NATIVEFUNCTION |
  15938. DUK_HOBJECT_FLAG_NEWENV |
  15939. DUK_HOBJECT_FLAG_STRICT |
  15940. DUK_HOBJECT_FLAG_NOTAIL |
  15941. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_FUNCTION);
  15942. (void) duk__push_c_function_raw(ctx, func, nargs, flags);
  15943. }
  15944. DUK_INTERNAL void duk_push_c_function_noconstruct_noexotic(duk_context *ctx, duk_c_function func, duk_int_t nargs) {
  15945. duk_uint_t flags;
  15946. flags = DUK_HOBJECT_FLAG_EXTENSIBLE |
  15947. DUK_HOBJECT_FLAG_NATIVEFUNCTION |
  15948. DUK_HOBJECT_FLAG_NEWENV |
  15949. DUK_HOBJECT_FLAG_STRICT |
  15950. DUK_HOBJECT_FLAG_NOTAIL |
  15951. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_FUNCTION);
  15952. (void) duk__push_c_function_raw(ctx, func, nargs, flags);
  15953. }
  15954. DUK_EXTERNAL duk_idx_t duk_push_c_lightfunc(duk_context *ctx, duk_c_function func, duk_idx_t nargs, duk_idx_t length, duk_int_t magic) {
  15955. duk_hthread *thr = (duk_hthread *) ctx;
  15956. duk_tval tv_tmp;
  15957. duk_small_uint_t lf_flags;
  15958. DUK_ASSERT(ctx != NULL);
  15959. /* check stack first */
  15960. if (thr->valstack_top >= thr->valstack_end) {
  15961. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  15962. }
  15963. if (nargs >= DUK_LFUNC_NARGS_MIN && nargs <= DUK_LFUNC_NARGS_MAX) {
  15964. /* as is */
  15965. } else if (nargs == DUK_VARARGS) {
  15966. nargs = DUK_LFUNC_NARGS_VARARGS;
  15967. } else {
  15968. goto api_error;
  15969. }
  15970. if (!(length >= DUK_LFUNC_LENGTH_MIN && length <= DUK_LFUNC_LENGTH_MAX)) {
  15971. goto api_error;
  15972. }
  15973. if (!(magic >= DUK_LFUNC_MAGIC_MIN && magic <= DUK_LFUNC_MAGIC_MAX)) {
  15974. goto api_error;
  15975. }
  15976. lf_flags = DUK_LFUNC_FLAGS_PACK(magic, length, nargs);
  15977. DUK_TVAL_SET_LIGHTFUNC(&tv_tmp, func, lf_flags);
  15978. duk_push_tval(ctx, &tv_tmp); /* XXX: direct valstack write */
  15979. DUK_ASSERT(thr->valstack_top != thr->valstack_bottom);
  15980. return ((duk_idx_t) (thr->valstack_top - thr->valstack_bottom)) - 1;
  15981. api_error:
  15982. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  15983. return 0; /* not reached */
  15984. }
  15985. DUK_EXTERNAL duk_idx_t duk_push_error_object_va_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, va_list ap) {
  15986. duk_hthread *thr = (duk_hthread *) ctx;
  15987. duk_idx_t ret;
  15988. duk_hobject *proto;
  15989. #ifdef DUK_USE_AUGMENT_ERROR_CREATE
  15990. duk_bool_t noblame_fileline;
  15991. #endif
  15992. DUK_ASSERT(ctx != NULL);
  15993. DUK_ASSERT(thr != NULL);
  15994. DUK_UNREF(filename);
  15995. DUK_UNREF(line);
  15996. /* Error code also packs a tracedata related flag. */
  15997. #ifdef DUK_USE_AUGMENT_ERROR_CREATE
  15998. noblame_fileline = err_code & DUK_ERRCODE_FLAG_NOBLAME_FILELINE;
  15999. #endif
  16000. err_code = err_code & (~DUK_ERRCODE_FLAG_NOBLAME_FILELINE);
  16001. /* error gets its 'name' from the prototype */
  16002. proto = duk_error_prototype_from_code(thr, err_code);
  16003. ret = duk_push_object_helper_proto(ctx,
  16004. DUK_HOBJECT_FLAG_EXTENSIBLE |
  16005. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_ERROR),
  16006. proto);
  16007. /* ... and its 'message' from an instance property */
  16008. if (fmt) {
  16009. duk_push_vsprintf(ctx, fmt, ap);
  16010. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_MESSAGE, DUK_PROPDESC_FLAGS_WC);
  16011. } else {
  16012. /* If no explicit message given, put error code into message field
  16013. * (as a number). This is not fully in keeping with the Ecmascript
  16014. * error model because messages are supposed to be strings (Error
  16015. * constructors use ToString() on their argument). However, it's
  16016. * probably more useful than having a separate 'code' property.
  16017. */
  16018. duk_push_int(ctx, err_code);
  16019. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_MESSAGE, DUK_PROPDESC_FLAGS_WC);
  16020. }
  16021. #if 0
  16022. /* Disabled for now, not sure this is a useful property */
  16023. duk_push_int(ctx, err_code);
  16024. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_CODE, DUK_PROPDESC_FLAGS_WC);
  16025. #endif
  16026. /* Creation time error augmentation */
  16027. #ifdef DUK_USE_AUGMENT_ERROR_CREATE
  16028. /* filename may be NULL in which case file/line is not recorded */
  16029. duk_err_augment_error_create(thr, thr, filename, line, noblame_fileline); /* may throw an error */
  16030. #endif
  16031. return ret;
  16032. }
  16033. DUK_EXTERNAL duk_idx_t duk_push_error_object_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, ...) {
  16034. va_list ap;
  16035. duk_idx_t ret;
  16036. va_start(ap, fmt);
  16037. ret = duk_push_error_object_va_raw(ctx, err_code, filename, line, fmt, ap);
  16038. va_end(ap);
  16039. return ret;
  16040. }
  16041. #if !defined(DUK_USE_VARIADIC_MACROS)
  16042. DUK_EXTERNAL duk_idx_t duk_push_error_object_stash(duk_context *ctx, duk_errcode_t err_code, const char *fmt, ...) {
  16043. const char *filename = duk_api_global_filename;
  16044. duk_int_t line = duk_api_global_line;
  16045. va_list ap;
  16046. duk_idx_t ret;
  16047. duk_api_global_filename = NULL;
  16048. duk_api_global_line = 0;
  16049. va_start(ap, fmt);
  16050. ret = duk_push_error_object_va_raw(ctx, err_code, filename, line, fmt, ap);
  16051. va_end(ap);
  16052. return ret;
  16053. }
  16054. #endif /* DUK_USE_VARIADIC_MACROS */
  16055. DUK_EXTERNAL void *duk_push_buffer_raw(duk_context *ctx, duk_size_t size, duk_small_uint_t flags) {
  16056. duk_hthread *thr = (duk_hthread *) ctx;
  16057. duk_tval *tv_slot;
  16058. duk_hbuffer *h;
  16059. DUK_ASSERT(ctx != NULL);
  16060. /* check stack first */
  16061. if (thr->valstack_top >= thr->valstack_end) {
  16062. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_PUSH_BEYOND_ALLOC_STACK);
  16063. }
  16064. /* Check for maximum buffer length. */
  16065. if (size > DUK_HBUFFER_MAX_BYTELEN) {
  16066. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_BUFFER_TOO_LONG);
  16067. }
  16068. h = duk_hbuffer_alloc(thr->heap, size, flags);
  16069. if (!h) {
  16070. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_BUFFER_ALLOC_FAILED);
  16071. }
  16072. tv_slot = thr->valstack_top;
  16073. DUK_TVAL_SET_BUFFER(tv_slot, h);
  16074. DUK_HBUFFER_INCREF(thr, h);
  16075. thr->valstack_top++;
  16076. return DUK_HBUFFER_GET_DATA_PTR(thr->heap, h);
  16077. }
  16078. DUK_EXTERNAL duk_idx_t duk_push_heapptr(duk_context *ctx, void *ptr) {
  16079. duk_hthread *thr = (duk_hthread *) ctx;
  16080. duk_idx_t ret;
  16081. DUK_ASSERT(ctx != NULL);
  16082. ret = (duk_idx_t) (thr->valstack_top - thr->valstack_bottom);
  16083. if (ptr == NULL) {
  16084. goto push_undefined;
  16085. }
  16086. switch (DUK_HEAPHDR_GET_TYPE((duk_heaphdr *) ptr)) {
  16087. case DUK_HTYPE_STRING:
  16088. duk_push_hstring(ctx, (duk_hstring *) ptr);
  16089. break;
  16090. case DUK_HTYPE_OBJECT:
  16091. duk_push_hobject(ctx, (duk_hobject *) ptr);
  16092. break;
  16093. case DUK_HTYPE_BUFFER:
  16094. duk_push_hbuffer(ctx, (duk_hbuffer *) ptr);
  16095. break;
  16096. default:
  16097. goto push_undefined;
  16098. }
  16099. return ret;
  16100. push_undefined:
  16101. duk_push_undefined(ctx);
  16102. return ret;
  16103. }
  16104. DUK_INTERNAL duk_idx_t duk_push_object_internal(duk_context *ctx) {
  16105. return duk_push_object_helper(ctx,
  16106. DUK_HOBJECT_FLAG_EXTENSIBLE |
  16107. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT),
  16108. -1); /* no prototype */
  16109. }
  16110. DUK_INTERNAL void duk_push_hstring(duk_context *ctx, duk_hstring *h) {
  16111. duk_tval tv;
  16112. DUK_ASSERT(ctx != NULL);
  16113. DUK_ASSERT(h != NULL);
  16114. DUK_TVAL_SET_STRING(&tv, h);
  16115. duk_push_tval(ctx, &tv);
  16116. }
  16117. DUK_INTERNAL void duk_push_hstring_stridx(duk_context *ctx, duk_small_int_t stridx) {
  16118. duk_hthread *thr = (duk_hthread *) ctx;
  16119. DUK_ASSERT(stridx >= 0 && stridx < DUK_HEAP_NUM_STRINGS);
  16120. duk_push_hstring(ctx, DUK_HTHREAD_GET_STRING(thr, stridx));
  16121. }
  16122. DUK_INTERNAL void duk_push_hobject(duk_context *ctx, duk_hobject *h) {
  16123. duk_tval tv;
  16124. DUK_ASSERT(ctx != NULL);
  16125. DUK_ASSERT(h != NULL);
  16126. DUK_TVAL_SET_OBJECT(&tv, h);
  16127. duk_push_tval(ctx, &tv);
  16128. }
  16129. DUK_INTERNAL void duk_push_hbuffer(duk_context *ctx, duk_hbuffer *h) {
  16130. duk_tval tv;
  16131. DUK_ASSERT(ctx != NULL);
  16132. DUK_ASSERT(h != NULL);
  16133. DUK_TVAL_SET_BUFFER(&tv, h);
  16134. duk_push_tval(ctx, &tv);
  16135. }
  16136. DUK_INTERNAL void duk_push_hobject_bidx(duk_context *ctx, duk_small_int_t builtin_idx) {
  16137. duk_hthread *thr = (duk_hthread *) ctx;
  16138. DUK_ASSERT(ctx != NULL);
  16139. DUK_ASSERT(thr != NULL);
  16140. DUK_ASSERT(builtin_idx >= 0 && builtin_idx < DUK_NUM_BUILTINS);
  16141. DUK_ASSERT(thr->builtins[builtin_idx] != NULL);
  16142. duk_push_hobject(ctx, thr->builtins[builtin_idx]);
  16143. }
  16144. /*
  16145. * Poppers
  16146. */
  16147. DUK_EXTERNAL void duk_pop_n(duk_context *ctx, duk_idx_t count) {
  16148. duk_hthread *thr = (duk_hthread *) ctx;
  16149. DUK_ASSERT(ctx != NULL);
  16150. if (count < 0) {
  16151. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_COUNT);
  16152. return;
  16153. }
  16154. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  16155. if ((duk_size_t) (thr->valstack_top - thr->valstack_bottom) < (duk_size_t) count) {
  16156. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_POP_TOO_MANY);
  16157. }
  16158. /*
  16159. * Must be very careful here, every DECREF may cause reallocation
  16160. * of our valstack.
  16161. */
  16162. /* XXX: inlined DECREF macro would be nice here: no NULL check,
  16163. * refzero queueing but no refzero algorithm run (= no pointer
  16164. * instability), inline code.
  16165. */
  16166. #ifdef DUK_USE_REFERENCE_COUNTING
  16167. while (count > 0) {
  16168. duk_tval tv_tmp;
  16169. duk_tval *tv;
  16170. tv = --thr->valstack_top; /* tv points to element just below prev top */
  16171. DUK_ASSERT(tv >= thr->valstack_bottom);
  16172. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  16173. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  16174. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  16175. count--;
  16176. }
  16177. #else
  16178. while (count > 0) {
  16179. duk_tval *tv;
  16180. tv = --thr->valstack_top;
  16181. DUK_ASSERT(tv >= thr->valstack_bottom);
  16182. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  16183. count--;
  16184. }
  16185. #endif
  16186. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  16187. }
  16188. DUK_EXTERNAL void duk_pop(duk_context *ctx) {
  16189. duk_pop_n(ctx, 1);
  16190. }
  16191. DUK_EXTERNAL void duk_pop_2(duk_context *ctx) {
  16192. duk_pop_n(ctx, 2);
  16193. }
  16194. DUK_EXTERNAL void duk_pop_3(duk_context *ctx) {
  16195. duk_pop_n(ctx, 3);
  16196. }
  16197. /*
  16198. * Error throwing
  16199. */
  16200. DUK_EXTERNAL void duk_throw(duk_context *ctx) {
  16201. duk_hthread *thr = (duk_hthread *) ctx;
  16202. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  16203. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  16204. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  16205. if (thr->valstack_top == thr->valstack_bottom) {
  16206. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  16207. }
  16208. /* Errors are augmented when they are created, not when they are
  16209. * thrown or re-thrown. The current error handler, however, runs
  16210. * just before an error is thrown.
  16211. */
  16212. #if defined(DUK_USE_AUGMENT_ERROR_THROW)
  16213. DUK_DDD(DUK_DDDPRINT("THROW ERROR (API): %!dT (before throw augment)", (duk_tval *) duk_get_tval(ctx, -1)));
  16214. duk_err_augment_error_throw(thr);
  16215. #endif
  16216. DUK_DDD(DUK_DDDPRINT("THROW ERROR (API): %!dT (after throw augment)", (duk_tval *) duk_get_tval(ctx, -1)));
  16217. duk_err_setup_heap_ljstate(thr, DUK_LJ_TYPE_THROW);
  16218. /* thr->heap->lj.jmpbuf_ptr is checked by duk_err_longjmp() so we don't
  16219. * need to check that here. If the value is NULL, a panic occurs because
  16220. * we can't return.
  16221. */
  16222. duk_err_longjmp(thr);
  16223. DUK_UNREACHABLE();
  16224. }
  16225. DUK_EXTERNAL void duk_fatal(duk_context *ctx, duk_errcode_t err_code, const char *err_msg) {
  16226. duk_hthread *thr = (duk_hthread *) ctx;
  16227. DUK_ASSERT(ctx != NULL);
  16228. DUK_ASSERT(thr != NULL);
  16229. DUK_ASSERT(thr->heap != NULL);
  16230. DUK_ASSERT(thr->heap->fatal_func != NULL);
  16231. DUK_D(DUK_DPRINT("fatal error occurred, code %ld, message %s",
  16232. (long) err_code, (const char *) err_msg));
  16233. /* fatal_func should be noreturn, but noreturn declarations on function
  16234. * pointers has a very spotty support apparently so it's not currently
  16235. * done.
  16236. */
  16237. thr->heap->fatal_func(ctx, err_code, err_msg);
  16238. DUK_PANIC(DUK_ERR_API_ERROR, "fatal handler returned");
  16239. }
  16240. DUK_EXTERNAL void duk_error_va_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, va_list ap) {
  16241. duk_push_error_object_va_raw(ctx, err_code, filename, line, fmt, ap);
  16242. duk_throw(ctx);
  16243. }
  16244. DUK_EXTERNAL void duk_error_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *fmt, ...) {
  16245. va_list ap;
  16246. va_start(ap, fmt);
  16247. duk_push_error_object_va_raw(ctx, err_code, filename, line, fmt, ap);
  16248. va_end(ap);
  16249. duk_throw(ctx);
  16250. }
  16251. #if !defined(DUK_USE_VARIADIC_MACROS)
  16252. DUK_EXTERNAL void duk_error_stash(duk_context *ctx, duk_errcode_t err_code, const char *fmt, ...) {
  16253. const char *filename;
  16254. duk_int_t line;
  16255. va_list ap;
  16256. filename = duk_api_global_filename;
  16257. line = duk_api_global_line;
  16258. duk_api_global_filename = NULL;
  16259. duk_api_global_line = 0;
  16260. va_start(ap, fmt);
  16261. duk_push_error_object_va_raw(ctx, err_code, filename, line, fmt, ap);
  16262. va_end(ap);
  16263. duk_throw(ctx);
  16264. }
  16265. #endif /* DUK_USE_VARIADIC_MACROS */
  16266. /*
  16267. * Comparison
  16268. */
  16269. DUK_EXTERNAL duk_bool_t duk_equals(duk_context *ctx, duk_idx_t index1, duk_idx_t index2) {
  16270. duk_hthread *thr = (duk_hthread *) ctx;
  16271. duk_tval *tv1, *tv2;
  16272. tv1 = duk_get_tval(ctx, index1);
  16273. if (!tv1) {
  16274. return 0;
  16275. }
  16276. tv2 = duk_get_tval(ctx, index2);
  16277. if (!tv2) {
  16278. return 0;
  16279. }
  16280. /* Coercion may be needed, the helper handles that by pushing the
  16281. * tagged values to the stack.
  16282. */
  16283. return duk_js_equals(thr, tv1, tv2);
  16284. }
  16285. DUK_EXTERNAL duk_bool_t duk_strict_equals(duk_context *ctx, duk_idx_t index1, duk_idx_t index2) {
  16286. duk_tval *tv1, *tv2;
  16287. tv1 = duk_get_tval(ctx, index1);
  16288. if (!tv1) {
  16289. return 0;
  16290. }
  16291. tv2 = duk_get_tval(ctx, index2);
  16292. if (!tv2) {
  16293. return 0;
  16294. }
  16295. /* No coercions or other side effects, so safe */
  16296. return duk_js_strict_equals(tv1, tv2);
  16297. }
  16298. /*
  16299. * Lightfunc
  16300. */
  16301. DUK_INTERNAL void duk_push_lightfunc_name(duk_context *ctx, duk_tval *tv) {
  16302. duk_c_function func;
  16303. DUK_ASSERT(DUK_TVAL_IS_LIGHTFUNC(tv));
  16304. /* Lightfunc name, includes Duktape/C native function pointer, which
  16305. * can often be used to locate the function from a symbol table.
  16306. * The name also includes the 16-bit duk_tval flags field because it
  16307. * includes the magic value. Because a single native function often
  16308. * provides different functionality depending on the magic value, it
  16309. * seems reasonably to include it in the name.
  16310. *
  16311. * On the other hand, a complicated name increases string table
  16312. * pressure in low memory environments (but only when function name
  16313. * is accessed).
  16314. */
  16315. func = DUK_TVAL_GET_LIGHTFUNC_FUNCPTR(tv);
  16316. duk_push_sprintf(ctx, "light_");
  16317. duk_push_string_funcptr(ctx, (duk_uint8_t *) &func, sizeof(func));
  16318. duk_push_sprintf(ctx, "_%04x", (unsigned int) DUK_TVAL_GET_LIGHTFUNC_FLAGS(tv));
  16319. duk_concat(ctx, 3);
  16320. }
  16321. DUK_INTERNAL void duk_push_lightfunc_tostring(duk_context *ctx, duk_tval *tv) {
  16322. DUK_ASSERT(DUK_TVAL_IS_LIGHTFUNC(tv));
  16323. duk_push_string(ctx, "function ");
  16324. duk_push_lightfunc_name(ctx, tv);
  16325. duk_push_string(ctx, "() {/* light */}");
  16326. duk_concat(ctx, 3);
  16327. }
  16328. /*
  16329. * Function pointers
  16330. *
  16331. * Printing function pointers is non-portable, so we do that by hex printing
  16332. * bytes from memory.
  16333. */
  16334. DUK_INTERNAL void duk_push_string_funcptr(duk_context *ctx, duk_uint8_t *ptr, duk_size_t sz) {
  16335. duk_uint8_t buf[32 * 2];
  16336. duk_uint8_t *p, *q;
  16337. duk_small_uint_t i;
  16338. duk_small_uint_t t;
  16339. DUK_ASSERT(sz <= 32); /* sanity limit for function pointer size */
  16340. p = buf;
  16341. #if defined(DUK_USE_INTEGER_LE)
  16342. q = ptr + sz;
  16343. #else
  16344. q = ptr;
  16345. #endif
  16346. for (i = 0; i < sz; i++) {
  16347. #if defined(DUK_USE_INTEGER_LE)
  16348. t = *(--q);
  16349. #else
  16350. t = *(q++);
  16351. #endif
  16352. *p++ = duk_lc_digits[t >> 4];
  16353. *p++ = duk_lc_digits[t & 0x0f];
  16354. }
  16355. duk_push_lstring(ctx, (const char *) buf, sz * 2);
  16356. }
  16357. #undef DUK__CHECK_SPACE
  16358. #line 1 "duk_api_string.c"
  16359. /*
  16360. * String manipulation
  16361. */
  16362. /* include removed: duk_internal.h */
  16363. DUK_LOCAL void duk__concat_and_join_helper(duk_context *ctx, duk_idx_t count_in, duk_bool_t is_join) {
  16364. duk_hthread *thr = (duk_hthread *) ctx;
  16365. duk_uint_t count;
  16366. duk_uint_t i;
  16367. duk_size_t idx;
  16368. duk_size_t len;
  16369. duk_hstring *h;
  16370. duk_uint8_t *buf;
  16371. DUK_ASSERT(ctx != NULL);
  16372. if (DUK_UNLIKELY(count_in <= 0)) {
  16373. if (count_in < 0) {
  16374. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_COUNT);
  16375. return;
  16376. }
  16377. DUK_ASSERT(count_in == 0);
  16378. duk_push_hstring_stridx(ctx, DUK_STRIDX_EMPTY_STRING);
  16379. return;
  16380. }
  16381. count = (duk_uint_t) count_in;
  16382. if (is_join) {
  16383. duk_size_t t1, t2, limit;
  16384. h = duk_to_hstring(ctx, -((duk_idx_t) count) - 1);
  16385. DUK_ASSERT(h != NULL);
  16386. /* A bit tricky overflow test, see doc/code-issues.txt. */
  16387. t1 = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h);
  16388. t2 = (duk_size_t) (count - 1);
  16389. limit = (duk_size_t) DUK_HSTRING_MAX_BYTELEN;
  16390. if (DUK_UNLIKELY(t2 != 0 && t1 > limit / t2)) {
  16391. /* Combined size of separators already overflows */
  16392. goto error_overflow;
  16393. }
  16394. len = (duk_size_t) (t1 * t2);
  16395. } else {
  16396. len = (duk_size_t) 0;
  16397. }
  16398. for (i = count; i >= 1; i--) {
  16399. duk_size_t new_len;
  16400. duk_to_string(ctx, -((duk_idx_t) i));
  16401. h = duk_require_hstring(ctx, -((duk_idx_t) i));
  16402. new_len = len + (duk_size_t) DUK_HSTRING_GET_BYTELEN(h);
  16403. /* Impose a string maximum length, need to handle overflow
  16404. * correctly.
  16405. */
  16406. if (new_len < len || /* wrapped */
  16407. new_len > (duk_size_t) DUK_HSTRING_MAX_BYTELEN) {
  16408. goto error_overflow;
  16409. }
  16410. len = new_len;
  16411. }
  16412. DUK_DDD(DUK_DDDPRINT("join/concat %lu strings, total length %lu bytes",
  16413. (unsigned long) count, (unsigned long) len));
  16414. /* use stack allocated buffer to ensure reachability in errors (e.g. intern error) */
  16415. buf = (duk_uint8_t *) duk_push_fixed_buffer(ctx, len);
  16416. DUK_ASSERT(buf != NULL);
  16417. /* [... (sep) str1 str2 ... strN buf] */
  16418. idx = 0;
  16419. for (i = count; i >= 1; i--) {
  16420. if (is_join && i != count) {
  16421. h = duk_require_hstring(ctx, -((duk_idx_t) count) - 2); /* extra -1 for buffer */
  16422. DUK_MEMCPY(buf + idx, DUK_HSTRING_GET_DATA(h), DUK_HSTRING_GET_BYTELEN(h));
  16423. idx += DUK_HSTRING_GET_BYTELEN(h);
  16424. }
  16425. h = duk_require_hstring(ctx, -((duk_idx_t) i) - 1); /* extra -1 for buffer */
  16426. DUK_MEMCPY(buf + idx, DUK_HSTRING_GET_DATA(h), DUK_HSTRING_GET_BYTELEN(h));
  16427. idx += DUK_HSTRING_GET_BYTELEN(h);
  16428. }
  16429. DUK_ASSERT(idx == len);
  16430. /* [... (sep) str1 str2 ... strN buf] */
  16431. /* get rid of the strings early to minimize memory use before intern */
  16432. if (is_join) {
  16433. duk_replace(ctx, -((duk_idx_t) count) - 2); /* overwrite sep */
  16434. duk_pop_n(ctx, count);
  16435. } else {
  16436. duk_replace(ctx, -((duk_idx_t) count) - 1); /* overwrite str1 */
  16437. duk_pop_n(ctx, count-1);
  16438. }
  16439. /* [... buf] */
  16440. (void) duk_to_string(ctx, -1);
  16441. /* [... res] */
  16442. return;
  16443. error_overflow:
  16444. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_CONCAT_RESULT_TOO_LONG);
  16445. }
  16446. DUK_EXTERNAL void duk_concat(duk_context *ctx, duk_idx_t count) {
  16447. duk__concat_and_join_helper(ctx, count, 0 /*is_join*/);
  16448. }
  16449. DUK_EXTERNAL void duk_join(duk_context *ctx, duk_idx_t count) {
  16450. duk__concat_and_join_helper(ctx, count, 1 /*is_join*/);
  16451. }
  16452. /* XXX: could map/decode be unified with duk_unicode_support.c code?
  16453. * Case conversion needs also the character surroundings though.
  16454. */
  16455. DUK_EXTERNAL void duk_decode_string(duk_context *ctx, duk_idx_t index, duk_decode_char_function callback, void *udata) {
  16456. duk_hthread *thr = (duk_hthread *) ctx;
  16457. duk_hstring *h_input;
  16458. const duk_uint8_t *p, *p_start, *p_end;
  16459. duk_codepoint_t cp;
  16460. h_input = duk_require_hstring(ctx, index);
  16461. DUK_ASSERT(h_input != NULL);
  16462. p_start = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h_input);
  16463. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_input);
  16464. p = p_start;
  16465. for (;;) {
  16466. if (p >= p_end) {
  16467. break;
  16468. }
  16469. cp = (int) duk_unicode_decode_xutf8_checked(thr, &p, p_start, p_end);
  16470. callback(udata, cp);
  16471. }
  16472. }
  16473. DUK_EXTERNAL void duk_map_string(duk_context *ctx, duk_idx_t index, duk_map_char_function callback, void *udata) {
  16474. duk_hthread *thr = (duk_hthread *) ctx;
  16475. duk_hstring *h_input;
  16476. duk_hbuffer_dynamic *h_buf;
  16477. const duk_uint8_t *p, *p_start, *p_end;
  16478. duk_codepoint_t cp;
  16479. index = duk_normalize_index(ctx, index);
  16480. h_input = duk_require_hstring(ctx, index);
  16481. DUK_ASSERT(h_input != NULL);
  16482. /* XXX: should init with a spare of at least h_input->blen? */
  16483. duk_push_dynamic_buffer(ctx, 0);
  16484. h_buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  16485. DUK_ASSERT(h_buf != NULL);
  16486. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(h_buf));
  16487. p_start = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h_input);
  16488. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_input);
  16489. p = p_start;
  16490. for (;;) {
  16491. if (p >= p_end) {
  16492. break;
  16493. }
  16494. cp = (int) duk_unicode_decode_xutf8_checked(thr, &p, p_start, p_end);
  16495. cp = callback(udata, cp);
  16496. duk_hbuffer_append_xutf8(thr, h_buf, cp);
  16497. }
  16498. duk_to_string(ctx, -1); /* invalidates h_buf pointer */
  16499. duk_replace(ctx, index);
  16500. }
  16501. DUK_EXTERNAL void duk_substring(duk_context *ctx, duk_idx_t index, duk_size_t start_offset, duk_size_t end_offset) {
  16502. duk_hthread *thr = (duk_hthread *) ctx;
  16503. duk_hstring *h;
  16504. duk_hstring *res;
  16505. duk_size_t start_byte_offset;
  16506. duk_size_t end_byte_offset;
  16507. DUK_ASSERT(ctx != NULL);
  16508. index = duk_require_normalize_index(ctx, index);
  16509. h = duk_require_hstring(ctx, index);
  16510. DUK_ASSERT(h != NULL);
  16511. if (end_offset >= DUK_HSTRING_GET_CHARLEN(h)) {
  16512. end_offset = DUK_HSTRING_GET_CHARLEN(h);
  16513. }
  16514. if (start_offset > end_offset) {
  16515. start_offset = end_offset;
  16516. }
  16517. DUK_ASSERT_DISABLE(start_offset >= 0);
  16518. DUK_ASSERT(start_offset <= end_offset && start_offset <= DUK_HSTRING_GET_CHARLEN(h));
  16519. DUK_ASSERT_DISABLE(end_offset >= 0);
  16520. DUK_ASSERT(end_offset >= start_offset && end_offset <= DUK_HSTRING_GET_CHARLEN(h));
  16521. /* guaranteed by string limits */
  16522. DUK_ASSERT(start_offset <= DUK_UINT32_MAX);
  16523. DUK_ASSERT(end_offset <= DUK_UINT32_MAX);
  16524. start_byte_offset = (duk_size_t) duk_heap_strcache_offset_char2byte(thr, h, (duk_uint_fast32_t) start_offset);
  16525. end_byte_offset = (duk_size_t) duk_heap_strcache_offset_char2byte(thr, h, (duk_uint_fast32_t) end_offset);
  16526. DUK_ASSERT(end_byte_offset >= start_byte_offset);
  16527. DUK_ASSERT(end_byte_offset - start_byte_offset <= DUK_UINT32_MAX); /* guaranteed by string limits */
  16528. /* no size check is necessary */
  16529. res = duk_heap_string_intern_checked(thr,
  16530. DUK_HSTRING_GET_DATA(h) + start_byte_offset,
  16531. (duk_uint32_t) (end_byte_offset - start_byte_offset));
  16532. duk_push_hstring(ctx, res);
  16533. duk_replace(ctx, index);
  16534. }
  16535. /* XXX: this is quite clunky. Add Unicode helpers to scan backwards and
  16536. * forwards with a callback to process codepoints?
  16537. */
  16538. DUK_EXTERNAL void duk_trim(duk_context *ctx, duk_idx_t index) {
  16539. duk_hthread *thr = (duk_hthread *) ctx;
  16540. duk_hstring *h;
  16541. const duk_uint8_t *p, *p_start, *p_end, *p_tmp1, *p_tmp2; /* pointers for scanning */
  16542. const duk_uint8_t *q_start, *q_end; /* start (incl) and end (excl) of trimmed part */
  16543. duk_codepoint_t cp;
  16544. index = duk_require_normalize_index(ctx, index);
  16545. h = duk_require_hstring(ctx, index);
  16546. DUK_ASSERT(h != NULL);
  16547. p_start = DUK_HSTRING_GET_DATA(h);
  16548. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h);
  16549. p = p_start;
  16550. while (p < p_end) {
  16551. p_tmp1 = p;
  16552. cp = (duk_codepoint_t) duk_unicode_decode_xutf8_checked(thr, &p_tmp1, p_start, p_end);
  16553. if (!(duk_unicode_is_whitespace(cp) || duk_unicode_is_line_terminator(cp))) {
  16554. break;
  16555. }
  16556. p = p_tmp1;
  16557. }
  16558. q_start = p;
  16559. if (p == p_end) {
  16560. /* entire string is whitespace */
  16561. q_end = p;
  16562. goto scan_done;
  16563. }
  16564. p = p_end;
  16565. while (p > p_start) {
  16566. p_tmp1 = p;
  16567. while (p > p_start) {
  16568. p--;
  16569. if (((*p) & 0xc0) != 0x80) {
  16570. break;
  16571. }
  16572. }
  16573. p_tmp2 = p;
  16574. cp = (duk_codepoint_t) duk_unicode_decode_xutf8_checked(thr, &p_tmp2, p_start, p_end);
  16575. if (!(duk_unicode_is_whitespace(cp) || duk_unicode_is_line_terminator(cp))) {
  16576. p = p_tmp1;
  16577. break;
  16578. }
  16579. }
  16580. q_end = p;
  16581. scan_done:
  16582. /* This may happen when forward and backward scanning disagree
  16583. * (possible for non-extended-UTF-8 strings).
  16584. */
  16585. if (q_end < q_start) {
  16586. q_end = q_start;
  16587. }
  16588. DUK_ASSERT(q_start >= p_start && q_start <= p_end);
  16589. DUK_ASSERT(q_end >= p_start && q_end <= p_end);
  16590. DUK_ASSERT(q_end >= q_start);
  16591. DUK_DDD(DUK_DDDPRINT("trim: p_start=%p, p_end=%p, q_start=%p, q_end=%p",
  16592. (void *) p_start, (void *) p_end, (void *) q_start, (void *) q_end));
  16593. if (q_start == p_start && q_end == p_end) {
  16594. DUK_DDD(DUK_DDDPRINT("nothing was trimmed: avoid interning (hashing etc)"));
  16595. return;
  16596. }
  16597. duk_push_lstring(ctx, (const char *) q_start, (duk_size_t) (q_end - q_start));
  16598. duk_replace(ctx, index);
  16599. }
  16600. DUK_EXTERNAL duk_codepoint_t duk_char_code_at(duk_context *ctx, duk_idx_t index, duk_size_t char_offset) {
  16601. duk_hthread *thr = (duk_hthread *) ctx;
  16602. duk_hstring *h;
  16603. duk_ucodepoint_t cp;
  16604. h = duk_require_hstring(ctx, index);
  16605. DUK_ASSERT(h != NULL);
  16606. DUK_ASSERT_DISABLE(char_offset >= 0); /* always true, arg is unsigned */
  16607. if (char_offset >= DUK_HSTRING_GET_CHARLEN(h)) {
  16608. return 0;
  16609. }
  16610. DUK_ASSERT(char_offset <= DUK_UINT_MAX); /* guaranteed by string limits */
  16611. cp = duk_hstring_char_code_at_raw(thr, h, (duk_uint_t) char_offset);
  16612. return (duk_codepoint_t) cp;
  16613. }
  16614. #line 1 "duk_api_var.c"
  16615. /*
  16616. * Variable access
  16617. */
  16618. /* include removed: duk_internal.h */
  16619. DUK_EXTERNAL void duk_get_var(duk_context *ctx) {
  16620. duk_hthread *thr = (duk_hthread *) ctx;
  16621. duk_activation *act;
  16622. duk_hstring *h_varname;
  16623. duk_small_int_t throw_flag = 1; /* always throw ReferenceError for unresolvable */
  16624. DUK_ASSERT(ctx != NULL);
  16625. h_varname = duk_require_hstring(ctx, -1); /* XXX: tostring? */
  16626. DUK_ASSERT(h_varname != NULL);
  16627. act = duk_hthread_get_current_activation(thr);
  16628. if (act) {
  16629. (void) duk_js_getvar_activation(thr, act, h_varname, throw_flag); /* -> [ ... varname val this ] */
  16630. } else {
  16631. /* Outside any activation -> look up from global. */
  16632. DUK_ASSERT(thr->builtins[DUK_BIDX_GLOBAL_ENV] != NULL);
  16633. (void) duk_js_getvar_envrec(thr, thr->builtins[DUK_BIDX_GLOBAL_ENV], h_varname, throw_flag);
  16634. }
  16635. /* [ ... varname val this ] (because throw_flag == 1, always resolved) */
  16636. duk_pop(ctx);
  16637. duk_remove(ctx, -2);
  16638. /* [ ... val ] */
  16639. /* Return value would be pointless: because throw_flag==1, we always
  16640. * throw if the identifier doesn't resolve.
  16641. */
  16642. return;
  16643. }
  16644. DUK_EXTERNAL void duk_put_var(duk_context *ctx) {
  16645. duk_hthread *thr = (duk_hthread *) ctx;
  16646. duk_activation *act;
  16647. duk_hstring *h_varname;
  16648. duk_tval *tv_val;
  16649. duk_small_int_t throw_flag;
  16650. DUK_ASSERT(ctx != NULL);
  16651. h_varname = duk_require_hstring(ctx, -2); /* XXX: tostring? */
  16652. DUK_ASSERT(h_varname != NULL);
  16653. tv_val = duk_require_tval(ctx, -1);
  16654. throw_flag = duk_is_strict_call(ctx);
  16655. act = duk_hthread_get_current_activation(thr);
  16656. if (act) {
  16657. duk_js_putvar_activation(thr, act, h_varname, tv_val, throw_flag); /* -> [ ... varname val this ] */
  16658. } else {
  16659. /* Outside any activation -> put to global. */
  16660. DUK_ASSERT(thr->builtins[DUK_BIDX_GLOBAL_ENV] != NULL);
  16661. duk_js_putvar_envrec(thr, thr->builtins[DUK_BIDX_GLOBAL_ENV], h_varname, tv_val, throw_flag);
  16662. }
  16663. /* [ ... varname val ] */
  16664. duk_pop_2(ctx);
  16665. /* [ ... ] */
  16666. return;
  16667. }
  16668. DUK_EXTERNAL duk_bool_t duk_del_var(duk_context *ctx) {
  16669. DUK_ERROR((duk_hthread *) ctx, DUK_ERR_UNIMPLEMENTED_ERROR, DUK_STR_UNIMPLEMENTED);
  16670. return 0;
  16671. }
  16672. DUK_EXTERNAL duk_bool_t duk_has_var(duk_context *ctx) {
  16673. DUK_ERROR((duk_hthread *) ctx, DUK_ERR_UNIMPLEMENTED_ERROR, DUK_STR_UNIMPLEMENTED);
  16674. return 0;
  16675. }
  16676. #line 1 "duk_bi_array.c"
  16677. /*
  16678. * Array built-ins
  16679. *
  16680. * Note that most Array built-ins are intentionally generic and work even
  16681. * when the 'this' binding is not an Array instance. To ensure this,
  16682. * Array algorithms do not assume "magical" Array behavior for the "length"
  16683. * property, for instance.
  16684. *
  16685. * XXX: the "Throw" flag should be set for (almost?) all [[Put]] and
  16686. * [[Delete]] operations, but it's currently false throughout. Go through
  16687. * all put/delete cases and check throw flag use. Need a new API primitive
  16688. * which allows throws flag to be specified.
  16689. *
  16690. * XXX: array lengths above 2G won't work reliably. There are many places
  16691. * where one needs a full signed 32-bit range ([-0xffffffff, 0xffffffff],
  16692. * i.e. -33- bits). Although array 'length' cannot be written to be outside
  16693. * the unsigned 32-bit range (E5.1 Section 15.4.5.1 throws a RangeError if so)
  16694. * some intermediate values may be above 0xffffffff and this may not be always
  16695. * correctly handled now (duk_uint32_t is not enough for all algorithms).
  16696. *
  16697. * For instance, push() can legitimately write entries beyond length 0xffffffff
  16698. * and cause a RangeError only at the end. To do this properly, the current
  16699. * push() implementation tracks the array index using a 'double' instead of a
  16700. * duk_uint32_t (which is somewhat awkward). See test-bi-array-push-maxlen.js.
  16701. *
  16702. * On using "put" vs. "def" prop
  16703. * =============================
  16704. *
  16705. * Code below must be careful to use the appropriate primitive as it matters
  16706. * for compliance. When using "put" there may be inherited properties in
  16707. * Array.prototype which cause side effects when values are written. When
  16708. * using "define" there are no such side effects, and many test262 test cases
  16709. * check for this (for real world code, such side effects are very rare).
  16710. * Both "put" and "define" are used in the E5.1 specification; as a rule,
  16711. * "put" is used when modifying an existing array (or a non-array 'this'
  16712. * binding) and "define" for setting values into a fresh result array.
  16713. *
  16714. * Also note that Array instance 'length' should be writable, but not
  16715. * enumerable and definitely not configurable: even Duktape code internally
  16716. * assumes that an Array instance will always have a 'length' property.
  16717. * Preventing deletion of the property is critical.
  16718. */
  16719. /* include removed: duk_internal.h */
  16720. /* Perform an intermediate join when this many elements have been pushed
  16721. * on the value stack.
  16722. */
  16723. #define DUK__ARRAY_MID_JOIN_LIMIT 4096
  16724. /* Shared entry code for many Array built-ins. Note that length is left
  16725. * on stack (it could be popped, but that's not necessary).
  16726. */
  16727. DUK_LOCAL duk_uint32_t duk__push_this_obj_len_u32(duk_context *ctx) {
  16728. duk_uint32_t len;
  16729. (void) duk_push_this_coercible_to_object(ctx);
  16730. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_LENGTH);
  16731. len = duk_to_uint32(ctx, -1);
  16732. /* -> [ ... ToObject(this) ToUint32(length) ] */
  16733. return len;
  16734. }
  16735. DUK_LOCAL duk_uint32_t duk__push_this_obj_len_u32_limited(duk_context *ctx) {
  16736. /* Range limited to [0, 0x7fffffff] range, i.e. range that can be
  16737. * represented with duk_int32_t. Use this when the method doesn't
  16738. * handle the full 32-bit unsigned range correctly.
  16739. */
  16740. duk_uint32_t ret = duk__push_this_obj_len_u32(ctx);
  16741. if (DUK_UNLIKELY(ret >= 0x80000000UL)) {
  16742. DUK_ERROR((duk_hthread *) ctx, DUK_ERR_INTERNAL_ERROR, DUK_STR_ARRAY_LENGTH_OVER_2G);
  16743. }
  16744. return ret;
  16745. }
  16746. /*
  16747. * Constructor
  16748. */
  16749. DUK_INTERNAL duk_ret_t duk_bi_array_constructor(duk_context *ctx) {
  16750. duk_idx_t nargs;
  16751. duk_double_t d;
  16752. duk_uint32_t len;
  16753. duk_idx_t i;
  16754. nargs = duk_get_top(ctx);
  16755. duk_push_array(ctx);
  16756. if (nargs == 1 && duk_is_number(ctx, 0)) {
  16757. /* XXX: expensive check (also shared elsewhere - so add a shared internal API call?) */
  16758. d = duk_get_number(ctx, 0);
  16759. len = duk_to_uint32(ctx, 0);
  16760. if (((duk_double_t) len) != d) {
  16761. return DUK_RET_RANGE_ERROR;
  16762. }
  16763. /* XXX: if 'len' is low, may want to ensure array part is kept:
  16764. * the caller is likely to want a dense array.
  16765. */
  16766. duk_push_u32(ctx, len);
  16767. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_W); /* [ ToUint32(len) array ToUint32(len) ] -> [ ToUint32(len) array ] */
  16768. return 1;
  16769. }
  16770. /* XXX: optimize by creating array into correct size directly, and
  16771. * operating on the array part directly; values can be memcpy()'d from
  16772. * value stack directly as long as refcounts are increased.
  16773. */
  16774. for (i = 0; i < nargs; i++) {
  16775. duk_dup(ctx, i);
  16776. duk_xdef_prop_index_wec(ctx, -2, (duk_uarridx_t) i);
  16777. }
  16778. duk_push_u32(ctx, (duk_uint32_t) nargs);
  16779. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_W);
  16780. return 1;
  16781. }
  16782. /*
  16783. * isArray()
  16784. */
  16785. DUK_INTERNAL duk_ret_t duk_bi_array_constructor_is_array(duk_context *ctx) {
  16786. duk_hobject *h;
  16787. h = duk_get_hobject_with_class(ctx, 0, DUK_HOBJECT_CLASS_ARRAY);
  16788. duk_push_boolean(ctx, (h != NULL));
  16789. return 1;
  16790. }
  16791. /*
  16792. * toString()
  16793. */
  16794. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_to_string(duk_context *ctx) {
  16795. (void) duk_push_this_coercible_to_object(ctx);
  16796. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_JOIN);
  16797. /* [ ... this func ] */
  16798. if (!duk_is_callable(ctx, -1)) {
  16799. /* Fall back to the initial (original) Object.toString(). We don't
  16800. * currently have pointers to the built-in functions, only the top
  16801. * level global objects (like "Array") so this is now done in a bit
  16802. * of a hacky manner. It would be cleaner to push the (original)
  16803. * function and use duk_call_method().
  16804. */
  16805. /* XXX: 'this' will be ToObject() coerced twice, which is incorrect
  16806. * but should have no visible side effects.
  16807. */
  16808. DUK_DDD(DUK_DDDPRINT("this.join is not callable, fall back to (original) Object.toString"));
  16809. duk_set_top(ctx, 0);
  16810. return duk_bi_object_prototype_to_string(ctx); /* has access to 'this' binding */
  16811. }
  16812. /* [ ... this func ] */
  16813. duk_insert(ctx, -2);
  16814. /* [ ... func this ] */
  16815. DUK_DDD(DUK_DDDPRINT("calling: func=%!iT, this=%!iT",
  16816. (duk_tval *) duk_get_tval(ctx, -2),
  16817. (duk_tval *) duk_get_tval(ctx, -1)));
  16818. duk_call_method(ctx, 0);
  16819. return 1;
  16820. }
  16821. /*
  16822. * concat()
  16823. */
  16824. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_concat(duk_context *ctx) {
  16825. duk_idx_t i, n;
  16826. duk_uarridx_t idx, idx_last;
  16827. duk_uarridx_t j, len;
  16828. duk_hobject *h;
  16829. /* XXX: the insert here is a bit expensive if there are a lot of items.
  16830. * It could also be special cased in the outermost for loop quite easily
  16831. * (as the element is dup()'d anyway).
  16832. */
  16833. (void) duk_push_this_coercible_to_object(ctx);
  16834. duk_insert(ctx, 0);
  16835. n = duk_get_top(ctx);
  16836. duk_push_array(ctx); /* -> [ ToObject(this) item1 ... itemN arr ] */
  16837. /* NOTE: The Array special behaviors are NOT invoked by duk_xdef_prop_index()
  16838. * (which differs from the official algorithm). If no error is thrown, this
  16839. * doesn't matter as the length is updated at the end. However, if an error
  16840. * is thrown, the length will be unset. That shouldn't matter because the
  16841. * caller won't get a reference to the intermediate value.
  16842. */
  16843. idx = 0;
  16844. idx_last = 0;
  16845. for (i = 0; i < n; i++) {
  16846. DUK_ASSERT_TOP(ctx, n + 1);
  16847. /* [ ToObject(this) item1 ... itemN arr ] */
  16848. duk_dup(ctx, i);
  16849. h = duk_get_hobject_with_class(ctx, -1, DUK_HOBJECT_CLASS_ARRAY);
  16850. if (!h) {
  16851. duk_xdef_prop_index_wec(ctx, -2, idx++);
  16852. idx_last = idx;
  16853. continue;
  16854. }
  16855. /* [ ToObject(this) item1 ... itemN arr item(i) ] */
  16856. /* XXX: an array can have length higher than 32 bits; this is not handled
  16857. * correctly now.
  16858. */
  16859. len = (duk_uarridx_t) duk_get_length(ctx, -1);
  16860. for (j = 0; j < len; j++) {
  16861. if (duk_get_prop_index(ctx, -1, j)) {
  16862. /* [ ToObject(this) item1 ... itemN arr item(i) item(i)[j] ] */
  16863. duk_xdef_prop_index_wec(ctx, -3, idx++);
  16864. idx_last = idx;
  16865. } else {
  16866. idx++;
  16867. duk_pop(ctx);
  16868. #if defined(DUK_USE_NONSTD_ARRAY_CONCAT_TRAILER)
  16869. /* According to E5.1 Section 15.4.4.4 nonexistent trailing
  16870. * elements do not affect 'length' of the result. Test262
  16871. * and other engines disagree, so update idx_last here too.
  16872. */
  16873. idx_last = idx;
  16874. #else
  16875. /* Strict standard behavior, ignore trailing elements for
  16876. * result 'length'.
  16877. */
  16878. #endif
  16879. }
  16880. }
  16881. duk_pop(ctx);
  16882. }
  16883. /* The E5.1 Section 15.4.4.4 algorithm doesn't set the length explicitly
  16884. * in the end, but because we're operating with an internal value which
  16885. * is known to be an array, this should be equivalent.
  16886. */
  16887. duk_push_uarridx(ctx, idx_last);
  16888. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_W);
  16889. DUK_ASSERT_TOP(ctx, n + 1);
  16890. return 1;
  16891. }
  16892. /*
  16893. * join(), toLocaleString()
  16894. *
  16895. * Note: checking valstack is necessary, but only in the per-element loop.
  16896. *
  16897. * Note: the trivial approach of pushing all the elements on the value stack
  16898. * and then calling duk_join() fails when the array contains a large number
  16899. * of elements. This problem can't be offloaded to duk_join() because the
  16900. * elements to join must be handled here and have special handling. Current
  16901. * approach is to do intermediate joins with very large number of elements.
  16902. * There is no fancy handling; the prefix gets re-joined multiple times.
  16903. */
  16904. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_join_shared(duk_context *ctx) {
  16905. duk_uint32_t len, count;
  16906. duk_uint32_t idx;
  16907. duk_small_int_t to_locale_string = duk_get_current_magic(ctx);
  16908. duk_idx_t valstack_required;
  16909. /* For join(), nargs is 1. For toLocaleString(), nargs is 0 and
  16910. * setting the top essentially pushes an undefined to the stack,
  16911. * thus defaulting to a comma separator.
  16912. */
  16913. duk_set_top(ctx, 1);
  16914. if (duk_is_undefined(ctx, 0)) {
  16915. duk_pop(ctx);
  16916. duk_push_hstring_stridx(ctx, DUK_STRIDX_COMMA);
  16917. } else {
  16918. duk_to_string(ctx, 0);
  16919. }
  16920. len = duk__push_this_obj_len_u32(ctx);
  16921. /* [ sep ToObject(this) len ] */
  16922. DUK_DDD(DUK_DDDPRINT("sep=%!T, this=%!T, len=%lu",
  16923. (duk_tval *) duk_get_tval(ctx, 0),
  16924. (duk_tval *) duk_get_tval(ctx, 1),
  16925. (unsigned long) len));
  16926. /* The extra (+4) is tight. */
  16927. valstack_required = (len >= DUK__ARRAY_MID_JOIN_LIMIT ?
  16928. DUK__ARRAY_MID_JOIN_LIMIT : len) + 4;
  16929. duk_require_stack(ctx, valstack_required);
  16930. duk_dup(ctx, 0);
  16931. /* [ sep ToObject(this) len sep ] */
  16932. count = 0;
  16933. idx = 0;
  16934. for (;;) {
  16935. if (count >= DUK__ARRAY_MID_JOIN_LIMIT || /* intermediate join to avoid valstack overflow */
  16936. idx >= len) { /* end of loop (careful with len==0) */
  16937. /* [ sep ToObject(this) len sep str0 ... str(count-1) ] */
  16938. DUK_DDD(DUK_DDDPRINT("mid/final join, count=%ld, idx=%ld, len=%ld",
  16939. (long) count, (long) idx, (long) len));
  16940. duk_join(ctx, (duk_idx_t) count); /* -> [ sep ToObject(this) len str ] */
  16941. duk_dup(ctx, 0); /* -> [ sep ToObject(this) len str sep ] */
  16942. duk_insert(ctx, -2); /* -> [ sep ToObject(this) len sep str ] */
  16943. count = 1;
  16944. }
  16945. if (idx >= len) {
  16946. /* if true, the stack already contains the final result */
  16947. break;
  16948. }
  16949. duk_get_prop_index(ctx, 1, (duk_uarridx_t) idx);
  16950. if (duk_is_null_or_undefined(ctx, -1)) {
  16951. duk_pop(ctx);
  16952. duk_push_hstring_stridx(ctx, DUK_STRIDX_EMPTY_STRING);
  16953. } else {
  16954. if (to_locale_string) {
  16955. duk_to_object(ctx, -1);
  16956. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_TO_LOCALE_STRING);
  16957. duk_insert(ctx, -2); /* -> [ ... toLocaleString ToObject(val) ] */
  16958. duk_call_method(ctx, 0);
  16959. duk_to_string(ctx, -1);
  16960. } else {
  16961. duk_to_string(ctx, -1);
  16962. }
  16963. }
  16964. count++;
  16965. idx++;
  16966. }
  16967. /* [ sep ToObject(this) len sep result ] */
  16968. return 1;
  16969. }
  16970. /*
  16971. * pop(), push()
  16972. */
  16973. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_pop(duk_context *ctx) {
  16974. duk_uint32_t len;
  16975. duk_uint32_t idx;
  16976. DUK_ASSERT_TOP(ctx, 0);
  16977. len = duk__push_this_obj_len_u32(ctx);
  16978. if (len == 0) {
  16979. duk_push_int(ctx, 0);
  16980. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LENGTH);
  16981. return 0;
  16982. }
  16983. idx = len - 1;
  16984. duk_get_prop_index(ctx, 0, (duk_uarridx_t) idx);
  16985. duk_del_prop_index(ctx, 0, (duk_uarridx_t) idx);
  16986. duk_push_u32(ctx, idx);
  16987. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LENGTH);
  16988. return 1;
  16989. }
  16990. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_push(duk_context *ctx) {
  16991. /* Note: 'this' is not necessarily an Array object. The push()
  16992. * algorithm is supposed to work for other kinds of objects too,
  16993. * so the algorithm has e.g. an explicit update for the 'length'
  16994. * property which is normally "magical" in arrays.
  16995. */
  16996. duk_uint32_t len;
  16997. duk_idx_t i, n;
  16998. n = duk_get_top(ctx);
  16999. len = duk__push_this_obj_len_u32(ctx);
  17000. /* [ arg1 ... argN obj length ] */
  17001. /* Technically Array.prototype.push() can create an Array with length
  17002. * longer than 2^32-1, i.e. outside the 32-bit range. The final length
  17003. * is *not* wrapped to 32 bits in the specification.
  17004. *
  17005. * This implementation tracks length with a uint32 because it's much
  17006. * more practical.
  17007. *
  17008. * See: test-bi-array-push-maxlen.js.
  17009. */
  17010. if (len + (duk_uint32_t) n < len) {
  17011. DUK_D(DUK_DPRINT("Array.prototype.push() would go beyond 32-bit length, throw"));
  17012. return DUK_RET_RANGE_ERROR;
  17013. }
  17014. for (i = 0; i < n; i++) {
  17015. duk_dup(ctx, i);
  17016. duk_put_prop_index(ctx, -3, len + i);
  17017. }
  17018. len += n;
  17019. duk_push_u32(ctx, len);
  17020. duk_dup_top(ctx);
  17021. duk_put_prop_stridx(ctx, -4, DUK_STRIDX_LENGTH);
  17022. /* [ arg1 ... argN obj length new_length ] */
  17023. return 1;
  17024. }
  17025. /*
  17026. * sort()
  17027. *
  17028. * Currently qsort with random pivot. This is now really, really slow,
  17029. * because there is no fast path for array parts.
  17030. *
  17031. * Signed indices are used because qsort() leaves and degenerate cases
  17032. * may use a negative offset.
  17033. */
  17034. DUK_LOCAL duk_small_int_t duk__array_sort_compare(duk_context *ctx, duk_int_t idx1, duk_int_t idx2) {
  17035. duk_bool_t have1, have2;
  17036. duk_bool_t undef1, undef2;
  17037. duk_small_int_t ret;
  17038. duk_idx_t idx_obj = 1; /* fixed offsets in valstack */
  17039. duk_idx_t idx_fn = 0;
  17040. duk_hstring *h1, *h2;
  17041. /* Fast exit if indices are identical. This is valid for a non-existent property,
  17042. * for an undefined value, and almost always for ToString() coerced comparison of
  17043. * arbitrary values (corner cases where this is not the case include e.g. a an
  17044. * object with varying ToString() coercion).
  17045. *
  17046. * The specification does not prohibit "caching" of values read from the array, so
  17047. * assuming equality for comparing an index with itself falls into the category of
  17048. * "caching".
  17049. *
  17050. * Also, compareFn may be inconsistent, so skipping a call to compareFn here may
  17051. * have an effect on the final result. The specification does not require any
  17052. * specific behavior for inconsistent compare functions, so again, this fast path
  17053. * is OK.
  17054. */
  17055. if (idx1 == idx2) {
  17056. DUK_DDD(DUK_DDDPRINT("duk__array_sort_compare: idx1=%ld, idx2=%ld -> indices identical, quick exit",
  17057. (long) idx1, (long) idx2));
  17058. return 0;
  17059. }
  17060. have1 = duk_get_prop_index(ctx, idx_obj, (duk_uarridx_t) idx1);
  17061. have2 = duk_get_prop_index(ctx, idx_obj, (duk_uarridx_t) idx2);
  17062. DUK_DDD(DUK_DDDPRINT("duk__array_sort_compare: idx1=%ld, idx2=%ld, have1=%ld, have2=%ld, val1=%!T, val2=%!T",
  17063. (long) idx1, (long) idx2, (long) have1, (long) have2,
  17064. (duk_tval *) duk_get_tval(ctx, -2), (duk_tval *) duk_get_tval(ctx, -1)));
  17065. if (have1) {
  17066. if (have2) {
  17067. ;
  17068. } else {
  17069. ret = -1;
  17070. goto pop_ret;
  17071. }
  17072. } else {
  17073. if (have2) {
  17074. ret = 1;
  17075. goto pop_ret;
  17076. } else {
  17077. ret = 0;
  17078. goto pop_ret;
  17079. }
  17080. }
  17081. undef1 = duk_is_undefined(ctx, -2);
  17082. undef2 = duk_is_undefined(ctx, -1);
  17083. if (undef1) {
  17084. if (undef2) {
  17085. ret = 0;
  17086. goto pop_ret;
  17087. } else {
  17088. ret = 1;
  17089. goto pop_ret;
  17090. }
  17091. } else {
  17092. if (undef2) {
  17093. ret = -1;
  17094. goto pop_ret;
  17095. } else {
  17096. ;
  17097. }
  17098. }
  17099. if (!duk_is_undefined(ctx, idx_fn)) {
  17100. duk_double_t d;
  17101. /* no need to check callable; duk_call() will do that */
  17102. duk_dup(ctx, idx_fn); /* -> [ ... x y fn ] */
  17103. duk_insert(ctx, -3); /* -> [ ... fn x y ] */
  17104. duk_call(ctx, 2); /* -> [ ... res ] */
  17105. /* The specification is a bit vague what to do if the return
  17106. * value is not a number. Other implementations seem to
  17107. * tolerate non-numbers but e.g. V8 won't apparently do a
  17108. * ToNumber().
  17109. */
  17110. /* XXX: best behavior for real world compatibility? */
  17111. d = duk_to_number(ctx, -1);
  17112. if (d < 0.0) {
  17113. ret = -1;
  17114. } else if (d > 0.0) {
  17115. ret = 1;
  17116. } else {
  17117. ret = 0;
  17118. }
  17119. duk_pop(ctx);
  17120. DUK_DDD(DUK_DDDPRINT("-> result %ld (from comparefn, after coercion)", (long) ret));
  17121. return ret;
  17122. }
  17123. /* string compare is the default (a bit oddly) */
  17124. h1 = duk_to_hstring(ctx, -2);
  17125. h2 = duk_to_hstring(ctx, -1);
  17126. DUK_ASSERT(h1 != NULL);
  17127. DUK_ASSERT(h2 != NULL);
  17128. ret = duk_js_string_compare(h1, h2); /* retval is directly usable */
  17129. goto pop_ret;
  17130. pop_ret:
  17131. duk_pop_2(ctx);
  17132. DUK_DDD(DUK_DDDPRINT("-> result %ld", (long) ret));
  17133. return ret;
  17134. }
  17135. DUK_LOCAL void duk__array_sort_swap(duk_context *ctx, duk_int_t l, duk_int_t r) {
  17136. duk_bool_t have_l, have_r;
  17137. duk_idx_t idx_obj = 1; /* fixed offset in valstack */
  17138. if (l == r) {
  17139. return;
  17140. }
  17141. /* swap elements; deal with non-existent elements correctly */
  17142. have_l = duk_get_prop_index(ctx, idx_obj, (duk_uarridx_t) l);
  17143. have_r = duk_get_prop_index(ctx, idx_obj, (duk_uarridx_t) r);
  17144. if (have_r) {
  17145. /* right exists, [[Put]] regardless whether or not left exists */
  17146. duk_put_prop_index(ctx, idx_obj, (duk_uarridx_t) l);
  17147. } else {
  17148. duk_del_prop_index(ctx, idx_obj, (duk_uarridx_t) l);
  17149. duk_pop(ctx);
  17150. }
  17151. if (have_l) {
  17152. duk_put_prop_index(ctx, idx_obj, (duk_uarridx_t) r);
  17153. } else {
  17154. duk_del_prop_index(ctx, idx_obj, (duk_uarridx_t) r);
  17155. duk_pop(ctx);
  17156. }
  17157. }
  17158. #if defined(DUK_USE_DDDPRINT)
  17159. /* Debug print which visualizes the qsort partitioning process. */
  17160. DUK_LOCAL void duk__debuglog_qsort_state(duk_context *ctx, duk_int_t lo, duk_int_t hi, duk_int_t pivot) {
  17161. char buf[4096];
  17162. char *ptr = buf;
  17163. duk_int_t i, n;
  17164. n = (duk_int_t) duk_get_length(ctx, 1);
  17165. if (n > 4000) {
  17166. n = 4000;
  17167. }
  17168. *ptr++ = '[';
  17169. for (i = 0; i < n; i++) {
  17170. if (i == pivot) {
  17171. *ptr++ = '|';
  17172. } else if (i == lo) {
  17173. *ptr++ = '<';
  17174. } else if (i == hi) {
  17175. *ptr++ = '>';
  17176. } else if (i >= lo && i <= hi) {
  17177. *ptr++ = '-';
  17178. } else {
  17179. *ptr++ = ' ';
  17180. }
  17181. }
  17182. *ptr++ = ']';
  17183. *ptr++ = '\0';
  17184. DUK_DDD(DUK_DDDPRINT("%s (lo=%ld, hi=%ld, pivot=%ld)",
  17185. (const char *) buf, (long) lo, (long) hi, (long) pivot));
  17186. }
  17187. #endif
  17188. DUK_LOCAL void duk__array_qsort(duk_context *ctx, duk_int_t lo, duk_int_t hi) {
  17189. duk_hthread *thr = (duk_hthread *) ctx;
  17190. duk_int_t p, l, r;
  17191. /* The lo/hi indices may be crossed and hi < 0 is possible at entry. */
  17192. DUK_DDD(DUK_DDDPRINT("duk__array_qsort: lo=%ld, hi=%ld, obj=%!T",
  17193. (long) lo, (long) hi, (duk_tval *) duk_get_tval(ctx, 1)));
  17194. DUK_ASSERT_TOP(ctx, 3);
  17195. /* In some cases it may be that lo > hi, or hi < 0; these
  17196. * degenerate cases happen e.g. for empty arrays, and in
  17197. * recursion leaves.
  17198. */
  17199. /* trivial cases */
  17200. if (hi - lo < 1) {
  17201. DUK_DDD(DUK_DDDPRINT("degenerate case, return immediately"));
  17202. return;
  17203. }
  17204. DUK_ASSERT(hi > lo);
  17205. DUK_ASSERT(hi - lo + 1 >= 2);
  17206. /* randomized pivot selection */
  17207. p = lo + (duk_util_tinyrandom_get_bits(thr, 30) % (hi - lo + 1)); /* rnd in [lo,hi] */
  17208. DUK_ASSERT(p >= lo && p <= hi);
  17209. DUK_DDD(DUK_DDDPRINT("lo=%ld, hi=%ld, chose pivot p=%ld",
  17210. (long) lo, (long) hi, (long) p));
  17211. /* move pivot out of the way */
  17212. duk__array_sort_swap(ctx, p, lo);
  17213. p = lo;
  17214. DUK_DDD(DUK_DDDPRINT("pivot moved out of the way: %!T", (duk_tval *) duk_get_tval(ctx, 1)));
  17215. l = lo + 1;
  17216. r = hi;
  17217. for (;;) {
  17218. /* find elements to swap */
  17219. for (;;) {
  17220. DUK_DDD(DUK_DDDPRINT("left scan: l=%ld, r=%ld, p=%ld",
  17221. (long) l, (long) r, (long) p));
  17222. if (l >= hi) {
  17223. break;
  17224. }
  17225. if (duk__array_sort_compare(ctx, l, p) >= 0) { /* !(l < p) */
  17226. break;
  17227. }
  17228. l++;
  17229. }
  17230. for (;;) {
  17231. DUK_DDD(DUK_DDDPRINT("right scan: l=%ld, r=%ld, p=%ld",
  17232. (long) l, (long) r, (long) p));
  17233. if (r <= lo) {
  17234. break;
  17235. }
  17236. if (duk__array_sort_compare(ctx, p, r) >= 0) { /* !(p < r) */
  17237. break;
  17238. }
  17239. r--;
  17240. }
  17241. if (l >= r) {
  17242. goto done;
  17243. }
  17244. DUK_ASSERT(l < r);
  17245. DUK_DDD(DUK_DDDPRINT("swap %ld and %ld", (long) l, (long) r));
  17246. duk__array_sort_swap(ctx, l, r);
  17247. DUK_DDD(DUK_DDDPRINT("after swap: %!T", (duk_tval *) duk_get_tval(ctx, 1)));
  17248. l++;
  17249. r--;
  17250. }
  17251. done:
  17252. /* Note that 'l' and 'r' may cross, i.e. r < l */
  17253. DUK_ASSERT(l >= lo && l <= hi);
  17254. DUK_ASSERT(r >= lo && r <= hi);
  17255. /* XXX: there's no explicit recursion bound here now. For the average
  17256. * qsort recursion depth O(log n) that's not really necessary: e.g. for
  17257. * 2**32 recursion depth would be about 32 which is OK. However, qsort
  17258. * worst case recursion depth is O(n) which may be a problem.
  17259. */
  17260. /* move pivot to its final place */
  17261. DUK_DDD(DUK_DDDPRINT("before final pivot swap: %!T", (duk_tval *) duk_get_tval(ctx, 1)));
  17262. duk__array_sort_swap(ctx, lo, r);
  17263. #if defined(DUK_USE_DDDPRINT)
  17264. duk__debuglog_qsort_state(ctx, lo, hi, r);
  17265. #endif
  17266. DUK_DDD(DUK_DDDPRINT("recurse: pivot=%ld, obj=%!T", (long) r, (duk_tval *) duk_get_tval(ctx, 1)));
  17267. duk__array_qsort(ctx, lo, r - 1);
  17268. duk__array_qsort(ctx, r + 1, hi);
  17269. }
  17270. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_sort(duk_context *ctx) {
  17271. duk_uint32_t len;
  17272. /* XXX: len >= 0x80000000 won't work below because a signed type
  17273. * is needed by qsort.
  17274. */
  17275. len = duk__push_this_obj_len_u32_limited(ctx);
  17276. /* stack[0] = compareFn
  17277. * stack[1] = ToObject(this)
  17278. * stack[2] = ToUint32(length)
  17279. */
  17280. if (len > 0) {
  17281. /* avoid degenerate cases, so that (len - 1) won't underflow */
  17282. duk__array_qsort(ctx, (duk_int_t) 0, (duk_int_t) (len - 1));
  17283. }
  17284. DUK_ASSERT_TOP(ctx, 3);
  17285. duk_pop(ctx);
  17286. return 1; /* return ToObject(this) */
  17287. }
  17288. /*
  17289. * splice()
  17290. */
  17291. /* XXX: this compiles to over 500 bytes now, even without special handling
  17292. * for an array part. Uses signed ints so does not handle full array range correctly.
  17293. */
  17294. /* XXX: can shift() / unshift() use the same helper?
  17295. * shift() is (close to?) <--> splice(0, 1)
  17296. * unshift is (close to?) <--> splice(0, 0, [items])?
  17297. */
  17298. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_splice(duk_context *ctx) {
  17299. duk_idx_t nargs;
  17300. duk_uint32_t len;
  17301. duk_bool_t have_delcount;
  17302. duk_int_t item_count;
  17303. duk_int_t act_start;
  17304. duk_int_t del_count;
  17305. duk_int_t i, n;
  17306. DUK_UNREF(have_delcount);
  17307. nargs = duk_get_top(ctx);
  17308. if (nargs < 2) {
  17309. duk_set_top(ctx, 2);
  17310. nargs = 2;
  17311. have_delcount = 0;
  17312. } else {
  17313. have_delcount = 1;
  17314. }
  17315. /* XXX: len >= 0x80000000 won't work below because we need to be
  17316. * able to represent -len.
  17317. */
  17318. len = duk__push_this_obj_len_u32_limited(ctx);
  17319. act_start = duk_to_int_clamped(ctx, 0, -((duk_int_t) len), (duk_int_t) len);
  17320. if (act_start < 0) {
  17321. act_start = len + act_start;
  17322. }
  17323. DUK_ASSERT(act_start >= 0 && act_start <= (duk_int_t) len);
  17324. #ifdef DUK_USE_NONSTD_ARRAY_SPLICE_DELCOUNT
  17325. if (have_delcount) {
  17326. #endif
  17327. del_count = duk_to_int_clamped(ctx, 1, 0, len - act_start);
  17328. #ifdef DUK_USE_NONSTD_ARRAY_SPLICE_DELCOUNT
  17329. } else {
  17330. /* E5.1 standard behavior when deleteCount is not given would be
  17331. * to treat it just like if 'undefined' was given, which coerces
  17332. * ultimately to 0. Real world behavior is to splice to the end
  17333. * of array, see test-bi-array-proto-splice-no-delcount.js.
  17334. */
  17335. del_count = len - act_start;
  17336. }
  17337. #endif
  17338. DUK_ASSERT(nargs >= 2);
  17339. item_count = (duk_int_t) (nargs - 2);
  17340. DUK_ASSERT(del_count >= 0 && del_count <= (duk_int_t) len - act_start);
  17341. DUK_ASSERT(del_count + act_start <= (duk_int_t) len);
  17342. /* For now, restrict result array into 32-bit length range. */
  17343. if (((duk_double_t) len) - ((duk_double_t) del_count) + ((duk_double_t) item_count) > (duk_double_t) DUK_UINT32_MAX) {
  17344. DUK_D(DUK_DPRINT("Array.prototype.splice() would go beyond 32-bit length, throw"));
  17345. return DUK_RET_RANGE_ERROR;
  17346. }
  17347. duk_push_array(ctx);
  17348. /* stack[0] = start
  17349. * stack[1] = deleteCount
  17350. * stack[2...nargs-1] = items
  17351. * stack[nargs] = ToObject(this) -3
  17352. * stack[nargs+1] = ToUint32(length) -2
  17353. * stack[nargs+2] = result array -1
  17354. */
  17355. DUK_ASSERT_TOP(ctx, nargs + 3);
  17356. /* Step 9: copy elements-to-be-deleted into the result array */
  17357. for (i = 0; i < del_count; i++) {
  17358. if (duk_get_prop_index(ctx, -3, (duk_uarridx_t) (act_start + i))) {
  17359. duk_xdef_prop_index_wec(ctx, -2, i); /* throw flag irrelevant (false in std alg) */
  17360. } else {
  17361. duk_pop(ctx);
  17362. }
  17363. }
  17364. duk_push_u32(ctx, (duk_uint32_t) del_count);
  17365. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_W);
  17366. /* Steps 12 and 13: reorganize elements to make room for itemCount elements */
  17367. if (item_count < del_count) {
  17368. /* [ A B C D E F G H ] rel_index = 2, del_count 3, item count 1
  17369. * -> [ A B F G H ] (conceptual intermediate step)
  17370. * -> [ A B . F G H ] (placeholder marked)
  17371. * [ A B C F G H ] (actual result at this point, C will be replaced)
  17372. */
  17373. DUK_ASSERT_TOP(ctx, nargs + 3);
  17374. n = len - del_count;
  17375. for (i = act_start; i < n; i++) {
  17376. if (duk_get_prop_index(ctx, -3, (duk_uarridx_t) (i + del_count))) {
  17377. duk_put_prop_index(ctx, -4, (duk_uarridx_t) (i + item_count));
  17378. } else {
  17379. duk_pop(ctx);
  17380. duk_del_prop_index(ctx, -3, (duk_uarridx_t) (i + item_count));
  17381. }
  17382. }
  17383. DUK_ASSERT_TOP(ctx, nargs + 3);
  17384. /* loop iterator init and limit changed from standard algorithm */
  17385. n = len - del_count + item_count;
  17386. for (i = len - 1; i >= n; i--) {
  17387. duk_del_prop_index(ctx, -3, (duk_uarridx_t) i);
  17388. }
  17389. DUK_ASSERT_TOP(ctx, nargs + 3);
  17390. } else if (item_count > del_count) {
  17391. /* [ A B C D E F G H ] rel_index = 2, del_count 3, item count 4
  17392. * -> [ A B F G H ] (conceptual intermediate step)
  17393. * -> [ A B . . . . F G H ] (placeholder marked)
  17394. * [ A B C D E F F G H ] (actual result at this point)
  17395. */
  17396. DUK_ASSERT_TOP(ctx, nargs + 3);
  17397. /* loop iterator init and limit changed from standard algorithm */
  17398. for (i = len - del_count - 1; i >= act_start; i--) {
  17399. if (duk_get_prop_index(ctx, -3, (duk_uarridx_t) (i + del_count))) {
  17400. duk_put_prop_index(ctx, -4, (duk_uarridx_t) (i + item_count));
  17401. } else {
  17402. duk_pop(ctx);
  17403. duk_del_prop_index(ctx, -3, (duk_uarridx_t) (i + item_count));
  17404. }
  17405. }
  17406. DUK_ASSERT_TOP(ctx, nargs + 3);
  17407. } else {
  17408. /* [ A B C D E F G H ] rel_index = 2, del_count 3, item count 3
  17409. * -> [ A B F G H ] (conceptual intermediate step)
  17410. * -> [ A B . . . F G H ] (placeholder marked)
  17411. * [ A B C D E F G H ] (actual result at this point)
  17412. */
  17413. }
  17414. DUK_ASSERT_TOP(ctx, nargs + 3);
  17415. /* Step 15: insert itemCount elements into the hole made above */
  17416. for (i = 0; i < item_count; i++) {
  17417. duk_dup(ctx, i + 2); /* args start at index 2 */
  17418. duk_put_prop_index(ctx, -4, (duk_uarridx_t) (act_start + i));
  17419. }
  17420. /* Step 16: update length; note that the final length may be above 32 bit range
  17421. * (but we checked above that this isn't the case here)
  17422. */
  17423. duk_push_u32(ctx, len - del_count + item_count);
  17424. duk_put_prop_stridx(ctx, -4, DUK_STRIDX_LENGTH);
  17425. /* result array is already at the top of stack */
  17426. DUK_ASSERT_TOP(ctx, nargs + 3);
  17427. return 1;
  17428. }
  17429. /*
  17430. * reverse()
  17431. */
  17432. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_reverse(duk_context *ctx) {
  17433. duk_uint32_t len;
  17434. duk_uint32_t middle;
  17435. duk_uint32_t lower, upper;
  17436. duk_bool_t have_lower, have_upper;
  17437. len = duk__push_this_obj_len_u32(ctx);
  17438. middle = len / 2;
  17439. /* If len <= 1, middle will be 0 and for-loop bails out
  17440. * immediately (0 < 0 -> false).
  17441. */
  17442. for (lower = 0; lower < middle; lower++) {
  17443. DUK_ASSERT(len >= 2);
  17444. DUK_ASSERT_TOP(ctx, 2);
  17445. DUK_ASSERT(len >= lower + 1);
  17446. upper = len - lower - 1;
  17447. have_lower = duk_get_prop_index(ctx, -2, (duk_uarridx_t) lower);
  17448. have_upper = duk_get_prop_index(ctx, -3, (duk_uarridx_t) upper);
  17449. /* [ ToObject(this) ToUint32(length) lowerValue upperValue ] */
  17450. if (have_upper) {
  17451. duk_put_prop_index(ctx, -4, (duk_uarridx_t) lower);
  17452. } else {
  17453. duk_del_prop_index(ctx, -4, (duk_uarridx_t) lower);
  17454. duk_pop(ctx);
  17455. }
  17456. if (have_lower) {
  17457. duk_put_prop_index(ctx, -3, (duk_uarridx_t) upper);
  17458. } else {
  17459. duk_del_prop_index(ctx, -3, (duk_uarridx_t) upper);
  17460. duk_pop(ctx);
  17461. }
  17462. DUK_ASSERT_TOP(ctx, 2);
  17463. }
  17464. DUK_ASSERT_TOP(ctx, 2);
  17465. duk_pop(ctx); /* -> [ ToObject(this) ] */
  17466. return 1;
  17467. }
  17468. /*
  17469. * slice()
  17470. */
  17471. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_slice(duk_context *ctx) {
  17472. duk_uint32_t len;
  17473. duk_int_t start, end;
  17474. duk_int_t i;
  17475. duk_uarridx_t idx;
  17476. duk_uint32_t res_length = 0;
  17477. /* XXX: len >= 0x80000000 won't work below because we need to be
  17478. * able to represent -len.
  17479. */
  17480. len = duk__push_this_obj_len_u32_limited(ctx);
  17481. duk_push_array(ctx);
  17482. /* stack[0] = start
  17483. * stack[1] = end
  17484. * stack[2] = ToObject(this)
  17485. * stack[3] = ToUint32(length)
  17486. * stack[4] = result array
  17487. */
  17488. start = duk_to_int_clamped(ctx, 0, -((duk_int_t) len), (duk_int_t) len);
  17489. if (start < 0) {
  17490. start = len + start;
  17491. }
  17492. /* XXX: could duk_is_undefined() provide defaulting undefined to 'len'
  17493. * (the upper limit)?
  17494. */
  17495. if (duk_is_undefined(ctx, 1)) {
  17496. end = len;
  17497. } else {
  17498. end = duk_to_int_clamped(ctx, 1, -((duk_int_t) len), (duk_int_t) len);
  17499. if (end < 0) {
  17500. end = len + end;
  17501. }
  17502. }
  17503. DUK_ASSERT(start >= 0 && (duk_uint32_t) start <= len);
  17504. DUK_ASSERT(end >= 0 && (duk_uint32_t) end <= len);
  17505. idx = 0;
  17506. for (i = start; i < end; i++) {
  17507. DUK_ASSERT_TOP(ctx, 5);
  17508. if (duk_get_prop_index(ctx, 2, (duk_uarridx_t) i)) {
  17509. duk_xdef_prop_index_wec(ctx, 4, idx);
  17510. res_length = idx + 1;
  17511. } else {
  17512. duk_pop(ctx);
  17513. }
  17514. idx++;
  17515. DUK_ASSERT_TOP(ctx, 5);
  17516. }
  17517. duk_push_u32(ctx, res_length);
  17518. duk_xdef_prop_stridx(ctx, 4, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_W);
  17519. DUK_ASSERT_TOP(ctx, 5);
  17520. return 1;
  17521. }
  17522. /*
  17523. * shift()
  17524. */
  17525. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_shift(duk_context *ctx) {
  17526. duk_uint32_t len;
  17527. duk_uint32_t i;
  17528. len = duk__push_this_obj_len_u32(ctx);
  17529. if (len == 0) {
  17530. duk_push_int(ctx, 0);
  17531. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LENGTH);
  17532. return 0;
  17533. }
  17534. duk_get_prop_index(ctx, 0, 0);
  17535. /* stack[0] = object (this)
  17536. * stack[1] = ToUint32(length)
  17537. * stack[2] = elem at index 0 (retval)
  17538. */
  17539. for (i = 1; i < len; i++) {
  17540. DUK_ASSERT_TOP(ctx, 3);
  17541. if (duk_get_prop_index(ctx, 0, (duk_uarridx_t) i)) {
  17542. /* fromPresent = true */
  17543. duk_put_prop_index(ctx, 0, (duk_uarridx_t) (i - 1));
  17544. } else {
  17545. /* fromPresent = false */
  17546. duk_del_prop_index(ctx, 0, (duk_uarridx_t) (i - 1));
  17547. duk_pop(ctx);
  17548. }
  17549. }
  17550. duk_del_prop_index(ctx, 0, (duk_uarridx_t) (len - 1));
  17551. duk_push_u32(ctx, (duk_uint32_t) (len - 1));
  17552. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LENGTH);
  17553. DUK_ASSERT_TOP(ctx, 3);
  17554. return 1;
  17555. }
  17556. /*
  17557. * unshift()
  17558. */
  17559. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_unshift(duk_context *ctx) {
  17560. duk_idx_t nargs;
  17561. duk_uint32_t len;
  17562. duk_uint32_t i;
  17563. nargs = duk_get_top(ctx);
  17564. len = duk__push_this_obj_len_u32(ctx);
  17565. /* stack[0...nargs-1] = unshift args (vararg)
  17566. * stack[nargs] = ToObject(this)
  17567. * stack[nargs+1] = ToUint32(length)
  17568. */
  17569. DUK_ASSERT_TOP(ctx, nargs + 2);
  17570. /* Note: unshift() may operate on indices above unsigned 32-bit range
  17571. * and the final length may be >= 2**32. However, we restrict the
  17572. * final result to 32-bit range for practicality.
  17573. */
  17574. if (len + (duk_uint32_t) nargs < len) {
  17575. DUK_D(DUK_DPRINT("Array.prototype.unshift() would go beyond 32-bit length, throw"));
  17576. return DUK_RET_RANGE_ERROR;
  17577. }
  17578. i = len;
  17579. while (i > 0) {
  17580. DUK_ASSERT_TOP(ctx, nargs + 2);
  17581. i--;
  17582. /* k+argCount-1; note that may be above 32-bit range */
  17583. if (duk_get_prop_index(ctx, -2, (duk_uarridx_t) i)) {
  17584. /* fromPresent = true */
  17585. /* [ ... ToObject(this) ToUint32(length) val ] */
  17586. duk_put_prop_index(ctx, -3, (duk_uarridx_t) (i + nargs)); /* -> [ ... ToObject(this) ToUint32(length) ] */
  17587. } else {
  17588. /* fromPresent = false */
  17589. /* [ ... ToObject(this) ToUint32(length) val ] */
  17590. duk_pop(ctx);
  17591. duk_del_prop_index(ctx, -2, (duk_uarridx_t) (i + nargs)); /* -> [ ... ToObject(this) ToUint32(length) ] */
  17592. }
  17593. DUK_ASSERT_TOP(ctx, nargs + 2);
  17594. }
  17595. for (i = 0; i < (duk_uint32_t) nargs; i++) {
  17596. DUK_ASSERT_TOP(ctx, nargs + 2);
  17597. duk_dup(ctx, i); /* -> [ ... ToObject(this) ToUint32(length) arg[i] ] */
  17598. duk_put_prop_index(ctx, -3, (duk_uarridx_t) i);
  17599. DUK_ASSERT_TOP(ctx, nargs + 2);
  17600. }
  17601. DUK_ASSERT_TOP(ctx, nargs + 2);
  17602. duk_push_u32(ctx, len + nargs);
  17603. duk_dup_top(ctx); /* -> [ ... ToObject(this) ToUint32(length) final_len final_len ] */
  17604. duk_put_prop_stridx(ctx, -4, DUK_STRIDX_LENGTH);
  17605. return 1;
  17606. }
  17607. /*
  17608. * indexOf(), lastIndexOf()
  17609. */
  17610. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_indexof_shared(duk_context *ctx) {
  17611. duk_idx_t nargs;
  17612. duk_int_t i, len;
  17613. duk_int_t from_index;
  17614. duk_small_int_t idx_step = duk_get_current_magic(ctx); /* idx_step is +1 for indexOf, -1 for lastIndexOf */
  17615. /* lastIndexOf() needs to be a vararg function because we must distinguish
  17616. * between an undefined fromIndex and a "not given" fromIndex; indexOf() is
  17617. * made vararg for symmetry although it doesn't strictly need to be.
  17618. */
  17619. nargs = duk_get_top(ctx);
  17620. duk_set_top(ctx, 2);
  17621. /* XXX: must be able to represent -len */
  17622. len = (duk_int_t) duk__push_this_obj_len_u32_limited(ctx);
  17623. if (len == 0) {
  17624. goto not_found;
  17625. }
  17626. /* Index clamping is a bit tricky, we must ensure that we'll only iterate
  17627. * through elements that exist and that the specific requirements from E5.1
  17628. * Sections 15.4.4.14 and 15.4.4.15 are fulfilled; especially:
  17629. *
  17630. * - indexOf: clamp to [-len,len], negative handling -> [0,len],
  17631. * if clamped result is len, for-loop bails out immediately
  17632. *
  17633. * - lastIndexOf: clamp to [-len-1, len-1], negative handling -> [-1, len-1],
  17634. * if clamped result is -1, for-loop bails out immediately
  17635. *
  17636. * If fromIndex is not given, ToInteger(undefined) = 0, which is correct
  17637. * for indexOf() but incorrect for lastIndexOf(). Hence special handling,
  17638. * and why lastIndexOf() needs to be a vararg function.
  17639. */
  17640. if (nargs >= 2) {
  17641. /* indexOf: clamp fromIndex to [-len, len]
  17642. * (if fromIndex == len, for-loop terminates directly)
  17643. *
  17644. * lastIndexOf: clamp fromIndex to [-len - 1, len - 1]
  17645. * (if clamped to -len-1 -> fromIndex becomes -1, terminates for-loop directly)
  17646. */
  17647. from_index = duk_to_int_clamped(ctx,
  17648. 1,
  17649. (idx_step > 0 ? -len : -len - 1),
  17650. (idx_step > 0 ? len : len - 1));
  17651. if (from_index < 0) {
  17652. /* for lastIndexOf, result may be -1 (mark immediate termination) */
  17653. from_index = len + from_index;
  17654. }
  17655. } else {
  17656. /* for indexOf, ToInteger(undefined) would be 0, i.e. correct, but
  17657. * handle both indexOf and lastIndexOf specially here.
  17658. */
  17659. if (idx_step > 0) {
  17660. from_index = 0;
  17661. } else {
  17662. from_index = len - 1;
  17663. }
  17664. }
  17665. /* stack[0] = searchElement
  17666. * stack[1] = fromIndex
  17667. * stack[2] = object
  17668. * stack[3] = length (not needed, but not popped above)
  17669. */
  17670. for (i = from_index; i >= 0 && i < len; i += idx_step) {
  17671. DUK_ASSERT_TOP(ctx, 4);
  17672. if (duk_get_prop_index(ctx, 2, (duk_uarridx_t) i)) {
  17673. DUK_ASSERT_TOP(ctx, 5);
  17674. if (duk_strict_equals(ctx, 0, 4)) {
  17675. duk_push_int(ctx, i);
  17676. return 1;
  17677. }
  17678. }
  17679. duk_pop(ctx);
  17680. }
  17681. not_found:
  17682. duk_push_int(ctx, -1);
  17683. return 1;
  17684. }
  17685. /*
  17686. * every(), some(), forEach(), map(), filter()
  17687. */
  17688. #define DUK__ITER_EVERY 0
  17689. #define DUK__ITER_SOME 1
  17690. #define DUK__ITER_FOREACH 2
  17691. #define DUK__ITER_MAP 3
  17692. #define DUK__ITER_FILTER 4
  17693. /* XXX: This helper is a bit awkward because the handling for the different iteration
  17694. * callers is quite different. This now compiles to a bit less than 500 bytes, so with
  17695. * 5 callers the net result is about 100 bytes / caller.
  17696. */
  17697. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_iter_shared(duk_context *ctx) {
  17698. duk_uint32_t len;
  17699. duk_uint32_t i;
  17700. duk_uarridx_t k;
  17701. duk_bool_t bval;
  17702. duk_small_int_t iter_type = duk_get_current_magic(ctx);
  17703. duk_uint32_t res_length = 0;
  17704. /* each call this helper serves has nargs==2 */
  17705. DUK_ASSERT_TOP(ctx, 2);
  17706. len = duk__push_this_obj_len_u32(ctx);
  17707. if (!duk_is_callable(ctx, 0)) {
  17708. goto type_error;
  17709. }
  17710. /* if thisArg not supplied, behave as if undefined was supplied */
  17711. if (iter_type == DUK__ITER_MAP || iter_type == DUK__ITER_FILTER) {
  17712. duk_push_array(ctx);
  17713. } else {
  17714. duk_push_undefined(ctx);
  17715. }
  17716. /* stack[0] = callback
  17717. * stack[1] = thisArg
  17718. * stack[2] = object
  17719. * stack[3] = ToUint32(length) (unused, but avoid unnecessary pop)
  17720. * stack[4] = result array (or undefined)
  17721. */
  17722. k = 0; /* result index for filter() */
  17723. for (i = 0; i < len; i++) {
  17724. DUK_ASSERT_TOP(ctx, 5);
  17725. if (!duk_get_prop_index(ctx, 2, (duk_uarridx_t) i)) {
  17726. #if defined(DUK_USE_NONSTD_ARRAY_MAP_TRAILER)
  17727. /* Real world behavior for map(): trailing non-existent
  17728. * elements don't invoke the user callback, but are still
  17729. * counted towards result 'length'.
  17730. */
  17731. if (iter_type == DUK__ITER_MAP) {
  17732. res_length = i + 1;
  17733. }
  17734. #else
  17735. /* Standard behavior for map(): trailing non-existent
  17736. * elements don't invoke the user callback and are not
  17737. * counted towards result 'length'.
  17738. */
  17739. #endif
  17740. duk_pop(ctx);
  17741. continue;
  17742. }
  17743. /* The original value needs to be preserved for filter(), hence
  17744. * this funny order. We can't re-get the value because of side
  17745. * effects.
  17746. */
  17747. duk_dup(ctx, 0);
  17748. duk_dup(ctx, 1);
  17749. duk_dup(ctx, -3);
  17750. duk_push_u32(ctx, i);
  17751. duk_dup(ctx, 2); /* [ ... val callback thisArg val i obj ] */
  17752. duk_call_method(ctx, 3); /* -> [ ... val retval ] */
  17753. switch (iter_type) {
  17754. case DUK__ITER_EVERY:
  17755. bval = duk_to_boolean(ctx, -1);
  17756. if (!bval) {
  17757. /* stack top contains 'false' */
  17758. return 1;
  17759. }
  17760. break;
  17761. case DUK__ITER_SOME:
  17762. bval = duk_to_boolean(ctx, -1);
  17763. if (bval) {
  17764. /* stack top contains 'true' */
  17765. return 1;
  17766. }
  17767. break;
  17768. case DUK__ITER_FOREACH:
  17769. /* nop */
  17770. break;
  17771. case DUK__ITER_MAP:
  17772. duk_dup(ctx, -1);
  17773. duk_xdef_prop_index_wec(ctx, 4, (duk_uarridx_t) i); /* retval to result[i] */
  17774. res_length = i + 1;
  17775. break;
  17776. case DUK__ITER_FILTER:
  17777. bval = duk_to_boolean(ctx, -1);
  17778. if (bval) {
  17779. duk_dup(ctx, -2); /* orig value */
  17780. duk_xdef_prop_index_wec(ctx, 4, (duk_uarridx_t) k);
  17781. k++;
  17782. res_length = k;
  17783. }
  17784. break;
  17785. default:
  17786. DUK_UNREACHABLE();
  17787. break;
  17788. }
  17789. duk_pop_2(ctx);
  17790. DUK_ASSERT_TOP(ctx, 5);
  17791. }
  17792. switch (iter_type) {
  17793. case DUK__ITER_EVERY:
  17794. duk_push_true(ctx);
  17795. break;
  17796. case DUK__ITER_SOME:
  17797. duk_push_false(ctx);
  17798. break;
  17799. case DUK__ITER_FOREACH:
  17800. duk_push_undefined(ctx);
  17801. break;
  17802. case DUK__ITER_MAP:
  17803. case DUK__ITER_FILTER:
  17804. DUK_ASSERT_TOP(ctx, 5);
  17805. DUK_ASSERT(duk_is_array(ctx, -1)); /* topmost element is the result array already */
  17806. duk_push_u32(ctx, res_length);
  17807. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_W);
  17808. break;
  17809. default:
  17810. DUK_UNREACHABLE();
  17811. break;
  17812. }
  17813. return 1;
  17814. type_error:
  17815. return DUK_RET_TYPE_ERROR;
  17816. }
  17817. /*
  17818. * reduce(), reduceRight()
  17819. */
  17820. DUK_INTERNAL duk_ret_t duk_bi_array_prototype_reduce_shared(duk_context *ctx) {
  17821. duk_idx_t nargs;
  17822. duk_bool_t have_acc;
  17823. duk_uint32_t i, len;
  17824. duk_small_int_t idx_step = duk_get_current_magic(ctx); /* idx_step is +1 for reduce, -1 for reduceRight */
  17825. /* We're a varargs function because we need to detect whether
  17826. * initialValue was given or not.
  17827. */
  17828. nargs = duk_get_top(ctx);
  17829. DUK_DDD(DUK_DDDPRINT("nargs=%ld", (long) nargs));
  17830. duk_set_top(ctx, 2);
  17831. len = duk__push_this_obj_len_u32(ctx);
  17832. if (!duk_is_callable(ctx, 0)) {
  17833. goto type_error;
  17834. }
  17835. /* stack[0] = callback fn
  17836. * stack[1] = initialValue
  17837. * stack[2] = object (coerced this)
  17838. * stack[3] = length (not needed, but not popped above)
  17839. * stack[4] = accumulator
  17840. */
  17841. have_acc = 0;
  17842. if (nargs >= 2) {
  17843. duk_dup(ctx, 1);
  17844. have_acc = 1;
  17845. }
  17846. DUK_DDD(DUK_DDDPRINT("have_acc=%ld, acc=%!T",
  17847. (long) have_acc, (duk_tval *) duk_get_tval(ctx, 3)));
  17848. /* For len == 0, i is initialized to len - 1 which underflows.
  17849. * The condition (i < len) will then exit the for-loop on the
  17850. * first round which is correct. Similarly, loop termination
  17851. * happens by i underflowing.
  17852. */
  17853. for (i = (idx_step >= 0 ? 0 : len - 1);
  17854. i < len; /* i >= 0 would always be true */
  17855. i += idx_step) {
  17856. DUK_DDD(DUK_DDDPRINT("i=%ld, len=%ld, have_acc=%ld, top=%ld, acc=%!T",
  17857. (long) i, (long) len, (long) have_acc,
  17858. (long) duk_get_top(ctx),
  17859. (duk_tval *) duk_get_tval(ctx, 4)));
  17860. DUK_ASSERT((have_acc && duk_get_top(ctx) == 5) ||
  17861. (!have_acc && duk_get_top(ctx) == 4));
  17862. if (!duk_has_prop_index(ctx, 2, (duk_uarridx_t) i)) {
  17863. continue;
  17864. }
  17865. if (!have_acc) {
  17866. DUK_ASSERT_TOP(ctx, 4);
  17867. duk_get_prop_index(ctx, 2, (duk_uarridx_t) i);
  17868. have_acc = 1;
  17869. DUK_ASSERT_TOP(ctx, 5);
  17870. } else {
  17871. DUK_ASSERT_TOP(ctx, 5);
  17872. duk_dup(ctx, 0);
  17873. duk_dup(ctx, 4);
  17874. duk_get_prop_index(ctx, 2, (duk_uarridx_t) i);
  17875. duk_push_u32(ctx, i);
  17876. duk_dup(ctx, 2);
  17877. DUK_DDD(DUK_DDDPRINT("calling reduce function: func=%!T, prev=%!T, curr=%!T, idx=%!T, obj=%!T",
  17878. (duk_tval *) duk_get_tval(ctx, -5), (duk_tval *) duk_get_tval(ctx, -4),
  17879. (duk_tval *) duk_get_tval(ctx, -3), (duk_tval *) duk_get_tval(ctx, -2),
  17880. (duk_tval *) duk_get_tval(ctx, -1)));
  17881. duk_call(ctx, 4);
  17882. DUK_DDD(DUK_DDDPRINT("-> result: %!T", (duk_tval *) duk_get_tval(ctx, -1)));
  17883. duk_replace(ctx, 4);
  17884. DUK_ASSERT_TOP(ctx, 5);
  17885. }
  17886. }
  17887. if (!have_acc) {
  17888. goto type_error;
  17889. }
  17890. DUK_ASSERT_TOP(ctx, 5);
  17891. return 1;
  17892. type_error:
  17893. return DUK_RET_TYPE_ERROR;
  17894. }
  17895. #line 1 "duk_bi_boolean.c"
  17896. /*
  17897. * Boolean built-ins
  17898. */
  17899. /* include removed: duk_internal.h */
  17900. /* Shared helper to provide toString() and valueOf(). Checks 'this', gets
  17901. * the primitive value to stack top, and optionally coerces with ToString().
  17902. */
  17903. DUK_INTERNAL duk_ret_t duk_bi_boolean_prototype_tostring_shared(duk_context *ctx) {
  17904. duk_tval *tv;
  17905. duk_hobject *h;
  17906. duk_small_int_t coerce_tostring = duk_get_current_magic(ctx);
  17907. /* XXX: there is room to use a shared helper here, many built-ins
  17908. * check the 'this' type, and if it's an object, check its class,
  17909. * then get its internal value, etc.
  17910. */
  17911. duk_push_this(ctx);
  17912. tv = duk_get_tval(ctx, -1);
  17913. DUK_ASSERT(tv != NULL);
  17914. if (DUK_TVAL_IS_BOOLEAN(tv)) {
  17915. goto type_ok;
  17916. } else if (DUK_TVAL_IS_OBJECT(tv)) {
  17917. h = DUK_TVAL_GET_OBJECT(tv);
  17918. DUK_ASSERT(h != NULL);
  17919. if (DUK_HOBJECT_GET_CLASS_NUMBER(h) == DUK_HOBJECT_CLASS_BOOLEAN) {
  17920. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE);
  17921. DUK_ASSERT(duk_is_boolean(ctx, -1));
  17922. goto type_ok;
  17923. }
  17924. }
  17925. return DUK_RET_TYPE_ERROR;
  17926. type_ok:
  17927. if (coerce_tostring) {
  17928. duk_to_string(ctx, -1);
  17929. }
  17930. return 1;
  17931. }
  17932. DUK_INTERNAL duk_ret_t duk_bi_boolean_constructor(duk_context *ctx) {
  17933. duk_hthread *thr = (duk_hthread *) ctx;
  17934. duk_hobject *h_this;
  17935. DUK_UNREF(thr);
  17936. duk_to_boolean(ctx, 0);
  17937. if (duk_is_constructor_call(ctx)) {
  17938. /* XXX: helper; rely on Boolean.prototype as being non-writable, non-configurable */
  17939. duk_push_this(ctx);
  17940. h_this = duk_get_hobject(ctx, -1);
  17941. DUK_ASSERT(h_this != NULL);
  17942. DUK_ASSERT(DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h_this) == thr->builtins[DUK_BIDX_BOOLEAN_PROTOTYPE]);
  17943. DUK_HOBJECT_SET_CLASS_NUMBER(h_this, DUK_HOBJECT_CLASS_BOOLEAN);
  17944. duk_dup(ctx, 0); /* -> [ val obj val ] */
  17945. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_NONE); /* XXX: proper flags? */
  17946. } /* unbalanced stack */
  17947. return 1;
  17948. }
  17949. #line 1 "duk_bi_buffer.c"
  17950. /*
  17951. * Buffer built-ins
  17952. */
  17953. /* include removed: duk_internal.h */
  17954. /*
  17955. * Constructor
  17956. */
  17957. DUK_INTERNAL duk_ret_t duk_bi_buffer_constructor(duk_context *ctx) {
  17958. duk_size_t buf_size;
  17959. duk_small_int_t buf_dynamic;
  17960. duk_uint8_t *buf_data;
  17961. const duk_uint8_t *src_data;
  17962. duk_hobject *h_obj;
  17963. /*
  17964. * Constructor arguments are currently somewhat compatible with
  17965. * (keep it that way if possible):
  17966. *
  17967. * http://nodejs.org/api/buffer.html
  17968. *
  17969. * Note that the ToBuffer() coercion (duk_to_buffer()) does NOT match
  17970. * the constructor behavior.
  17971. */
  17972. buf_dynamic = duk_get_boolean(ctx, 1); /* default to false */
  17973. switch (duk_get_type(ctx, 0)) {
  17974. case DUK_TYPE_NUMBER:
  17975. /* new buffer of specified size */
  17976. buf_size = (duk_size_t) duk_to_int(ctx, 0);
  17977. (void) duk_push_buffer(ctx, buf_size, buf_dynamic);
  17978. break;
  17979. case DUK_TYPE_BUFFER:
  17980. /* return input buffer, converted to a Buffer object if called as a
  17981. * constructor (no change if called as a function).
  17982. */
  17983. duk_set_top(ctx, 1);
  17984. break;
  17985. case DUK_TYPE_STRING:
  17986. /* new buffer with string contents */
  17987. src_data = (const duk_uint8_t *) duk_get_lstring(ctx, 0, &buf_size);
  17988. DUK_ASSERT(src_data != NULL); /* even for zero-length string */
  17989. buf_data = (duk_uint8_t *) duk_push_buffer(ctx, buf_size, buf_dynamic);
  17990. DUK_MEMCPY((void *) buf_data, (const void *) src_data, (size_t) buf_size);
  17991. break;
  17992. case DUK_TYPE_OBJECT:
  17993. /* Buffer object: get the plain buffer inside. If called as as
  17994. * constructor, a new Buffer object pointing to the same plain
  17995. * buffer is created below.
  17996. */
  17997. h_obj = duk_get_hobject(ctx, 0);
  17998. DUK_ASSERT(h_obj != NULL);
  17999. if (DUK_HOBJECT_GET_CLASS_NUMBER(h_obj) != DUK_HOBJECT_CLASS_BUFFER) {
  18000. return DUK_RET_TYPE_ERROR;
  18001. }
  18002. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_INT_VALUE);
  18003. DUK_ASSERT(duk_is_buffer(ctx, -1));
  18004. break;
  18005. case DUK_TYPE_NONE:
  18006. default:
  18007. return DUK_RET_TYPE_ERROR;
  18008. }
  18009. /* stack is unbalanced, but: [ <something> buf ] */
  18010. if (duk_is_constructor_call(ctx)) {
  18011. duk_push_object_helper(ctx,
  18012. DUK_HOBJECT_FLAG_EXTENSIBLE |
  18013. DUK_HOBJECT_FLAG_EXOTIC_BUFFEROBJ |
  18014. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_BUFFER),
  18015. DUK_BIDX_BUFFER_PROTOTYPE);
  18016. /* Buffer object internal value is immutable */
  18017. duk_dup(ctx, -2);
  18018. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_NONE);
  18019. }
  18020. /* Note: unbalanced stack on purpose */
  18021. return 1;
  18022. }
  18023. /*
  18024. * toString(), valueOf()
  18025. */
  18026. DUK_INTERNAL duk_ret_t duk_bi_buffer_prototype_tostring_shared(duk_context *ctx) {
  18027. duk_tval *tv;
  18028. duk_small_int_t to_string = duk_get_current_magic(ctx);
  18029. duk_push_this(ctx);
  18030. tv = duk_require_tval(ctx, -1);
  18031. DUK_ASSERT(tv != NULL);
  18032. if (DUK_TVAL_IS_BUFFER(tv)) {
  18033. /* nop */
  18034. } else if (DUK_TVAL_IS_OBJECT(tv)) {
  18035. duk_hobject *h = DUK_TVAL_GET_OBJECT(tv);
  18036. DUK_ASSERT(h != NULL);
  18037. /* Must be a "buffer object", i.e. class "Buffer" */
  18038. if (DUK_HOBJECT_GET_CLASS_NUMBER(h) != DUK_HOBJECT_CLASS_BUFFER) {
  18039. goto type_error;
  18040. }
  18041. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE);
  18042. } else {
  18043. goto type_error;
  18044. }
  18045. if (to_string) {
  18046. duk_to_string(ctx, -1);
  18047. }
  18048. return 1;
  18049. type_error:
  18050. return DUK_RET_TYPE_ERROR;
  18051. }
  18052. #line 1 "duk_bi_date.c"
  18053. /*
  18054. * Date built-ins
  18055. *
  18056. * Unlike most built-ins, Date has a lot of platform dependencies for
  18057. * getting UTC time, converting between UTC and local time, and parsing
  18058. * and formatting time values.
  18059. *
  18060. * See doc/datetime.txt.
  18061. *
  18062. * Platform specific links:
  18063. *
  18064. * - http://msdn.microsoft.com/en-us/library/windows/desktop/ms725473(v=vs.85).aspx
  18065. */
  18066. /* include removed: duk_internal.h */
  18067. /*
  18068. * Platform specific includes and defines
  18069. *
  18070. * Note that necessary system headers (like <sys/time.h>) are included
  18071. * by duk_internal.h (or duk_features.h, which is included by duk_internal.h)
  18072. * because the header locations vary between systems and we don't want
  18073. * that clutter here.
  18074. */
  18075. #define DUK__GET_NOW_TIMEVAL duk_bi_date_get_now
  18076. #define DUK__GET_LOCAL_TZOFFSET duk__get_local_tzoffset
  18077. /* Buffer sizes for some UNIX calls. Larger than strictly necessary
  18078. * to avoid Valgrind errors.
  18079. */
  18080. #define DUK__STRPTIME_BUF_SIZE 64
  18081. #define DUK__STRFTIME_BUF_SIZE 64
  18082. /*
  18083. * Other file level defines
  18084. */
  18085. /* Forward declarations. */
  18086. DUK_LOCAL_DECL duk_double_t duk__push_this_get_timeval_tzoffset(duk_context *ctx, duk_small_uint_t flags, duk_int_t *out_tzoffset);
  18087. DUK_LOCAL_DECL duk_double_t duk__push_this_get_timeval(duk_context *ctx, duk_small_uint_t flags);
  18088. DUK_LOCAL_DECL void duk__timeval_to_parts(duk_double_t d, duk_int_t *parts, duk_double_t *dparts, duk_small_uint_t flags);
  18089. DUK_LOCAL_DECL duk_double_t duk__get_timeval_from_dparts(duk_double_t *dparts, duk_small_uint_t flags);
  18090. DUK_LOCAL_DECL void duk__twodigit_year_fixup(duk_context *ctx, duk_idx_t idx_val);
  18091. DUK_LOCAL_DECL duk_bool_t duk__is_leap_year(duk_int_t year);
  18092. DUK_LOCAL_DECL duk_bool_t duk__timeval_in_valid_range(duk_double_t x);
  18093. DUK_LOCAL_DECL duk_bool_t duk__timeval_in_leeway_range(duk_double_t x);
  18094. DUK_LOCAL_DECL duk_bool_t duk__year_in_valid_range(duk_double_t year);
  18095. /* Millisecond count constants. */
  18096. #define DUK__MS_SECOND 1000L
  18097. #define DUK__MS_MINUTE (60L * 1000L)
  18098. #define DUK__MS_HOUR (60L * 60L * 1000L)
  18099. #define DUK__MS_DAY (24L * 60L * 60L * 1000L)
  18100. /* Ecmascript date range is 100 million days from Epoch:
  18101. * > 100e6 * 24 * 60 * 60 * 1000 // 100M days in millisecs
  18102. * 8640000000000000
  18103. * (= 8.64e15)
  18104. */
  18105. #define DUK__MS_100M_DAYS (8.64e15)
  18106. #define DUK__MS_100M_DAYS_LEEWAY (8.64e15 + 24 * 3600e3)
  18107. /* Ecmascript year range:
  18108. * > new Date(100e6 * 24 * 3600e3).toISOString()
  18109. * '+275760-09-13T00:00:00.000Z'
  18110. * > new Date(-100e6 * 24 * 3600e3).toISOString()
  18111. * '-271821-04-20T00:00:00.000Z'
  18112. */
  18113. #define DUK__MIN_ECMA_YEAR (-271821)
  18114. #define DUK__MAX_ECMA_YEAR 275760
  18115. /* Part indices for internal breakdowns. Part order from DUK__IDX_YEAR to
  18116. * DUK__IDX_MILLISECOND matches argument ordering of Ecmascript API calls
  18117. * (like Date constructor call). A few functions in this file depend
  18118. * on the specific ordering, so change with care. 16 bits are not enough
  18119. * for all parts (year, specifically).
  18120. *
  18121. * (Must be in-sync with genbuiltins.py.)
  18122. */
  18123. #define DUK__IDX_YEAR 0 /* year */
  18124. #define DUK__IDX_MONTH 1 /* month: 0 to 11 */
  18125. #define DUK__IDX_DAY 2 /* day within month: 0 to 30 */
  18126. #define DUK__IDX_HOUR 3
  18127. #define DUK__IDX_MINUTE 4
  18128. #define DUK__IDX_SECOND 5
  18129. #define DUK__IDX_MILLISECOND 6
  18130. #define DUK__IDX_WEEKDAY 7 /* weekday: 0 to 6, 0=sunday, 1=monday, etc */
  18131. #define DUK__NUM_PARTS 8
  18132. /* Internal API call flags, used for various functions in this file.
  18133. * Certain flags are used by only certain functions, but since the flags
  18134. * don't overlap, a single flags value can be passed around to multiple
  18135. * functions.
  18136. *
  18137. * The unused top bits of the flags field are also used to pass values
  18138. * to helpers (duk__get_part_helper() and duk__set_part_helper()).
  18139. *
  18140. * (Must be in-sync with genbuiltins.py.)
  18141. */
  18142. #define DUK__FLAG_NAN_TO_ZERO (1 << 0) /* timeval breakdown: internal time value NaN -> zero */
  18143. #define DUK__FLAG_NAN_TO_RANGE_ERROR (1 << 1) /* timeval breakdown: internal time value NaN -> RangeError (toISOString) */
  18144. #define DUK__FLAG_ONEBASED (1 << 2) /* timeval breakdown: convert month and day-of-month parts to one-based (default is zero-based) */
  18145. #define DUK__FLAG_EQUIVYEAR (1 << 3) /* timeval breakdown: replace year with equivalent year in the [1971,2037] range for DST calculations */
  18146. #define DUK__FLAG_LOCALTIME (1 << 4) /* convert time value to local time */
  18147. #define DUK__FLAG_SUB1900 (1 << 5) /* getter: subtract 1900 from year when getting year part */
  18148. #define DUK__FLAG_TOSTRING_DATE (1 << 6) /* include date part in string conversion result */
  18149. #define DUK__FLAG_TOSTRING_TIME (1 << 7) /* include time part in string conversion result */
  18150. #define DUK__FLAG_TOSTRING_LOCALE (1 << 8) /* use locale specific formatting if available */
  18151. #define DUK__FLAG_TIMESETTER (1 << 9) /* setter: call is a time setter (affects hour, min, sec, ms); otherwise date setter (affects year, month, day-in-month) */
  18152. #define DUK__FLAG_YEAR_FIXUP (1 << 10) /* setter: perform 2-digit year fixup (00...99 -> 1900...1999) */
  18153. #define DUK__FLAG_SEP_T (1 << 11) /* string conversion: use 'T' instead of ' ' as a separator */
  18154. #define DUK__FLAG_VALUE_SHIFT 12 /* additional values begin at bit 12 */
  18155. /* Debug macro to print all parts and dparts (used manually because of debug level). */
  18156. #define DUK__DPRINT_PARTS_AND_DPARTS(parts,dparts) do { \
  18157. DUK_D(DUK_DPRINT("parts: %ld %ld %ld %ld %ld %ld %ld %ld, dparts: %lf %lf %lf %lf %lf %lf %lf %lf", \
  18158. (long) (parts)[0], (long) (parts)[1], \
  18159. (long) (parts)[2], (long) (parts)[3], \
  18160. (long) (parts)[4], (long) (parts)[5], \
  18161. (long) (parts)[6], (long) (parts)[7], \
  18162. (double) (dparts)[0], (double) (dparts)[1], \
  18163. (double) (dparts)[2], (double) (dparts)[3], \
  18164. (double) (dparts)[4], (double) (dparts)[5], \
  18165. (double) (dparts)[6], (double) (dparts)[7])); \
  18166. } while (0)
  18167. #define DUK__DPRINT_PARTS(parts) do { \
  18168. DUK_D(DUK_DPRINT("parts: %ld %ld %ld %ld %ld %ld %ld %ld", \
  18169. (long) (parts)[0], (long) (parts)[1], \
  18170. (long) (parts)[2], (long) (parts)[3], \
  18171. (long) (parts)[4], (long) (parts)[5], \
  18172. (long) (parts)[6], (long) (parts)[7])); \
  18173. } while (0)
  18174. #define DUK__DPRINT_DPARTS(dparts) do { \
  18175. DUK_D(DUK_DPRINT("dparts: %lf %lf %lf %lf %lf %lf %lf %lf", \
  18176. (double) (dparts)[0], (double) (dparts)[1], \
  18177. (double) (dparts)[2], (double) (dparts)[3], \
  18178. (double) (dparts)[4], (double) (dparts)[5], \
  18179. (double) (dparts)[6], (double) (dparts)[7])); \
  18180. } while (0)
  18181. /* Equivalent year for DST calculations outside [1970,2038[ range, see
  18182. * E5 Section 15.9.1.8. Equivalent year has the same leap-year-ness and
  18183. * starts with the same weekday on Jan 1.
  18184. * https://bugzilla.mozilla.org/show_bug.cgi?id=351066
  18185. */
  18186. #define DUK__YEAR(x) ((duk_uint8_t) ((x) - 1970))
  18187. DUK_LOCAL duk_uint8_t duk__date_equivyear[14] = {
  18188. #if 1
  18189. /* This is based on V8 EquivalentYear() algorithm (see src/genequivyear.py):
  18190. * http://code.google.com/p/v8/source/browse/trunk/src/date.h#146
  18191. */
  18192. /* non-leap year: sunday, monday, ... */
  18193. DUK__YEAR(2023), DUK__YEAR(2035), DUK__YEAR(2019), DUK__YEAR(2031),
  18194. DUK__YEAR(2015), DUK__YEAR(2027), DUK__YEAR(2011),
  18195. /* leap year: sunday, monday, ... */
  18196. DUK__YEAR(2012), DUK__YEAR(2024), DUK__YEAR(2008), DUK__YEAR(2020),
  18197. DUK__YEAR(2032), DUK__YEAR(2016), DUK__YEAR(2028)
  18198. #endif
  18199. #if 0
  18200. /* This is based on Rhino EquivalentYear() algorithm:
  18201. * https://github.com/mozilla/rhino/blob/f99cc11d616f0cdda2c42bde72b3484df6182947/src/org/mozilla/javascript/NativeDate.java
  18202. */
  18203. /* non-leap year: sunday, monday, ... */
  18204. DUK__YEAR(1978), DUK__YEAR(1973), DUK__YEAR(1985), DUK__YEAR(1986),
  18205. DUK__YEAR(1981), DUK__YEAR(1971), DUK__YEAR(1977),
  18206. /* leap year: sunday, monday, ... */
  18207. DUK__YEAR(1984), DUK__YEAR(1996), DUK__YEAR(1980), DUK__YEAR(1992),
  18208. DUK__YEAR(1976), DUK__YEAR(1988), DUK__YEAR(1972)
  18209. #endif
  18210. };
  18211. #undef DUK__YEAR
  18212. /*
  18213. * Platform specific helpers
  18214. */
  18215. #ifdef DUK_USE_DATE_NOW_GETTIMEOFDAY
  18216. /* Get current Ecmascript time (= UNIX/Posix time, but in milliseconds). */
  18217. DUK_INTERNAL duk_double_t duk_bi_date_get_now(duk_context *ctx) {
  18218. duk_hthread *thr = (duk_hthread *) ctx;
  18219. struct timeval tv;
  18220. duk_double_t d;
  18221. if (gettimeofday(&tv, NULL) != 0) {
  18222. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, "gettimeofday failed");
  18223. }
  18224. d = ((duk_double_t) tv.tv_sec) * 1000.0 +
  18225. ((duk_double_t) (tv.tv_usec / 1000));
  18226. DUK_ASSERT(DUK_FLOOR(d) == d); /* no fractions */
  18227. return d;
  18228. }
  18229. #endif /* DUK_USE_DATE_NOW_GETTIMEOFDAY */
  18230. #ifdef DUK_USE_DATE_NOW_TIME
  18231. /* Not a very good provider: only full seconds are available. */
  18232. DUK_INTERNAL duk_double_t duk_bi_date_get_now(duk_context *ctx) {
  18233. time_t t = time(NULL);
  18234. return ((duk_double_t) t) * 1000.0;
  18235. }
  18236. #endif /* DUK_USE_DATE_NOW_TIME */
  18237. #if defined(DUK_USE_DATE_NOW_WINDOWS) || defined(DUK_USE_DATE_TZO_WINDOWS)
  18238. /* Shared Windows helpers. */
  18239. DUK_LOCAL void duk__convert_systime_to_ularge(const SYSTEMTIME *st, ULARGE_INTEGER *res) {
  18240. FILETIME ft;
  18241. if (SystemTimeToFileTime(st, &ft) == 0) {
  18242. DUK_D(DUK_DPRINT("SystemTimeToFileTime() failed, returning 0"));
  18243. res->QuadPart = 0;
  18244. } else {
  18245. res->LowPart = ft.dwLowDateTime;
  18246. res->HighPart = ft.dwHighDateTime;
  18247. }
  18248. }
  18249. DUK_LOCAL void duk__set_systime_jan1970(SYSTEMTIME *st) {
  18250. DUK_MEMZERO((void *) st, sizeof(*st));
  18251. st->wYear = 1970;
  18252. st->wMonth = 1;
  18253. st->wDayOfWeek = 4; /* not sure whether or not needed; Thursday */
  18254. st->wDay = 1;
  18255. DUK_ASSERT(st->wHour == 0);
  18256. DUK_ASSERT(st->wMinute == 0);
  18257. DUK_ASSERT(st->wSecond == 0);
  18258. DUK_ASSERT(st->wMilliseconds == 0);
  18259. }
  18260. #endif /* defined(DUK_USE_DATE_NOW_WINDOWS) || defined(DUK_USE_DATE_TZO_WINDOWS) */
  18261. #ifdef DUK_USE_DATE_NOW_WINDOWS
  18262. DUK_INTERNAL duk_double_t duk_bi_date_get_now(duk_context *ctx) {
  18263. /* Suggested step-by-step method from documentation of RtlTimeToSecondsSince1970:
  18264. * http://msdn.microsoft.com/en-us/library/windows/desktop/ms724928(v=vs.85).aspx
  18265. */
  18266. SYSTEMTIME st1, st2;
  18267. ULARGE_INTEGER tmp1, tmp2;
  18268. DUK_UNREF(ctx);
  18269. GetSystemTime(&st1);
  18270. duk__convert_systime_to_ularge((const SYSTEMTIME *) &st1, &tmp1);
  18271. duk__set_systime_jan1970(&st2);
  18272. duk__convert_systime_to_ularge((const SYSTEMTIME *) &st2, &tmp2);
  18273. /* Difference is in 100ns units, convert to milliseconds w/o fractions */
  18274. return (duk_double_t) ((tmp1.QuadPart - tmp2.QuadPart) / 10000LL);
  18275. }
  18276. #endif /* DUK_USE_DATE_NOW_WINDOWS */
  18277. #if defined(DUK_USE_DATE_TZO_GMTIME) || defined(DUK_USE_DATE_TZO_GMTIME_R)
  18278. /* Get local time offset (in seconds) for a certain (UTC) instant 'd'. */
  18279. DUK_LOCAL duk_int_t duk__get_local_tzoffset(duk_double_t d) {
  18280. time_t t, t1, t2;
  18281. duk_int_t parts[DUK__NUM_PARTS];
  18282. duk_double_t dparts[DUK__NUM_PARTS];
  18283. struct tm tms[2];
  18284. #ifdef DUK_USE_DATE_TZO_GMTIME
  18285. struct tm *tm_ptr;
  18286. #endif
  18287. /* For NaN/inf, the return value doesn't matter. */
  18288. if (!DUK_ISFINITE(d)) {
  18289. return 0;
  18290. }
  18291. /* If not within Ecmascript range, some integer time calculations
  18292. * won't work correctly (and some asserts will fail), so bail out
  18293. * if so. This fixes test-bug-date-insane-setyear.js. There is
  18294. * a +/- 24h leeway in this range check to avoid a test262 corner
  18295. * case documented in test-bug-date-timeval-edges.js.
  18296. */
  18297. if (!duk__timeval_in_leeway_range(d)) {
  18298. DUK_DD(DUK_DDPRINT("timeval not within valid range, skip tzoffset computation to avoid integer overflows"));
  18299. return 0;
  18300. }
  18301. /*
  18302. * This is a bit tricky to implement portably. The result depends
  18303. * on the timestamp (specifically, DST depends on the timestamp).
  18304. * If e.g. UNIX APIs are used, they'll have portability issues with
  18305. * very small and very large years.
  18306. *
  18307. * Current approach:
  18308. *
  18309. * - Stay within portable UNIX limits by using equivalent year mapping.
  18310. * Avoid year 1970 and 2038 as some conversions start to fail, at
  18311. * least on some platforms. Avoiding 1970 means that there are
  18312. * currently DST discrepancies for 1970.
  18313. *
  18314. * - Create a UTC and local time breakdowns from 't'. Then create
  18315. * a time_t using gmtime() and localtime() and compute the time
  18316. * difference between the two.
  18317. *
  18318. * Equivalent year mapping (E5 Section 15.9.1.8):
  18319. *
  18320. * If the host environment provides functionality for determining
  18321. * daylight saving time, the implementation of ECMAScript is free
  18322. * to map the year in question to an equivalent year (same
  18323. * leap-year-ness and same starting week day for the year) for which
  18324. * the host environment provides daylight saving time information.
  18325. * The only restriction is that all equivalent years should produce
  18326. * the same result.
  18327. *
  18328. * This approach is quite reasonable but not entirely correct, e.g.
  18329. * the specification also states (E5 Section 15.9.1.8):
  18330. *
  18331. * The implementation of ECMAScript should not try to determine
  18332. * whether the exact time was subject to daylight saving time, but
  18333. * just whether daylight saving time would have been in effect if
  18334. * the _current daylight saving time algorithm_ had been used at the
  18335. * time. This avoids complications such as taking into account the
  18336. * years that the locale observed daylight saving time year round.
  18337. *
  18338. * Since we rely on the platform APIs for conversions between local
  18339. * time and UTC, we can't guarantee the above. Rather, if the platform
  18340. * has historical DST rules they will be applied. This seems to be the
  18341. * general preferred direction in Ecmascript standardization (or at least
  18342. * implementations) anyway, and even the equivalent year mapping should
  18343. * be disabled if the platform is known to handle DST properly for the
  18344. * full Ecmascript range.
  18345. *
  18346. * The following has useful discussion and links:
  18347. *
  18348. * https://bugzilla.mozilla.org/show_bug.cgi?id=351066
  18349. */
  18350. duk__timeval_to_parts(d, parts, dparts, DUK__FLAG_EQUIVYEAR /*flags*/);
  18351. DUK_ASSERT(parts[DUK__IDX_YEAR] >= 1970 && parts[DUK__IDX_YEAR] <= 2038);
  18352. d = duk__get_timeval_from_dparts(dparts, 0 /*flags*/);
  18353. DUK_ASSERT(d >= 0 && d < 2147483648.0 * 1000.0); /* unsigned 31-bit range */
  18354. t = (time_t) (d / 1000.0);
  18355. DUK_DDD(DUK_DDDPRINT("timeval: %lf -> time_t %ld", (double) d, (long) t));
  18356. t1 = t;
  18357. DUK_MEMZERO((void *) tms, sizeof(struct tm) * 2);
  18358. #if defined(DUK_USE_DATE_TZO_GMTIME_R)
  18359. (void) gmtime_r(&t, &tms[0]);
  18360. (void) localtime_r(&t, &tms[1]);
  18361. #elif defined(DUK_USE_DATE_TZO_GMTIME)
  18362. tm_ptr = gmtime(&t);
  18363. DUK_MEMCPY((void *) &tms[0], tm_ptr, sizeof(struct tm));
  18364. tm_ptr = localtime(&t);
  18365. DUK_MEMCPY((void *) &tms[1], tm_ptr, sizeof(struct tm));
  18366. #else
  18367. #error internal error
  18368. #endif
  18369. DUK_DDD(DUK_DDDPRINT("gmtime result: tm={sec:%ld,min:%ld,hour:%ld,mday:%ld,mon:%ld,year:%ld,"
  18370. "wday:%ld,yday:%ld,isdst:%ld}",
  18371. (long) tms[0].tm_sec, (long) tms[0].tm_min, (long) tms[0].tm_hour,
  18372. (long) tms[0].tm_mday, (long) tms[0].tm_mon, (long) tms[0].tm_year,
  18373. (long) tms[0].tm_wday, (long) tms[0].tm_yday, (long) tms[0].tm_isdst));
  18374. DUK_DDD(DUK_DDDPRINT("localtime result: tm={sec:%ld,min:%ld,hour:%ld,mday:%ld,mon:%ld,year:%ld,"
  18375. "wday:%ld,yday:%ld,isdst:%ld}",
  18376. (long) tms[1].tm_sec, (long) tms[1].tm_min, (long) tms[1].tm_hour,
  18377. (long) tms[1].tm_mday, (long) tms[1].tm_mon, (long) tms[1].tm_year,
  18378. (long) tms[1].tm_wday, (long) tms[1].tm_yday, (long) tms[1].tm_isdst));
  18379. t1 = mktime(&tms[0]); /* UTC */
  18380. t2 = mktime(&tms[1]); /* local */
  18381. if (t1 == (time_t) -1 || t2 == (time_t) -1) {
  18382. /* This check used to be for (t < 0) but on some platforms
  18383. * time_t is unsigned and apparently the proper way to detect
  18384. * an mktime() error return is the cast above. See e.g.:
  18385. * http://pubs.opengroup.org/onlinepubs/009695299/functions/mktime.html
  18386. */
  18387. goto error;
  18388. }
  18389. if (tms[1].tm_isdst > 0) {
  18390. t2 += 3600;
  18391. } else if (tms[1].tm_isdst < 0) {
  18392. DUK_D(DUK_DPRINT("tm_isdst is negative: %d", (int) tms[1].tm_isdst));
  18393. }
  18394. DUK_DDD(DUK_DDDPRINT("t1=%ld (utc), t2=%ld (local)", (long) t1, (long) t2));
  18395. /* Compute final offset in seconds, positive if local time ahead of
  18396. * UTC (returned value is UTC-to-local offset).
  18397. *
  18398. * difftime() returns a double, so coercion to int generates quite
  18399. * a lot of code. Direct subtraction is not portable, however.
  18400. * XXX: allow direct subtraction on known platforms.
  18401. */
  18402. #if 0
  18403. return (duk_int_t) (t2 - t1);
  18404. #endif
  18405. return (duk_int_t) difftime(t2, t1);
  18406. error:
  18407. /* XXX: return something more useful, so that caller can throw? */
  18408. DUK_D(DUK_DPRINT("mktime() failed, d=%lf", (double) d));
  18409. return 0;
  18410. }
  18411. #endif /* DUK_USE_DATE_TZO_GMTIME */
  18412. #if defined(DUK_USE_DATE_TZO_WINDOWS)
  18413. DUK_LOCAL duk_int_t duk__get_local_tzoffset(duk_double_t d) {
  18414. SYSTEMTIME st1;
  18415. SYSTEMTIME st2;
  18416. SYSTEMTIME st3;
  18417. ULARGE_INTEGER tmp1;
  18418. ULARGE_INTEGER tmp2;
  18419. ULARGE_INTEGER tmp3;
  18420. FILETIME ft1;
  18421. /* XXX: handling of timestamps outside Windows supported range.
  18422. * How does Windows deal with dates before 1600? Does windows
  18423. * support all Ecmascript years (like -200000 and +200000)?
  18424. * Should equivalent year mapping be used here too? If so, use
  18425. * a shared helper (currently integrated into timeval-to-parts).
  18426. */
  18427. /* Use the approach described in "Remarks" of FileTimeToLocalFileTime:
  18428. * http://msdn.microsoft.com/en-us/library/windows/desktop/ms724277(v=vs.85).aspx
  18429. */
  18430. duk__set_systime_jan1970(&st1);
  18431. duk__convert_systime_to_ularge((const SYSTEMTIME *) &st1, &tmp1);
  18432. tmp2.QuadPart = (ULONGLONG) (d * 10000.0); /* millisec -> 100ns units since jan 1, 1970 */
  18433. tmp2.QuadPart += tmp1.QuadPart; /* input 'd' in Windows UTC, 100ns units */
  18434. ft1.dwLowDateTime = tmp2.LowPart;
  18435. ft1.dwHighDateTime = tmp2.HighPart;
  18436. FileTimeToSystemTime((const FILETIME *) &ft1, &st2);
  18437. if (SystemTimeToTzSpecificLocalTime((LPTIME_ZONE_INFORMATION) NULL, &st2, &st3) == 0) {
  18438. DUK_D(DUK_DPRINT("SystemTimeToTzSpecificLocalTime() failed, return tzoffset 0"));
  18439. return 0;
  18440. }
  18441. duk__convert_systime_to_ularge((const SYSTEMTIME *) &st3, &tmp3);
  18442. /* Positive if local time ahead of UTC. */
  18443. return (duk_int_t) (((LONGLONG) tmp3.QuadPart - (LONGLONG) tmp2.QuadPart) / 10000000LL); /* seconds */
  18444. }
  18445. #endif /* DUK_USE_DATE_TZO_WINDOWS */
  18446. #ifdef DUK_USE_DATE_PRS_STRPTIME
  18447. DUK_LOCAL duk_bool_t duk__parse_string_strptime(duk_context *ctx, const char *str) {
  18448. struct tm tm;
  18449. time_t t;
  18450. char buf[DUK__STRPTIME_BUF_SIZE];
  18451. /* copy to buffer with spare to avoid Valgrind gripes from strptime */
  18452. DUK_ASSERT(str != NULL);
  18453. DUK_MEMZERO(buf, sizeof(buf)); /* valgrind whine without this */
  18454. DUK_SNPRINTF(buf, sizeof(buf), "%s", (const char *) str);
  18455. buf[sizeof(buf) - 1] = (char) 0;
  18456. DUK_DDD(DUK_DDDPRINT("parsing: '%s'", (const char *) buf));
  18457. DUK_MEMZERO(&tm, sizeof(tm));
  18458. if (strptime((const char *) buf, "%c", &tm) != NULL) {
  18459. DUK_DDD(DUK_DDDPRINT("before mktime: tm={sec:%ld,min:%ld,hour:%ld,mday:%ld,mon:%ld,year:%ld,"
  18460. "wday:%ld,yday:%ld,isdst:%ld}",
  18461. (long) tm.tm_sec, (long) tm.tm_min, (long) tm.tm_hour,
  18462. (long) tm.tm_mday, (long) tm.tm_mon, (long) tm.tm_year,
  18463. (long) tm.tm_wday, (long) tm.tm_yday, (long) tm.tm_isdst));
  18464. tm.tm_isdst = -1; /* negative: dst info not available */
  18465. t = mktime(&tm);
  18466. DUK_DDD(DUK_DDDPRINT("mktime() -> %ld", (long) t));
  18467. if (t >= 0) {
  18468. duk_push_number(ctx, ((duk_double_t) t) * 1000.0);
  18469. return 1;
  18470. }
  18471. }
  18472. return 0;
  18473. }
  18474. #endif /* DUK_USE_DATE_PRS_STRPTIME */
  18475. #ifdef DUK_USE_DATE_PRS_GETDATE
  18476. DUK_LOCAL duk_bool_t duk__parse_string_getdate(duk_context *ctx, const char *str) {
  18477. struct tm tm;
  18478. duk_small_int_t rc;
  18479. time_t t;
  18480. /* For this to work, DATEMSK must be set, so this is not very
  18481. * convenient for an embeddable interpreter.
  18482. */
  18483. DUK_MEMZERO(&tm, sizeof(struct tm));
  18484. rc = (duk_small_int_t) getdate_r(str, &tm);
  18485. DUK_DDD(DUK_DDDPRINT("getdate_r() -> %ld", (long) rc));
  18486. if (rc == 0) {
  18487. t = mktime(&tm);
  18488. DUK_DDD(DUK_DDDPRINT("mktime() -> %ld", (long) t));
  18489. if (t >= 0) {
  18490. duk_push_number(ctx, (duk_double_t) t);
  18491. return 1;
  18492. }
  18493. }
  18494. return 0;
  18495. }
  18496. #endif /* DUK_USE_DATE_PRS_GETDATE */
  18497. #ifdef DUK_USE_DATE_FMT_STRFTIME
  18498. DUK_LOCAL duk_bool_t duk__format_parts_strftime(duk_context *ctx, duk_int_t *parts, duk_int_t tzoffset, duk_small_uint_t flags) {
  18499. char buf[DUK__STRFTIME_BUF_SIZE];
  18500. struct tm tm;
  18501. const char *fmt;
  18502. DUK_UNREF(tzoffset);
  18503. /* If the platform doesn't support the entire Ecmascript range, we need
  18504. * to return 0 so that the caller can fall back to the default formatter.
  18505. *
  18506. * For now, assume that if time_t is 8 bytes or more, the whole Ecmascript
  18507. * range is supported. For smaller time_t values (4 bytes in practice),
  18508. * assumes that the signed 32-bit range is supported.
  18509. *
  18510. * XXX: detect this more correctly per platform. The size of time_t is
  18511. * probably not an accurate guarantee of strftime() supporting or not
  18512. * supporting a large time range (the full Ecmascript range).
  18513. */
  18514. if (sizeof(time_t) < 8 &&
  18515. (parts[DUK__IDX_YEAR] < 1970 || parts[DUK__IDX_YEAR] > 2037)) {
  18516. /* be paranoid for 32-bit time values (even avoiding negative ones) */
  18517. return 0;
  18518. }
  18519. DUK_MEMZERO(&tm, sizeof(tm));
  18520. tm.tm_sec = parts[DUK__IDX_SECOND];
  18521. tm.tm_min = parts[DUK__IDX_MINUTE];
  18522. tm.tm_hour = parts[DUK__IDX_HOUR];
  18523. tm.tm_mday = parts[DUK__IDX_DAY]; /* already one-based */
  18524. tm.tm_mon = parts[DUK__IDX_MONTH] - 1; /* one-based -> zero-based */
  18525. tm.tm_year = parts[DUK__IDX_YEAR] - 1900;
  18526. tm.tm_wday = parts[DUK__IDX_WEEKDAY];
  18527. tm.tm_isdst = 0;
  18528. DUK_MEMZERO(buf, sizeof(buf));
  18529. if ((flags & DUK__FLAG_TOSTRING_DATE) && (flags & DUK__FLAG_TOSTRING_TIME)) {
  18530. fmt = "%c";
  18531. } else if (flags & DUK__FLAG_TOSTRING_DATE) {
  18532. fmt = "%x";
  18533. } else {
  18534. DUK_ASSERT(flags & DUK__FLAG_TOSTRING_TIME);
  18535. fmt = "%X";
  18536. }
  18537. (void) strftime(buf, sizeof(buf) - 1, fmt, &tm);
  18538. DUK_ASSERT(buf[sizeof(buf) - 1] == 0);
  18539. duk_push_string(ctx, buf);
  18540. return 1;
  18541. }
  18542. #endif /* DUK_USE_DATE_FMT_STRFTIME */
  18543. /*
  18544. * ISO 8601 subset parser.
  18545. */
  18546. /* Parser part count. */
  18547. #define DUK__NUM_ISO8601_PARSER_PARTS 9
  18548. /* Parser part indices. */
  18549. #define DUK__PI_YEAR 0
  18550. #define DUK__PI_MONTH 1
  18551. #define DUK__PI_DAY 2
  18552. #define DUK__PI_HOUR 3
  18553. #define DUK__PI_MINUTE 4
  18554. #define DUK__PI_SECOND 5
  18555. #define DUK__PI_MILLISECOND 6
  18556. #define DUK__PI_TZHOUR 7
  18557. #define DUK__PI_TZMINUTE 8
  18558. /* Parser part masks. */
  18559. #define DUK__PM_YEAR (1 << DUK__PI_YEAR)
  18560. #define DUK__PM_MONTH (1 << DUK__PI_MONTH)
  18561. #define DUK__PM_DAY (1 << DUK__PI_DAY)
  18562. #define DUK__PM_HOUR (1 << DUK__PI_HOUR)
  18563. #define DUK__PM_MINUTE (1 << DUK__PI_MINUTE)
  18564. #define DUK__PM_SECOND (1 << DUK__PI_SECOND)
  18565. #define DUK__PM_MILLISECOND (1 << DUK__PI_MILLISECOND)
  18566. #define DUK__PM_TZHOUR (1 << DUK__PI_TZHOUR)
  18567. #define DUK__PM_TZMINUTE (1 << DUK__PI_TZMINUTE)
  18568. /* Parser separator indices. */
  18569. #define DUK__SI_PLUS 0
  18570. #define DUK__SI_MINUS 1
  18571. #define DUK__SI_T 2
  18572. #define DUK__SI_SPACE 3
  18573. #define DUK__SI_COLON 4
  18574. #define DUK__SI_PERIOD 5
  18575. #define DUK__SI_Z 6
  18576. #define DUK__SI_NUL 7
  18577. /* Parser separator masks. */
  18578. #define DUK__SM_PLUS (1 << DUK__SI_PLUS)
  18579. #define DUK__SM_MINUS (1 << DUK__SI_MINUS)
  18580. #define DUK__SM_T (1 << DUK__SI_T)
  18581. #define DUK__SM_SPACE (1 << DUK__SI_SPACE)
  18582. #define DUK__SM_COLON (1 << DUK__SI_COLON)
  18583. #define DUK__SM_PERIOD (1 << DUK__SI_PERIOD)
  18584. #define DUK__SM_Z (1 << DUK__SI_Z)
  18585. #define DUK__SM_NUL (1 << DUK__SI_NUL)
  18586. /* Rule control flags. */
  18587. #define DUK__CF_NEG (1 << 0) /* continue matching, set neg_tzoffset flag */
  18588. #define DUK__CF_ACCEPT (1 << 1) /* accept string */
  18589. #define DUK__CF_ACCEPT_NUL (1 << 2) /* accept string if next char is NUL (otherwise reject) */
  18590. #define DUK__PACK_RULE(partmask,sepmask,nextpart,flags) \
  18591. ((duk_uint32_t) (partmask) + \
  18592. (((duk_uint32_t) (sepmask)) << 9) + \
  18593. (((duk_uint32_t) (nextpart)) << 17) + \
  18594. (((duk_uint32_t) (flags)) << 21))
  18595. #define DUK__UNPACK_RULE(rule,var_nextidx,var_flags) do { \
  18596. (var_nextidx) = (duk_small_uint_t) (((rule) >> 17) & 0x0f); \
  18597. (var_flags) = (duk_small_uint_t) ((rule) >> 21); \
  18598. } while (0)
  18599. #define DUK__RULE_MASK_PART_SEP 0x1ffffUL
  18600. /* Matching separator index is used in the control table */
  18601. DUK_LOCAL const duk_uint8_t duk__parse_iso8601_seps[] = {
  18602. DUK_ASC_PLUS /*0*/, DUK_ASC_MINUS /*1*/, DUK_ASC_UC_T /*2*/, DUK_ASC_SPACE /*3*/,
  18603. DUK_ASC_COLON /*4*/, DUK_ASC_PERIOD /*5*/, DUK_ASC_UC_Z /*6*/, DUK_ASC_NUL /*7*/
  18604. };
  18605. /* Rule table: first matching rule is used to determine what to do next. */
  18606. DUK_LOCAL const duk_uint32_t duk__parse_iso8601_control[] = {
  18607. DUK__PACK_RULE(DUK__PM_YEAR, DUK__SM_MINUS, DUK__PI_MONTH, 0),
  18608. DUK__PACK_RULE(DUK__PM_MONTH, DUK__SM_MINUS, DUK__PI_DAY, 0),
  18609. DUK__PACK_RULE(DUK__PM_YEAR | DUK__PM_MONTH | DUK__PM_DAY, DUK__SM_T | DUK__SM_SPACE, DUK__PI_HOUR, 0),
  18610. DUK__PACK_RULE(DUK__PM_HOUR, DUK__SM_COLON, DUK__PI_MINUTE, 0),
  18611. DUK__PACK_RULE(DUK__PM_MINUTE, DUK__SM_COLON, DUK__PI_SECOND, 0),
  18612. DUK__PACK_RULE(DUK__PM_SECOND, DUK__SM_PERIOD, DUK__PI_MILLISECOND, 0),
  18613. DUK__PACK_RULE(DUK__PM_TZHOUR, DUK__SM_COLON, DUK__PI_TZMINUTE, 0),
  18614. DUK__PACK_RULE(DUK__PM_YEAR | DUK__PM_MONTH | DUK__PM_DAY | DUK__PM_HOUR /*Note1*/ | DUK__PM_MINUTE | DUK__PM_SECOND | DUK__PM_MILLISECOND, DUK__SM_PLUS, DUK__PI_TZHOUR, 0),
  18615. DUK__PACK_RULE(DUK__PM_YEAR | DUK__PM_MONTH | DUK__PM_DAY | DUK__PM_HOUR /*Note1*/ | DUK__PM_MINUTE | DUK__PM_SECOND | DUK__PM_MILLISECOND, DUK__SM_MINUS, DUK__PI_TZHOUR, DUK__CF_NEG),
  18616. DUK__PACK_RULE(DUK__PM_YEAR | DUK__PM_MONTH | DUK__PM_DAY | DUK__PM_HOUR /*Note1*/ | DUK__PM_MINUTE | DUK__PM_SECOND | DUK__PM_MILLISECOND, DUK__SM_Z, 0, DUK__CF_ACCEPT_NUL),
  18617. DUK__PACK_RULE(DUK__PM_YEAR | DUK__PM_MONTH | DUK__PM_DAY | DUK__PM_HOUR /*Note1*/ | DUK__PM_MINUTE | DUK__PM_SECOND | DUK__PM_MILLISECOND | DUK__PM_TZHOUR /*Note2*/ | DUK__PM_TZMINUTE, DUK__SM_NUL, 0, DUK__CF_ACCEPT)
  18618. /* Note1: the specification doesn't require matching a time form with
  18619. * just hours ("HH"), but we accept it here, e.g. "2012-01-02T12Z".
  18620. *
  18621. * Note2: the specification doesn't require matching a timezone offset
  18622. * with just hours ("HH"), but accept it here, e.g. "2012-01-02T03:04:05+02"
  18623. */
  18624. };
  18625. DUK_LOCAL duk_bool_t duk__parse_string_iso8601_subset(duk_context *ctx, const char *str) {
  18626. duk_int_t parts[DUK__NUM_ISO8601_PARSER_PARTS];
  18627. duk_double_t dparts[DUK__NUM_PARTS];
  18628. duk_double_t d;
  18629. const duk_uint8_t *p;
  18630. duk_small_uint_t part_idx = 0;
  18631. duk_int_t accum = 0;
  18632. duk_small_uint_t ndigits = 0;
  18633. duk_bool_t neg_year = 0;
  18634. duk_bool_t neg_tzoffset = 0;
  18635. duk_uint_fast8_t ch;
  18636. duk_small_uint_t i;
  18637. /* During parsing, month and day are one-based; set defaults here. */
  18638. DUK_MEMZERO(parts, sizeof(parts));
  18639. DUK_ASSERT(parts[DUK__IDX_YEAR] == 0); /* don't care value, year is mandatory */
  18640. parts[DUK__IDX_MONTH] = 1;
  18641. parts[DUK__IDX_DAY] = 1;
  18642. /* Special handling for year sign. */
  18643. p = (const duk_uint8_t *) str;
  18644. ch = p[0];
  18645. if (ch == DUK_ASC_PLUS) {
  18646. p++;
  18647. } else if (ch == DUK_ASC_MINUS) {
  18648. neg_year = 1;
  18649. p++;
  18650. }
  18651. for (;;) {
  18652. ch = *p++;
  18653. DUK_DDD(DUK_DDDPRINT("parsing, part_idx=%ld, char=%ld ('%c')",
  18654. (long) part_idx, (long) ch,
  18655. (int) ((ch >= 0x20 && ch <= 0x7e) ? ch : DUK_ASC_QUESTION)));
  18656. if (ch >= DUK_ASC_0 && ch <= DUK_ASC_9) {
  18657. if (ndigits >= 9) {
  18658. DUK_DDD(DUK_DDDPRINT("too many digits -> reject"));
  18659. goto reject;
  18660. }
  18661. if (part_idx == DUK__PI_MILLISECOND /*msec*/ && ndigits >= 3) {
  18662. /* ignore millisecond fractions after 3 */
  18663. } else {
  18664. accum = accum * 10 + ((duk_int_t) ch) - ((duk_int_t) DUK_ASC_0) + 0x00;
  18665. ndigits++;
  18666. }
  18667. } else {
  18668. duk_uint_fast32_t match_val;
  18669. duk_small_int_t sep_idx;
  18670. if (ndigits <= 0) {
  18671. goto reject;
  18672. }
  18673. if (part_idx == DUK__PI_MILLISECOND) {
  18674. /* complete the millisecond field */
  18675. while (ndigits < 3) {
  18676. accum *= 10;
  18677. ndigits++;
  18678. }
  18679. }
  18680. parts[part_idx] = accum;
  18681. DUK_DDD(DUK_DDDPRINT("wrote part %ld -> value %ld", (long) part_idx, (long) accum));
  18682. accum = 0;
  18683. ndigits = 0;
  18684. for (i = 0; i < (duk_small_uint_t) (sizeof(duk__parse_iso8601_seps) / sizeof(duk_uint8_t)); i++) {
  18685. if (duk__parse_iso8601_seps[i] == ch) {
  18686. break;
  18687. }
  18688. }
  18689. if (i == (duk_small_uint_t) (sizeof(duk__parse_iso8601_seps) / sizeof(duk_uint8_t))) {
  18690. DUK_DDD(DUK_DDDPRINT("separator character doesn't match -> reject"));
  18691. goto reject;
  18692. }
  18693. sep_idx = i;
  18694. match_val = (1UL << part_idx) + (1UL << (sep_idx + 9)); /* match against rule part/sep bits */
  18695. for (i = 0; i < (duk_small_uint_t) (sizeof(duk__parse_iso8601_control) / sizeof(duk_uint32_t)); i++) {
  18696. duk_uint_fast32_t rule = duk__parse_iso8601_control[i];
  18697. duk_small_uint_t nextpart;
  18698. duk_small_uint_t cflags;
  18699. DUK_DDD(DUK_DDDPRINT("part_idx=%ld, sep_idx=%ld, match_val=0x%08lx, considering rule=0x%08lx",
  18700. (long) part_idx, (long) sep_idx,
  18701. (unsigned long) match_val, (unsigned long) rule));
  18702. if ((rule & match_val) != match_val) {
  18703. continue;
  18704. }
  18705. DUK__UNPACK_RULE(rule, nextpart, cflags);
  18706. DUK_DDD(DUK_DDDPRINT("rule match -> part_idx=%ld, sep_idx=%ld, match_val=0x%08lx, "
  18707. "rule=0x%08lx -> nextpart=%ld, cflags=0x%02lx",
  18708. (long) part_idx, (long) sep_idx,
  18709. (unsigned long) match_val, (unsigned long) rule,
  18710. (long) nextpart, (unsigned long) cflags));
  18711. if (cflags & DUK__CF_NEG) {
  18712. neg_tzoffset = 1;
  18713. }
  18714. if (cflags & DUK__CF_ACCEPT) {
  18715. goto accept;
  18716. }
  18717. if (cflags & DUK__CF_ACCEPT_NUL) {
  18718. DUK_ASSERT(*(p - 1) != (char) 0);
  18719. if (*p == DUK_ASC_NUL) {
  18720. goto accept;
  18721. }
  18722. goto reject;
  18723. }
  18724. part_idx = nextpart;
  18725. break;
  18726. } /* rule match */
  18727. if (i == (duk_small_uint_t) (sizeof(duk__parse_iso8601_control) / sizeof(duk_uint32_t))) {
  18728. DUK_DDD(DUK_DDDPRINT("no rule matches -> reject"));
  18729. goto reject;
  18730. }
  18731. if (ch == 0) {
  18732. /* This shouldn't be necessary, but check just in case
  18733. * to avoid any chance of overruns.
  18734. */
  18735. DUK_DDD(DUK_DDDPRINT("NUL after rule matching (should not happen) -> reject"));
  18736. goto reject;
  18737. }
  18738. } /* if-digit-else-ctrl */
  18739. } /* char loop */
  18740. /* We should never exit the loop above, but if we do, reject
  18741. * by falling through.
  18742. */
  18743. DUK_DDD(DUK_DDDPRINT("fell out of char loop without explicit accept/reject -> reject"));
  18744. reject:
  18745. DUK_DDD(DUK_DDDPRINT("reject"));
  18746. return 0;
  18747. accept:
  18748. DUK_DDD(DUK_DDDPRINT("accept"));
  18749. /* Apply timezone offset to get the main parts in UTC */
  18750. if (neg_year) {
  18751. parts[DUK__PI_YEAR] = -parts[DUK__PI_YEAR];
  18752. }
  18753. if (neg_tzoffset) {
  18754. parts[DUK__PI_HOUR] += parts[DUK__PI_TZHOUR];
  18755. parts[DUK__PI_MINUTE] += parts[DUK__PI_TZMINUTE];
  18756. } else {
  18757. parts[DUK__PI_HOUR] -= parts[DUK__PI_TZHOUR];
  18758. parts[DUK__PI_MINUTE] -= parts[DUK__PI_TZMINUTE];
  18759. }
  18760. parts[DUK__PI_MONTH] -= 1; /* zero-based month */
  18761. parts[DUK__PI_DAY] -= 1; /* zero-based day */
  18762. /* Use double parts, they tolerate unnormalized time.
  18763. *
  18764. * Note: DUK__IDX_WEEKDAY is initialized with a bogus value (DUK__PI_TZHOUR)
  18765. * on purpose. It won't be actually used by duk__get_timeval_from_dparts(),
  18766. * but will make the value initialized just in case, and avoid any
  18767. * potential for Valgrind issues.
  18768. */
  18769. for (i = 0; i < DUK__NUM_PARTS; i++) {
  18770. DUK_DDD(DUK_DDDPRINT("part[%ld] = %ld", (long) i, (long) parts[i]));
  18771. dparts[i] = parts[i];
  18772. }
  18773. d = duk__get_timeval_from_dparts(dparts, 0 /*flags*/);
  18774. duk_push_number(ctx, d);
  18775. return 1;
  18776. }
  18777. /*
  18778. * Date/time parsing helper.
  18779. *
  18780. * Parse a datetime string into a time value. We must first try to parse
  18781. * the input according to the standard format in E5.1 Section 15.9.1.15.
  18782. * If that fails, we can try to parse using custom parsing, which can
  18783. * either be platform neutral (custom code) or platform specific (using
  18784. * existing platform API calls).
  18785. *
  18786. * Note in particular that we must parse whatever toString(), toUTCString(),
  18787. * and toISOString() can produce; see E5.1 Section 15.9.4.2.
  18788. *
  18789. * Returns 1 to allow tailcalling.
  18790. *
  18791. * There is much room for improvement here with respect to supporting
  18792. * alternative datetime formats. For instance, V8 parses '2012-01-01' as
  18793. * UTC and '2012/01/01' as local time.
  18794. */
  18795. DUK_LOCAL duk_ret_t duk__parse_string(duk_context *ctx, const char *str) {
  18796. /* XXX: there is a small risk here: because the ISO 8601 parser is
  18797. * very loose, it may end up parsing some datetime values which
  18798. * would be better parsed with a platform specific parser.
  18799. */
  18800. DUK_ASSERT(str != NULL);
  18801. DUK_DDD(DUK_DDDPRINT("parse datetime from string '%s'", (const char *) str));
  18802. if (duk__parse_string_iso8601_subset(ctx, str) != 0) {
  18803. return 1;
  18804. }
  18805. #if defined(DUK_USE_DATE_PRS_STRPTIME)
  18806. if (duk__parse_string_strptime(ctx, str) != 0) {
  18807. return 1;
  18808. }
  18809. #elif defined(DUK_USE_DATE_PRS_GETDATE)
  18810. if (duk__parse_string_getdate(ctx, str) != 0) {
  18811. return 1;
  18812. }
  18813. #else
  18814. /* No platform-specific parsing, this is not an error. */
  18815. #endif
  18816. duk_push_nan(ctx);
  18817. return 1;
  18818. }
  18819. /*
  18820. * Calendar helpers
  18821. *
  18822. * Some helpers are used for getters and can operate on normalized values
  18823. * which can be represented with 32-bit signed integers. Other helpers are
  18824. * needed by setters and operate on un-normalized double values, must watch
  18825. * out for non-finite numbers etc.
  18826. */
  18827. DUK_LOCAL duk_uint8_t duk__days_in_month[12] = {
  18828. (duk_uint8_t) 31, (duk_uint8_t) 28, (duk_uint8_t) 31, (duk_uint8_t) 30,
  18829. (duk_uint8_t) 31, (duk_uint8_t) 30, (duk_uint8_t) 31, (duk_uint8_t) 31,
  18830. (duk_uint8_t) 30, (duk_uint8_t) 31, (duk_uint8_t) 30, (duk_uint8_t) 31
  18831. };
  18832. /* Maximum iteration count for computing UTC-to-local time offset when
  18833. * creating an Ecmascript time value from local parts.
  18834. */
  18835. #define DUK__LOCAL_TZOFFSET_MAXITER 4
  18836. /* Because 'day since epoch' can be negative and is used to compute weekday
  18837. * using a modulo operation, add this multiple of 7 to avoid negative values
  18838. * when year is below 1970 epoch. Ecmascript time values are restricted to
  18839. * +/- 100 million days from epoch, so this adder fits nicely into 32 bits.
  18840. * Round to a multiple of 7 (= floor(100000000 / 7) * 7) and add margin.
  18841. */
  18842. #define DUK__WEEKDAY_MOD_ADDER (20000000 * 7) /* 0x08583b00 */
  18843. DUK_LOCAL duk_bool_t duk__is_leap_year(duk_int_t year) {
  18844. if ((year % 4) != 0) {
  18845. return 0;
  18846. }
  18847. if ((year % 100) != 0) {
  18848. return 1;
  18849. }
  18850. if ((year % 400) != 0) {
  18851. return 0;
  18852. }
  18853. return 1;
  18854. }
  18855. DUK_LOCAL duk_bool_t duk__timeval_in_valid_range(duk_double_t x) {
  18856. return (x >= -DUK__MS_100M_DAYS && x <= DUK__MS_100M_DAYS);
  18857. }
  18858. DUK_LOCAL duk_bool_t duk__timeval_in_leeway_range(duk_double_t x) {
  18859. return (x >= -DUK__MS_100M_DAYS_LEEWAY && x <= DUK__MS_100M_DAYS_LEEWAY);
  18860. }
  18861. DUK_LOCAL duk_bool_t duk__year_in_valid_range(duk_double_t x) {
  18862. return (x >= DUK__MIN_ECMA_YEAR && x <= DUK__MAX_ECMA_YEAR);
  18863. }
  18864. DUK_LOCAL duk_double_t duk__timeclip(duk_double_t x) {
  18865. if (!DUK_ISFINITE(x)) {
  18866. return DUK_DOUBLE_NAN;
  18867. }
  18868. if (!duk__timeval_in_valid_range(x)) {
  18869. return DUK_DOUBLE_NAN;
  18870. }
  18871. x = duk_js_tointeger_number(x);
  18872. /* Here we'd have the option to normalize -0 to +0. */
  18873. return x;
  18874. }
  18875. /* Integer division which floors also negative values correctly. */
  18876. DUK_LOCAL duk_int_t duk__div_floor(duk_int_t a, duk_int_t b) {
  18877. DUK_ASSERT(b > 0);
  18878. if (a >= 0) {
  18879. return a / b;
  18880. } else {
  18881. /* e.g. a = -4, b = 5 --> -4 - 5 + 1 / 5 --> -8 / 5 --> -1
  18882. * a = -5, b = 5 --> -5 - 5 + 1 / 5 --> -9 / 5 --> -1
  18883. * a = -6, b = 5 --> -6 - 5 + 1 / 5 --> -10 / 5 --> -2
  18884. */
  18885. return (a - b + 1) / b;
  18886. }
  18887. }
  18888. /* Compute day number of the first day of a given year. */
  18889. DUK_LOCAL duk_int_t duk__day_from_year(duk_int_t year) {
  18890. /* Note: in integer arithmetic, (x / 4) is same as floor(x / 4) for non-negative
  18891. * values, but is incorrect for negative ones.
  18892. */
  18893. return 365 * (year - 1970)
  18894. + duk__div_floor(year - 1969, 4)
  18895. - duk__div_floor(year - 1901, 100)
  18896. + duk__div_floor(year - 1601, 400);
  18897. }
  18898. /* Given a day number, determine year and day-within-year. */
  18899. DUK_LOCAL duk_int_t duk__year_from_day(duk_int_t day, duk_small_int_t *out_day_within_year) {
  18900. duk_int_t year;
  18901. duk_int_t diff_days;
  18902. /* estimate year upwards (towards positive infinity), then back down;
  18903. * two iterations should be enough
  18904. */
  18905. if (day >= 0) {
  18906. year = 1970 + day / 365;
  18907. } else {
  18908. year = 1970 + day / 366;
  18909. }
  18910. for (;;) {
  18911. diff_days = duk__day_from_year(year) - day;
  18912. DUK_DDD(DUK_DDDPRINT("year=%ld day=%ld, diff_days=%ld", (long) year, (long) day, (long) diff_days));
  18913. if (diff_days <= 0) {
  18914. DUK_ASSERT(-diff_days < 366); /* fits into duk_small_int_t */
  18915. *out_day_within_year = -diff_days;
  18916. DUK_DDD(DUK_DDDPRINT("--> year=%ld, day-within-year=%ld",
  18917. (long) year, (long) *out_day_within_year));
  18918. DUK_ASSERT(*out_day_within_year >= 0);
  18919. DUK_ASSERT(*out_day_within_year < (duk__is_leap_year(year) ? 366 : 365));
  18920. return year;
  18921. }
  18922. /* Note: this is very tricky; we must never 'overshoot' the
  18923. * correction downwards.
  18924. */
  18925. year -= 1 + (diff_days - 1) / 366; /* conservative */
  18926. }
  18927. }
  18928. /* Given a (year, month, day-within-month) triple, compute day number.
  18929. * The input triple is un-normalized and may contain non-finite values.
  18930. */
  18931. DUK_LOCAL duk_double_t duk__make_day(duk_double_t year, duk_double_t month, duk_double_t day) {
  18932. duk_int_t day_num;
  18933. duk_bool_t is_leap;
  18934. duk_small_int_t i, n;
  18935. /* Assume that year, month, day are all coerced to whole numbers.
  18936. * They may also be NaN or infinity, in which case this function
  18937. * must return NaN or infinity to ensure time value becomes NaN.
  18938. * If 'day' is NaN, the final return will end up returning a NaN,
  18939. * so it doesn't need to be checked here.
  18940. */
  18941. if (!DUK_ISFINITE(year) || !DUK_ISFINITE(month)) {
  18942. return DUK_DOUBLE_NAN;
  18943. }
  18944. year += DUK_FLOOR(month / 12.0);
  18945. month = DUK_FMOD(month, 12.0);
  18946. if (month < 0.0) {
  18947. /* handle negative values */
  18948. month += 12.0;
  18949. }
  18950. /* The algorithm in E5.1 Section 15.9.1.12 normalizes month, but
  18951. * does not normalize the day-of-month (nor check whether or not
  18952. * it is finite) because it's not necessary for finding the day
  18953. * number which matches the (year,month) pair.
  18954. *
  18955. * We assume that duk__day_from_year() is exact here.
  18956. *
  18957. * Without an explicit infinity / NaN check in the beginning,
  18958. * day_num would be a bogus integer here.
  18959. *
  18960. * It's possible for 'year' to be out of integer range here.
  18961. * If so, we need to return NaN without integer overflow.
  18962. * This fixes test-bug-setyear-overflow.js.
  18963. */
  18964. if (!duk__year_in_valid_range(year)) {
  18965. DUK_DD(DUK_DDPRINT("year not in ecmascript valid range, avoid integer overflow: %lf", (double) year));
  18966. return DUK_DOUBLE_NAN;
  18967. }
  18968. day_num = duk__day_from_year((duk_int_t) year);
  18969. is_leap = duk__is_leap_year((duk_int_t) year);
  18970. n = (duk_small_int_t) month;
  18971. for (i = 0; i < n; i++) {
  18972. day_num += duk__days_in_month[i];
  18973. if (i == 1 && is_leap) {
  18974. day_num++;
  18975. }
  18976. }
  18977. /* If 'day' is NaN, returns NaN. */
  18978. return (duk_double_t) day_num + day;
  18979. }
  18980. /* Split time value into parts. The time value is assumed to be an internal
  18981. * one, i.e. finite, no fractions. Possible local time adjustment has already
  18982. * been applied when reading the time value.
  18983. */
  18984. DUK_LOCAL void duk__timeval_to_parts(duk_double_t d, duk_int_t *parts, duk_double_t *dparts, duk_small_uint_t flags) {
  18985. duk_double_t d1, d2;
  18986. duk_int_t t1, t2;
  18987. duk_int_t day_since_epoch;
  18988. duk_int_t year; /* does not fit into 16 bits */
  18989. duk_small_int_t day_in_year;
  18990. duk_small_int_t month;
  18991. duk_small_int_t day;
  18992. duk_small_int_t dim;
  18993. duk_int_t jan1_since_epoch;
  18994. duk_small_int_t jan1_weekday;
  18995. duk_int_t equiv_year;
  18996. duk_small_uint_t i;
  18997. duk_bool_t is_leap;
  18998. duk_small_int_t arridx;
  18999. DUK_ASSERT(DUK_ISFINITE(d)); /* caller checks */
  19000. DUK_ASSERT(DUK_FLOOR(d) == d); /* no fractions in internal time */
  19001. /* The timevalue must be in valid Ecmascript range, but since a local
  19002. * time offset can be applied, we need to allow a +/- 24h leeway to
  19003. * the value. In other words, although the UTC time is within the
  19004. * Ecmascript range, the local part values can be just outside of it.
  19005. */
  19006. DUK_UNREF(duk__timeval_in_leeway_range);
  19007. DUK_ASSERT(duk__timeval_in_leeway_range(d));
  19008. /* these computations are guaranteed to be exact for the valid
  19009. * E5 time value range, assuming milliseconds without fractions.
  19010. */
  19011. d1 = (duk_double_t) DUK_FMOD(d, (double) DUK__MS_DAY);
  19012. if (d1 < 0.0) {
  19013. /* deal with negative values */
  19014. d1 += (duk_double_t) DUK__MS_DAY;
  19015. }
  19016. d2 = DUK_FLOOR((double) (d / (duk_double_t) DUK__MS_DAY));
  19017. DUK_ASSERT(d2 * ((duk_double_t) DUK__MS_DAY) + d1 == d);
  19018. /* now expected to fit into a 32-bit integer */
  19019. t1 = (duk_int_t) d1;
  19020. t2 = (duk_int_t) d2;
  19021. day_since_epoch = t2;
  19022. DUK_ASSERT((duk_double_t) t1 == d1);
  19023. DUK_ASSERT((duk_double_t) t2 == d2);
  19024. /* t1 = milliseconds within day (fits 32 bit)
  19025. * t2 = day number from epoch (fits 32 bit, may be negative)
  19026. */
  19027. parts[DUK__IDX_MILLISECOND] = t1 % 1000; t1 /= 1000;
  19028. parts[DUK__IDX_SECOND] = t1 % 60; t1 /= 60;
  19029. parts[DUK__IDX_MINUTE] = t1 % 60; t1 /= 60;
  19030. parts[DUK__IDX_HOUR] = t1;
  19031. DUK_ASSERT(parts[DUK__IDX_MILLISECOND] >= 0 && parts[DUK__IDX_MILLISECOND] <= 999);
  19032. DUK_ASSERT(parts[DUK__IDX_SECOND] >= 0 && parts[DUK__IDX_SECOND] <= 59);
  19033. DUK_ASSERT(parts[DUK__IDX_MINUTE] >= 0 && parts[DUK__IDX_MINUTE] <= 59);
  19034. DUK_ASSERT(parts[DUK__IDX_HOUR] >= 0 && parts[DUK__IDX_HOUR] <= 23);
  19035. DUK_DDD(DUK_DDDPRINT("d=%lf, d1=%lf, d2=%lf, t1=%ld, t2=%ld, parts: hour=%ld min=%ld sec=%ld msec=%ld",
  19036. (double) d, (double) d1, (double) d2, (long) t1, (long) t2,
  19037. (long) parts[DUK__IDX_HOUR],
  19038. (long) parts[DUK__IDX_MINUTE],
  19039. (long) parts[DUK__IDX_SECOND],
  19040. (long) parts[DUK__IDX_MILLISECOND]));
  19041. /* This assert depends on the input parts representing time inside
  19042. * the Ecmascript range.
  19043. */
  19044. DUK_ASSERT(t2 + DUK__WEEKDAY_MOD_ADDER >= 0);
  19045. parts[DUK__IDX_WEEKDAY] = (t2 + 4 + DUK__WEEKDAY_MOD_ADDER) % 7; /* E5.1 Section 15.9.1.6 */
  19046. DUK_ASSERT(parts[DUK__IDX_WEEKDAY] >= 0 && parts[DUK__IDX_WEEKDAY] <= 6);
  19047. year = duk__year_from_day(t2, &day_in_year);
  19048. day = day_in_year;
  19049. is_leap = duk__is_leap_year(year);
  19050. for (month = 0; month < 12; month++) {
  19051. dim = duk__days_in_month[month];
  19052. if (month == 1 && is_leap) {
  19053. dim++;
  19054. }
  19055. DUK_DDD(DUK_DDDPRINT("month=%ld, dim=%ld, day=%ld",
  19056. (long) month, (long) dim, (long) day));
  19057. if (day < dim) {
  19058. break;
  19059. }
  19060. day -= dim;
  19061. }
  19062. DUK_DDD(DUK_DDDPRINT("final month=%ld", (long) month));
  19063. DUK_ASSERT(month >= 0 && month <= 11);
  19064. DUK_ASSERT(day >= 0 && day <= 31);
  19065. /* Equivalent year mapping, used to avoid DST trouble when platform
  19066. * may fail to provide reasonable DST answers for dates outside the
  19067. * ordinary range (e.g. 1970-2038). An equivalent year has the same
  19068. * leap-year-ness as the original year and begins on the same weekday
  19069. * (Jan 1).
  19070. *
  19071. * The year 2038 is avoided because there seem to be problems with it
  19072. * on some platforms. The year 1970 is also avoided as there were
  19073. * practical problems with it; an equivalent year is used for it too,
  19074. * which breaks some DST computations for 1970 right now, see e.g.
  19075. * test-bi-date-tzoffset-brute-fi.js.
  19076. */
  19077. if ((flags & DUK__FLAG_EQUIVYEAR) && (year < 1971 || year > 2037)) {
  19078. DUK_ASSERT(is_leap == 0 || is_leap == 1);
  19079. jan1_since_epoch = day_since_epoch - day_in_year; /* day number for Jan 1 since epoch */
  19080. DUK_ASSERT(jan1_since_epoch + DUK__WEEKDAY_MOD_ADDER >= 0);
  19081. jan1_weekday = (jan1_since_epoch + 4 + DUK__WEEKDAY_MOD_ADDER) % 7; /* E5.1 Section 15.9.1.6 */
  19082. DUK_ASSERT(jan1_weekday >= 0 && jan1_weekday <= 6);
  19083. arridx = jan1_weekday;
  19084. if (is_leap) {
  19085. arridx += 7;
  19086. }
  19087. DUK_ASSERT(arridx >= 0 && arridx < (duk_small_int_t) (sizeof(duk__date_equivyear) / sizeof(duk_uint8_t)));
  19088. equiv_year = (duk_int_t) duk__date_equivyear[arridx] + 1970;
  19089. year = equiv_year;
  19090. DUK_DDD(DUK_DDDPRINT("equiv year mapping, year=%ld, day_in_year=%ld, day_since_epoch=%ld, "
  19091. "jan1_since_epoch=%ld, jan1_weekday=%ld -> equiv year %ld",
  19092. (long) year, (long) day_in_year, (long) day_since_epoch,
  19093. (long) jan1_since_epoch, (long) jan1_weekday, (long) equiv_year));
  19094. }
  19095. parts[DUK__IDX_YEAR] = year;
  19096. parts[DUK__IDX_MONTH] = month;
  19097. parts[DUK__IDX_DAY] = day;
  19098. if (flags & DUK__FLAG_ONEBASED) {
  19099. parts[DUK__IDX_MONTH]++; /* zero-based -> one-based */
  19100. parts[DUK__IDX_DAY]++; /* -""- */
  19101. }
  19102. if (dparts != NULL) {
  19103. for (i = 0; i < DUK__NUM_PARTS; i++) {
  19104. dparts[i] = (duk_double_t) parts[i];
  19105. }
  19106. }
  19107. }
  19108. /* Compute time value from (double) parts. The parts can be either UTC
  19109. * or local time; if local, they need to be (conceptually) converted into
  19110. * UTC time. The parts may represent valid or invalid time, and may be
  19111. * wildly out of range (but may cancel each other and still come out in
  19112. * the valid Date range).
  19113. */
  19114. DUK_LOCAL duk_double_t duk__get_timeval_from_dparts(duk_double_t *dparts, duk_small_uint_t flags) {
  19115. #if defined(DUK_USE_PARANOID_DATE_COMPUTATION)
  19116. /* See comments below on MakeTime why these are volatile. */
  19117. volatile duk_double_t tmp_time;
  19118. volatile duk_double_t tmp_day;
  19119. volatile duk_double_t d;
  19120. #else
  19121. duk_double_t tmp_time;
  19122. duk_double_t tmp_day;
  19123. duk_double_t d;
  19124. #endif
  19125. duk_small_uint_t i;
  19126. duk_int_t tzoff, tzoffprev1, tzoffprev2;
  19127. /* Expects 'this' at top of stack on entry. */
  19128. /* Coerce all finite parts with ToInteger(). ToInteger() must not
  19129. * be called for NaN/Infinity because it will convert e.g. NaN to
  19130. * zero. If ToInteger() has already been called, this has no side
  19131. * effects and is idempotent.
  19132. *
  19133. * Don't read dparts[DUK__IDX_WEEKDAY]; it will cause Valgrind issues
  19134. * if the value is uninitialized.
  19135. */
  19136. for (i = 0; i <= DUK__IDX_MILLISECOND; i++) {
  19137. /* SCANBUILD: scan-build complains here about assigned value
  19138. * being garbage or undefined. This is correct but operating
  19139. * on undefined values has no ill effect and is ignored by the
  19140. * caller in the case where this happens.
  19141. */
  19142. d = dparts[i];
  19143. if (DUK_ISFINITE(d)) {
  19144. dparts[i] = duk_js_tointeger_number(d);
  19145. }
  19146. }
  19147. /* Use explicit steps in computation to try to ensure that
  19148. * computation happens with intermediate results coerced to
  19149. * double values (instead of using something more accurate).
  19150. * E.g. E5.1 Section 15.9.1.11 requires use of IEEE 754
  19151. * rules (= Ecmascript '+' and '*' operators).
  19152. *
  19153. * Without 'volatile' even this approach fails on some platform
  19154. * and compiler combinations. For instance, gcc 4.8.1 on Ubuntu
  19155. * 64-bit, with -m32 and without -std=c99, test-bi-date-canceling.js
  19156. * would fail because of some optimizations when computing tmp_time
  19157. * (MakeTime below). Adding 'volatile' to tmp_time solved this
  19158. * particular problem (annoyingly, also adding debug prints or
  19159. * running the executable under valgrind hides it).
  19160. */
  19161. /* MakeTime */
  19162. tmp_time = 0.0;
  19163. tmp_time += dparts[DUK__IDX_HOUR] * ((duk_double_t) DUK__MS_HOUR);
  19164. tmp_time += dparts[DUK__IDX_MINUTE] * ((duk_double_t) DUK__MS_MINUTE);
  19165. tmp_time += dparts[DUK__IDX_SECOND] * ((duk_double_t) DUK__MS_SECOND);
  19166. tmp_time += dparts[DUK__IDX_MILLISECOND];
  19167. /* MakeDay */
  19168. tmp_day = duk__make_day(dparts[DUK__IDX_YEAR], dparts[DUK__IDX_MONTH], dparts[DUK__IDX_DAY]);
  19169. /* MakeDate */
  19170. d = tmp_day * ((duk_double_t) DUK__MS_DAY) + tmp_time;
  19171. DUK_DDD(DUK_DDDPRINT("time=%lf day=%lf --> timeval=%lf",
  19172. (double) tmp_time, (double) tmp_day, (double) d));
  19173. /* Optional UTC conversion. */
  19174. if (flags & DUK__FLAG_LOCALTIME) {
  19175. /* DUK__GET_LOCAL_TZOFFSET() needs to be called with a time
  19176. * value computed from UTC parts. At this point we only have
  19177. * 'd' which is a time value computed from local parts, so it
  19178. * is off by the UTC-to-local time offset which we don't know
  19179. * yet. The current solution for computing the UTC-to-local
  19180. * time offset is to iterate a few times and detect a fixed
  19181. * point or a two-cycle loop (or a sanity iteration limit),
  19182. * see test-bi-date-local-parts.js and test-bi-date-tzoffset-basic-fi.js.
  19183. *
  19184. * E5.1 Section 15.9.1.9:
  19185. * UTC(t) = t - LocalTZA - DaylightSavingTA(t - LocalTZA)
  19186. *
  19187. * For NaN/inf, DUK__GET_LOCAL_TZOFFSET() returns 0.
  19188. */
  19189. #if 0
  19190. /* Old solution: don't iterate, incorrect */
  19191. tzoff = DUK__GET_LOCAL_TZOFFSET(d);
  19192. DUK_DDD(DUK_DDDPRINT("tzoffset w/o iteration, tzoff=%ld", (long) tzoff));
  19193. d -= tzoff * 1000L;
  19194. DUK_UNREF(tzoffprev1);
  19195. DUK_UNREF(tzoffprev2);
  19196. #endif
  19197. /* Iteration solution */
  19198. tzoff = 0;
  19199. tzoffprev1 = 999999999L; /* invalid value which never matches */
  19200. for (i = 0; i < DUK__LOCAL_TZOFFSET_MAXITER; i++) {
  19201. tzoffprev2 = tzoffprev1;
  19202. tzoffprev1 = tzoff;
  19203. tzoff = DUK__GET_LOCAL_TZOFFSET(d - tzoff * 1000L);
  19204. DUK_DDD(DUK_DDDPRINT("tzoffset iteration, i=%d, tzoff=%ld, tzoffprev1=%ld tzoffprev2=%ld",
  19205. (int) i, (long) tzoff, (long) tzoffprev1, (long) tzoffprev2));
  19206. if (tzoff == tzoffprev1) {
  19207. DUK_DDD(DUK_DDDPRINT("tzoffset iteration finished, i=%d, tzoff=%ld, tzoffprev1=%ld, tzoffprev2=%ld",
  19208. (int) i, (long) tzoff, (long) tzoffprev1, (long) tzoffprev2));
  19209. break;
  19210. } else if (tzoff == tzoffprev2) {
  19211. /* Two value cycle, see e.g. test-bi-date-tzoffset-basic-fi.js.
  19212. * In these cases, favor a higher tzoffset to get a consistent
  19213. * result which is independent of iteration count. Not sure if
  19214. * this is a generically correct solution.
  19215. */
  19216. DUK_DDD(DUK_DDDPRINT("tzoffset iteration two-value cycle, i=%d, tzoff=%ld, tzoffprev1=%ld, tzoffprev2=%ld",
  19217. (int) i, (long) tzoff, (long) tzoffprev1, (long) tzoffprev2));
  19218. if (tzoffprev1 > tzoff) {
  19219. tzoff = tzoffprev1;
  19220. }
  19221. break;
  19222. }
  19223. }
  19224. DUK_DDD(DUK_DDDPRINT("tzoffset iteration, tzoff=%ld", (long) tzoff));
  19225. d -= tzoff * 1000L;
  19226. }
  19227. /* TimeClip(), which also handles Infinity -> NaN conversion */
  19228. d = duk__timeclip(d);
  19229. return d;
  19230. }
  19231. /*
  19232. * API oriented helpers
  19233. */
  19234. /* Push 'this' binding, check that it is a Date object; then push the
  19235. * internal time value. At the end, stack is: [ ... this timeval ].
  19236. * Returns the time value. Local time adjustment is done if requested.
  19237. */
  19238. DUK_LOCAL duk_double_t duk__push_this_get_timeval_tzoffset(duk_context *ctx, duk_small_uint_t flags, duk_int_t *out_tzoffset) {
  19239. duk_hthread *thr = (duk_hthread *) ctx;
  19240. duk_hobject *h;
  19241. duk_double_t d;
  19242. duk_int_t tzoffset = 0;
  19243. duk_push_this(ctx);
  19244. h = duk_get_hobject(ctx, -1); /* XXX: getter with class check, useful in built-ins */
  19245. if (h == NULL || DUK_HOBJECT_GET_CLASS_NUMBER(h) != DUK_HOBJECT_CLASS_DATE) {
  19246. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "expected Date");
  19247. }
  19248. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE);
  19249. d = duk_to_number(ctx, -1);
  19250. duk_pop(ctx);
  19251. if (DUK_ISNAN(d)) {
  19252. if (flags & DUK__FLAG_NAN_TO_ZERO) {
  19253. d = 0.0;
  19254. }
  19255. if (flags & DUK__FLAG_NAN_TO_RANGE_ERROR) {
  19256. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, "Invalid Date");
  19257. }
  19258. }
  19259. /* if no NaN handling flag, may still be NaN here, but not Inf */
  19260. DUK_ASSERT(!DUK_ISINF(d));
  19261. if (flags & DUK__FLAG_LOCALTIME) {
  19262. /* Note: DST adjustment is determined using UTC time.
  19263. * If 'd' is NaN, tzoffset will be 0.
  19264. */
  19265. tzoffset = DUK__GET_LOCAL_TZOFFSET(d); /* seconds */
  19266. d += tzoffset * 1000L;
  19267. }
  19268. if (out_tzoffset) {
  19269. *out_tzoffset = tzoffset;
  19270. }
  19271. /* [ ... this ] */
  19272. return d;
  19273. }
  19274. DUK_LOCAL duk_double_t duk__push_this_get_timeval(duk_context *ctx, duk_small_uint_t flags) {
  19275. return duk__push_this_get_timeval_tzoffset(ctx, flags, NULL);
  19276. }
  19277. /* Set timeval to 'this' from dparts, push the new time value onto the
  19278. * value stack and return 1 (caller can then tailcall us). Expects
  19279. * the value stack to contain 'this' on the stack top.
  19280. */
  19281. DUK_LOCAL duk_ret_t duk__set_this_timeval_from_dparts(duk_context *ctx, duk_double_t *dparts, duk_small_uint_t flags) {
  19282. duk_double_t d;
  19283. /* [ ... this ] */
  19284. d = duk__get_timeval_from_dparts(dparts, flags);
  19285. duk_push_number(ctx, d); /* -> [ ... this timeval_new ] */
  19286. duk_dup_top(ctx); /* -> [ ... this timeval_new timeval_new ] */
  19287. duk_put_prop_stridx(ctx, -3, DUK_STRIDX_INT_VALUE);
  19288. /* stack top: new time value, return 1 to allow tailcalls */
  19289. return 1;
  19290. }
  19291. /* 'out_buf' must be at least DUK_BI_DATE_ISO8601_BUFSIZE long. */
  19292. DUK_LOCAL void duk__format_parts_iso8601(duk_int_t *parts, duk_int_t tzoffset, duk_small_uint_t flags, duk_uint8_t *out_buf) {
  19293. char yearstr[8]; /* "-123456\0" */
  19294. char tzstr[8]; /* "+11:22\0" */
  19295. char sep = (flags & DUK__FLAG_SEP_T) ? DUK_ASC_UC_T : DUK_ASC_SPACE;
  19296. DUK_ASSERT(parts[DUK__IDX_MONTH] >= 1 && parts[DUK__IDX_MONTH] <= 12);
  19297. DUK_ASSERT(parts[DUK__IDX_DAY] >= 1 && parts[DUK__IDX_DAY] <= 31);
  19298. DUK_ASSERT(parts[DUK__IDX_YEAR] >= -999999 && parts[DUK__IDX_YEAR] <= 999999);
  19299. /* Note: %06d for positive value, %07d for negative value to include
  19300. * sign and 6 digits.
  19301. */
  19302. DUK_SNPRINTF(yearstr,
  19303. sizeof(yearstr),
  19304. (parts[DUK__IDX_YEAR] >= 0 && parts[DUK__IDX_YEAR] <= 9999) ? "%04ld" :
  19305. ((parts[DUK__IDX_YEAR] >= 0) ? "+%06ld" : "%07ld"),
  19306. (long) parts[DUK__IDX_YEAR]);
  19307. yearstr[sizeof(yearstr) - 1] = (char) 0;
  19308. if (flags & DUK__FLAG_LOCALTIME) {
  19309. /* tzoffset seconds are dropped; 16 bits suffice for
  19310. * time offset in minutes
  19311. */
  19312. if (tzoffset >= 0) {
  19313. duk_small_int_t tmp = tzoffset / 60;
  19314. DUK_SNPRINTF(tzstr, sizeof(tzstr), "+%02d:%02d", (int) (tmp / 60), (int) (tmp % 60));
  19315. } else {
  19316. duk_small_int_t tmp = -tzoffset / 60;
  19317. DUK_SNPRINTF(tzstr, sizeof(tzstr), "-%02d:%02d", (int) (tmp / 60), (int) (tmp % 60));
  19318. }
  19319. tzstr[sizeof(tzstr) - 1] = (char) 0;
  19320. } else {
  19321. tzstr[0] = DUK_ASC_UC_Z;
  19322. tzstr[1] = (char) 0;
  19323. }
  19324. /* Unlike year, the other parts fit into 16 bits so %d format
  19325. * is portable.
  19326. */
  19327. if ((flags & DUK__FLAG_TOSTRING_DATE) && (flags & DUK__FLAG_TOSTRING_TIME)) {
  19328. DUK_SPRINTF((char *) out_buf, "%s-%02d-%02d%c%02d:%02d:%02d.%03d%s",
  19329. (const char *) yearstr, (int) parts[DUK__IDX_MONTH], (int) parts[DUK__IDX_DAY], (int) sep,
  19330. (int) parts[DUK__IDX_HOUR], (int) parts[DUK__IDX_MINUTE],
  19331. (int) parts[DUK__IDX_SECOND], (int) parts[DUK__IDX_MILLISECOND], (const char *) tzstr);
  19332. } else if (flags & DUK__FLAG_TOSTRING_DATE) {
  19333. DUK_SPRINTF((char *) out_buf, "%s-%02d-%02d",
  19334. (const char *) yearstr, (int) parts[DUK__IDX_MONTH], (int) parts[DUK__IDX_DAY]);
  19335. } else {
  19336. DUK_ASSERT(flags & DUK__FLAG_TOSTRING_TIME);
  19337. DUK_SPRINTF((char *) out_buf, "%02d:%02d:%02d.%03d%s",
  19338. (int) parts[DUK__IDX_HOUR], (int) parts[DUK__IDX_MINUTE],
  19339. (int) parts[DUK__IDX_SECOND], (int) parts[DUK__IDX_MILLISECOND],
  19340. (const char *) tzstr);
  19341. }
  19342. }
  19343. /* Helper for string conversion calls: check 'this' binding, get the
  19344. * internal time value, and format date and/or time in a few formats.
  19345. * Return value allows tail calls.
  19346. */
  19347. DUK_LOCAL duk_ret_t duk__to_string_helper(duk_context *ctx, duk_small_uint_t flags) {
  19348. duk_double_t d;
  19349. duk_int_t parts[DUK__NUM_PARTS];
  19350. duk_int_t tzoffset; /* seconds, doesn't fit into 16 bits */
  19351. duk_bool_t rc;
  19352. duk_uint8_t buf[DUK_BI_DATE_ISO8601_BUFSIZE];
  19353. DUK_UNREF(rc); /* unreferenced with some options */
  19354. d = duk__push_this_get_timeval_tzoffset(ctx, flags, &tzoffset);
  19355. if (DUK_ISNAN(d)) {
  19356. duk_push_hstring_stridx(ctx, DUK_STRIDX_INVALID_DATE);
  19357. return 1;
  19358. }
  19359. DUK_ASSERT(DUK_ISFINITE(d));
  19360. /* formatters always get one-based month/day-of-month */
  19361. duk__timeval_to_parts(d, parts, NULL, DUK__FLAG_ONEBASED);
  19362. DUK_ASSERT(parts[DUK__IDX_MONTH] >= 1 && parts[DUK__IDX_MONTH] <= 12);
  19363. DUK_ASSERT(parts[DUK__IDX_DAY] >= 1 && parts[DUK__IDX_DAY] <= 31);
  19364. if (flags & DUK__FLAG_TOSTRING_LOCALE) {
  19365. /* try locale specific formatter; if it refuses to format the
  19366. * string, fall back to an ISO 8601 formatted value in local
  19367. * time.
  19368. */
  19369. #ifdef DUK_USE_DATE_FMT_STRFTIME
  19370. rc = duk__format_parts_strftime(ctx, parts, tzoffset, flags);
  19371. if (rc != 0) {
  19372. return 1;
  19373. }
  19374. #else
  19375. /* No locale specific formatter; this is OK, we fall back
  19376. * to ISO 8601.
  19377. */
  19378. #endif
  19379. }
  19380. /* Different calling convention than above used because the helper
  19381. * is shared.
  19382. */
  19383. duk__format_parts_iso8601(parts, tzoffset, flags, buf);
  19384. duk_push_string(ctx, (const char *) buf);
  19385. return 1;
  19386. }
  19387. /* Helper for component getter calls: check 'this' binding, get the
  19388. * internal time value, split it into parts (either as UTC time or
  19389. * local time), push a specified component as a return value to the
  19390. * value stack and return 1 (caller can then tailcall us).
  19391. */
  19392. DUK_LOCAL duk_ret_t duk__get_part_helper(duk_context *ctx, duk_small_uint_t flags_and_idx) {
  19393. duk_double_t d;
  19394. duk_int_t parts[DUK__NUM_PARTS];
  19395. duk_small_uint_t idx_part = (duk_small_uint_t) (flags_and_idx >> DUK__FLAG_VALUE_SHIFT); /* unpack args */
  19396. DUK_ASSERT_DISABLE(idx_part >= 0); /* unsigned */
  19397. DUK_ASSERT(idx_part < DUK__NUM_PARTS);
  19398. d = duk__push_this_get_timeval(ctx, flags_and_idx);
  19399. if (DUK_ISNAN(d)) {
  19400. duk_push_nan(ctx);
  19401. return 1;
  19402. }
  19403. DUK_ASSERT(DUK_ISFINITE(d));
  19404. duk__timeval_to_parts(d, parts, NULL, flags_and_idx); /* no need to mask idx portion */
  19405. /* Setter APIs detect special year numbers (0...99) and apply a +1900
  19406. * only in certain cases. The legacy getYear() getter applies -1900
  19407. * unconditionally.
  19408. */
  19409. duk_push_int(ctx, (flags_and_idx & DUK__FLAG_SUB1900) ? parts[idx_part] - 1900 : parts[idx_part]);
  19410. return 1;
  19411. }
  19412. /* Helper for component setter calls: check 'this' binding, get the
  19413. * internal time value, split it into parts (either as UTC time or
  19414. * local time), modify one or more components as specified, recompute
  19415. * the time value, set it as the internal value. Finally, push the
  19416. * new time value as a return value to the value stack and return 1
  19417. * (caller can then tailcall us).
  19418. */
  19419. DUK_LOCAL duk_ret_t duk__set_part_helper(duk_context *ctx, duk_small_uint_t flags_and_maxnargs) {
  19420. duk_double_t d;
  19421. duk_int_t parts[DUK__NUM_PARTS];
  19422. duk_double_t dparts[DUK__NUM_PARTS];
  19423. duk_idx_t nargs;
  19424. duk_small_uint_t maxnargs = (duk_small_uint_t) (flags_and_maxnargs >> DUK__FLAG_VALUE_SHIFT); /* unpack args */
  19425. duk_small_uint_t idx_first, idx;
  19426. duk_small_uint_t i;
  19427. nargs = duk_get_top(ctx);
  19428. d = duk__push_this_get_timeval(ctx, flags_and_maxnargs);
  19429. DUK_ASSERT(DUK_ISFINITE(d) || DUK_ISNAN(d));
  19430. if (DUK_ISFINITE(d)) {
  19431. duk__timeval_to_parts(d, parts, dparts, flags_and_maxnargs);
  19432. } else {
  19433. /* NaN timevalue: we need to coerce the arguments, but
  19434. * the resulting internal timestamp needs to remain NaN.
  19435. * This works but is not pretty: parts and dparts will
  19436. * be partially uninitialized, but we only write to them.
  19437. */
  19438. }
  19439. /*
  19440. * Determining which datetime components to overwrite based on
  19441. * stack arguments is a bit complicated, but important to factor
  19442. * out from setters themselves for compactness.
  19443. *
  19444. * If DUK__FLAG_TIMESETTER, maxnargs indicates setter type:
  19445. *
  19446. * 1 -> millisecond
  19447. * 2 -> second, [millisecond]
  19448. * 3 -> minute, [second], [millisecond]
  19449. * 4 -> hour, [minute], [second], [millisecond]
  19450. *
  19451. * Else:
  19452. *
  19453. * 1 -> date
  19454. * 2 -> month, [date]
  19455. * 3 -> year, [month], [date]
  19456. *
  19457. * By comparing nargs and maxnargs (and flags) we know which
  19458. * components to override. We rely on part index ordering.
  19459. */
  19460. if (flags_and_maxnargs & DUK__FLAG_TIMESETTER) {
  19461. DUK_ASSERT(maxnargs >= 1 && maxnargs <= 4);
  19462. idx_first = DUK__IDX_MILLISECOND - (maxnargs - 1);
  19463. } else {
  19464. DUK_ASSERT(maxnargs >= 1 && maxnargs <= 3);
  19465. idx_first = DUK__IDX_DAY - (maxnargs - 1);
  19466. }
  19467. DUK_ASSERT_DISABLE(idx_first >= 0); /* unsigned */
  19468. DUK_ASSERT(idx_first < DUK__NUM_PARTS);
  19469. for (i = 0; i < maxnargs; i++) {
  19470. if ((duk_idx_t) i >= nargs) {
  19471. /* no argument given -> leave components untouched */
  19472. break;
  19473. }
  19474. idx = idx_first + i;
  19475. DUK_ASSERT_DISABLE(idx >= 0); /* unsigned */
  19476. DUK_ASSERT(idx < DUK__NUM_PARTS);
  19477. if (idx == DUK__IDX_YEAR && (flags_and_maxnargs & DUK__FLAG_YEAR_FIXUP)) {
  19478. duk__twodigit_year_fixup(ctx, (duk_idx_t) i);
  19479. }
  19480. dparts[idx] = duk_to_number(ctx, i);
  19481. if (idx == DUK__IDX_DAY) {
  19482. /* Day-of-month is one-based in the API, but zero-based
  19483. * internally, so fix here. Note that month is zero-based
  19484. * both in the API and internally.
  19485. */
  19486. /* SCANBUILD: complains about use of uninitialized values.
  19487. * The complaint is correct, but operating in undefined
  19488. * values here is intentional in some cases and the caller
  19489. * ignores the results.
  19490. */
  19491. dparts[idx] -= 1.0;
  19492. }
  19493. }
  19494. /* Leaves new timevalue on stack top and returns 1, which is correct
  19495. * for part setters.
  19496. */
  19497. if (DUK_ISFINITE(d)) {
  19498. return duk__set_this_timeval_from_dparts(ctx, dparts, flags_and_maxnargs);
  19499. } else {
  19500. /* Internal timevalue is already NaN, so don't touch it. */
  19501. duk_push_nan(ctx);
  19502. return 1;
  19503. }
  19504. }
  19505. /* Apply ToNumber() to specified index; if ToInteger(val) in [0,99], add
  19506. * 1900 and replace value at idx_val.
  19507. */
  19508. DUK_LOCAL void duk__twodigit_year_fixup(duk_context *ctx, duk_idx_t idx_val) {
  19509. duk_double_t d;
  19510. /* XXX: idx_val would fit into 16 bits, but using duk_small_uint_t
  19511. * might not generate better code due to casting.
  19512. */
  19513. /* E5 Sections 15.9.3.1, B.2.4, B.2.5 */
  19514. duk_to_number(ctx, idx_val);
  19515. if (duk_is_nan(ctx, idx_val)) {
  19516. return;
  19517. }
  19518. duk_dup(ctx, idx_val);
  19519. duk_to_int(ctx, -1);
  19520. d = duk_get_number(ctx, -1); /* get as double to handle huge numbers correctly */
  19521. if (d >= 0.0 && d <= 99.0) {
  19522. d += 1900.0;
  19523. duk_push_number(ctx, d);
  19524. duk_replace(ctx, idx_val);
  19525. }
  19526. duk_pop(ctx);
  19527. }
  19528. /* Set datetime parts from stack arguments, defaulting any missing values.
  19529. * Day-of-week is not set; it is not required when setting the time value.
  19530. */
  19531. DUK_LOCAL void duk__set_parts_from_args(duk_context *ctx, duk_double_t *dparts, duk_idx_t nargs) {
  19532. duk_double_t d;
  19533. duk_small_uint_t i;
  19534. duk_small_uint_t idx;
  19535. /* Causes a ToNumber() coercion, but doesn't break coercion order since
  19536. * year is coerced first anyway.
  19537. */
  19538. duk__twodigit_year_fixup(ctx, 0);
  19539. /* There are at most 7 args, but we use 8 here so that also
  19540. * DUK__IDX_WEEKDAY gets initialized (to zero) to avoid the potential
  19541. * for any Valgrind gripes later.
  19542. */
  19543. for (i = 0; i < 8; i++) {
  19544. /* Note: rely on index ordering */
  19545. idx = DUK__IDX_YEAR + i;
  19546. if ((duk_idx_t) i < nargs) {
  19547. d = duk_to_number(ctx, (duk_idx_t) i);
  19548. if (idx == DUK__IDX_DAY) {
  19549. /* Convert day from one-based to zero-based (internal). This may
  19550. * cause the day part to be negative, which is OK.
  19551. */
  19552. d -= 1.0;
  19553. }
  19554. } else {
  19555. /* All components default to 0 except day-of-month which defaults
  19556. * to 1. However, because our internal day-of-month is zero-based,
  19557. * it also defaults to zero here.
  19558. */
  19559. d = 0.0;
  19560. }
  19561. dparts[idx] = d;
  19562. }
  19563. DUK_DDD(DUK_DDDPRINT("parts from args -> %lf %lf %lf %lf %lf %lf %lf %lf",
  19564. (double) dparts[0], (double) dparts[1],
  19565. (double) dparts[2], (double) dparts[3],
  19566. (double) dparts[4], (double) dparts[5],
  19567. (double) dparts[6], (double) dparts[7]));
  19568. }
  19569. /*
  19570. * Helper to format a time value into caller buffer, used by logging.
  19571. * 'out_buf' must be at least DUK_BI_DATE_ISO8601_BUFSIZE long.
  19572. */
  19573. DUK_INTERNAL void duk_bi_date_format_timeval(duk_double_t timeval, duk_uint8_t *out_buf) {
  19574. duk_int_t parts[DUK__NUM_PARTS];
  19575. duk__timeval_to_parts(timeval,
  19576. parts,
  19577. NULL,
  19578. DUK__FLAG_ONEBASED);
  19579. duk__format_parts_iso8601(parts,
  19580. 0 /*tzoffset*/,
  19581. DUK__FLAG_TOSTRING_DATE |
  19582. DUK__FLAG_TOSTRING_TIME |
  19583. DUK__FLAG_SEP_T /*flags*/,
  19584. out_buf);
  19585. }
  19586. /*
  19587. * Indirect magic value lookup for Date methods.
  19588. *
  19589. * Date methods don't put their control flags into the function magic value
  19590. * because they wouldn't fit into a LIGHTFUNC's magic field. Instead, the
  19591. * magic value is set to an index pointing to the array of control flags
  19592. * below.
  19593. *
  19594. * This must be kept in strict sync with genbuiltins.py!
  19595. */
  19596. static duk_uint16_t duk__date_magics[] = {
  19597. /* 0: toString */
  19598. DUK__FLAG_TOSTRING_DATE + DUK__FLAG_TOSTRING_TIME + DUK__FLAG_LOCALTIME,
  19599. /* 1: toDateString */
  19600. DUK__FLAG_TOSTRING_DATE + DUK__FLAG_LOCALTIME,
  19601. /* 2: toTimeString */
  19602. DUK__FLAG_TOSTRING_TIME + DUK__FLAG_LOCALTIME,
  19603. /* 3: toLocaleString */
  19604. DUK__FLAG_TOSTRING_DATE + DUK__FLAG_TOSTRING_TIME + DUK__FLAG_TOSTRING_LOCALE + DUK__FLAG_LOCALTIME,
  19605. /* 4: toLocaleDateString */
  19606. DUK__FLAG_TOSTRING_DATE + DUK__FLAG_TOSTRING_LOCALE + DUK__FLAG_LOCALTIME,
  19607. /* 5: toLocaleTimeString */
  19608. DUK__FLAG_TOSTRING_TIME + DUK__FLAG_TOSTRING_LOCALE + DUK__FLAG_LOCALTIME,
  19609. /* 6: toUTCString */
  19610. DUK__FLAG_TOSTRING_DATE + DUK__FLAG_TOSTRING_TIME,
  19611. /* 7: toISOString */
  19612. DUK__FLAG_TOSTRING_DATE + DUK__FLAG_TOSTRING_TIME + DUK__FLAG_NAN_TO_RANGE_ERROR + DUK__FLAG_SEP_T,
  19613. /* 8: getFullYear */
  19614. DUK__FLAG_LOCALTIME + (DUK__IDX_YEAR << DUK__FLAG_VALUE_SHIFT),
  19615. /* 9: getUTCFullYear */
  19616. 0 + (DUK__IDX_YEAR << DUK__FLAG_VALUE_SHIFT),
  19617. /* 10: getMonth */
  19618. DUK__FLAG_LOCALTIME + (DUK__IDX_MONTH << DUK__FLAG_VALUE_SHIFT),
  19619. /* 11: getUTCMonth */
  19620. 0 + (DUK__IDX_MONTH << DUK__FLAG_VALUE_SHIFT),
  19621. /* 12: getDate */
  19622. DUK__FLAG_ONEBASED + DUK__FLAG_LOCALTIME + (DUK__IDX_DAY << DUK__FLAG_VALUE_SHIFT),
  19623. /* 13: getUTCDate */
  19624. DUK__FLAG_ONEBASED + (DUK__IDX_DAY << DUK__FLAG_VALUE_SHIFT),
  19625. /* 14: getDay */
  19626. DUK__FLAG_LOCALTIME + (DUK__IDX_WEEKDAY << DUK__FLAG_VALUE_SHIFT),
  19627. /* 15: getUTCDay */
  19628. 0 + (DUK__IDX_WEEKDAY << DUK__FLAG_VALUE_SHIFT),
  19629. /* 16: getHours */
  19630. DUK__FLAG_LOCALTIME + (DUK__IDX_HOUR << DUK__FLAG_VALUE_SHIFT),
  19631. /* 17: getUTCHours */
  19632. 0 + (DUK__IDX_HOUR << DUK__FLAG_VALUE_SHIFT),
  19633. /* 18: getMinutes */
  19634. DUK__FLAG_LOCALTIME + (DUK__IDX_MINUTE << DUK__FLAG_VALUE_SHIFT),
  19635. /* 19: getUTCMinutes */
  19636. 0 + (DUK__IDX_MINUTE << DUK__FLAG_VALUE_SHIFT),
  19637. /* 20: getSeconds */
  19638. DUK__FLAG_LOCALTIME + (DUK__IDX_SECOND << DUK__FLAG_VALUE_SHIFT),
  19639. /* 21: getUTCSeconds */
  19640. 0 + (DUK__IDX_SECOND << DUK__FLAG_VALUE_SHIFT),
  19641. /* 22: getMilliseconds */
  19642. DUK__FLAG_LOCALTIME + (DUK__IDX_MILLISECOND << DUK__FLAG_VALUE_SHIFT),
  19643. /* 23: getUTCMilliseconds */
  19644. 0 + (DUK__IDX_MILLISECOND << DUK__FLAG_VALUE_SHIFT),
  19645. /* 24: setMilliseconds */
  19646. DUK__FLAG_TIMESETTER + DUK__FLAG_LOCALTIME + (1 << DUK__FLAG_VALUE_SHIFT),
  19647. /* 25: setUTCMilliseconds */
  19648. DUK__FLAG_TIMESETTER + (1 << DUK__FLAG_VALUE_SHIFT),
  19649. /* 26: setSeconds */
  19650. DUK__FLAG_TIMESETTER + DUK__FLAG_LOCALTIME + (2 << DUK__FLAG_VALUE_SHIFT),
  19651. /* 27: setUTCSeconds */
  19652. DUK__FLAG_TIMESETTER + (2 << DUK__FLAG_VALUE_SHIFT),
  19653. /* 28: setMinutes */
  19654. DUK__FLAG_TIMESETTER + DUK__FLAG_LOCALTIME + (3 << DUK__FLAG_VALUE_SHIFT),
  19655. /* 29: setUTCMinutes */
  19656. DUK__FLAG_TIMESETTER + (3 << DUK__FLAG_VALUE_SHIFT),
  19657. /* 30: setHours */
  19658. DUK__FLAG_TIMESETTER + DUK__FLAG_LOCALTIME + (4 << DUK__FLAG_VALUE_SHIFT),
  19659. /* 31: setUTCHours */
  19660. DUK__FLAG_TIMESETTER + (4 << DUK__FLAG_VALUE_SHIFT),
  19661. /* 32: setDate */
  19662. DUK__FLAG_LOCALTIME + (1 << DUK__FLAG_VALUE_SHIFT),
  19663. /* 33: setUTCDate */
  19664. 0 + (1 << DUK__FLAG_VALUE_SHIFT),
  19665. /* 34: setMonth */
  19666. DUK__FLAG_LOCALTIME + (2 << DUK__FLAG_VALUE_SHIFT),
  19667. /* 35: setUTCMonth */
  19668. 0 + (2 << DUK__FLAG_VALUE_SHIFT),
  19669. /* 36: setFullYear */
  19670. DUK__FLAG_NAN_TO_ZERO + DUK__FLAG_LOCALTIME + (3 << DUK__FLAG_VALUE_SHIFT),
  19671. /* 37: setUTCFullYear */
  19672. DUK__FLAG_NAN_TO_ZERO + (3 << DUK__FLAG_VALUE_SHIFT),
  19673. /* 38: getYear */
  19674. DUK__FLAG_LOCALTIME + DUK__FLAG_SUB1900 + (DUK__IDX_YEAR << DUK__FLAG_VALUE_SHIFT),
  19675. /* 39: setYear */
  19676. DUK__FLAG_NAN_TO_ZERO + DUK__FLAG_YEAR_FIXUP + (3 << DUK__FLAG_VALUE_SHIFT),
  19677. };
  19678. DUK_LOCAL duk_small_uint_t duk__date_get_indirect_magic(duk_context *ctx) {
  19679. duk_small_int_t magicidx = (duk_small_uint_t) duk_get_current_magic(ctx);
  19680. DUK_ASSERT(magicidx >= 0 && magicidx < (duk_small_int_t) (sizeof(duk__date_magics) / sizeof(duk_uint16_t)));
  19681. return (duk_small_uint_t) duk__date_magics[magicidx];
  19682. }
  19683. /*
  19684. * Constructor calls
  19685. */
  19686. DUK_INTERNAL duk_ret_t duk_bi_date_constructor(duk_context *ctx) {
  19687. duk_idx_t nargs = duk_get_top(ctx);
  19688. duk_bool_t is_cons = duk_is_constructor_call(ctx);
  19689. duk_double_t dparts[DUK__NUM_PARTS];
  19690. duk_double_t d;
  19691. DUK_DDD(DUK_DDDPRINT("Date constructor, nargs=%ld, is_cons=%ld", (long) nargs, (long) is_cons));
  19692. duk_push_object_helper(ctx,
  19693. DUK_HOBJECT_FLAG_EXTENSIBLE |
  19694. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_DATE),
  19695. DUK_BIDX_DATE_PROTOTYPE);
  19696. /* Unlike most built-ins, the internal [[PrimitiveValue]] of a Date
  19697. * is mutable.
  19698. */
  19699. if (nargs == 0 || !is_cons) {
  19700. d = duk__timeclip(DUK__GET_NOW_TIMEVAL(ctx));
  19701. duk_push_number(ctx, d);
  19702. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_W);
  19703. if (!is_cons) {
  19704. /* called as a normal function: return new Date().toString() */
  19705. duk_to_string(ctx, -1);
  19706. }
  19707. return 1;
  19708. } else if (nargs == 1) {
  19709. duk_to_primitive(ctx, 0, DUK_HINT_NONE);
  19710. if (duk_is_string(ctx, 0)) {
  19711. duk__parse_string(ctx, duk_to_string(ctx, 0));
  19712. duk_replace(ctx, 0); /* may be NaN */
  19713. }
  19714. d = duk__timeclip(duk_to_number(ctx, 0));
  19715. duk_push_number(ctx, d);
  19716. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_W);
  19717. return 1;
  19718. }
  19719. duk__set_parts_from_args(ctx, dparts, nargs);
  19720. /* Parts are in local time, convert when setting. */
  19721. (void) duk__set_this_timeval_from_dparts(ctx, dparts, DUK__FLAG_LOCALTIME /*flags*/); /* -> [ ... this timeval ] */
  19722. duk_pop(ctx); /* -> [ ... this ] */
  19723. return 1;
  19724. }
  19725. DUK_INTERNAL duk_ret_t duk_bi_date_constructor_parse(duk_context *ctx) {
  19726. return duk__parse_string(ctx, duk_to_string(ctx, 0));
  19727. }
  19728. DUK_INTERNAL duk_ret_t duk_bi_date_constructor_utc(duk_context *ctx) {
  19729. duk_idx_t nargs = duk_get_top(ctx);
  19730. duk_double_t dparts[DUK__NUM_PARTS];
  19731. duk_double_t d;
  19732. /* Behavior for nargs < 2 is implementation dependent: currently we'll
  19733. * set a NaN time value (matching V8 behavior) in this case.
  19734. */
  19735. if (nargs < 2) {
  19736. duk_push_nan(ctx);
  19737. } else {
  19738. duk__set_parts_from_args(ctx, dparts, nargs);
  19739. d = duk__get_timeval_from_dparts(dparts, 0 /*flags*/);
  19740. duk_push_number(ctx, d);
  19741. }
  19742. return 1;
  19743. }
  19744. DUK_INTERNAL duk_ret_t duk_bi_date_constructor_now(duk_context *ctx) {
  19745. duk_double_t d;
  19746. d = DUK__GET_NOW_TIMEVAL(ctx);
  19747. DUK_ASSERT(duk__timeclip(d) == d); /* TimeClip() should never be necessary */
  19748. duk_push_number(ctx, d);
  19749. return 1;
  19750. }
  19751. /*
  19752. * String/JSON conversions
  19753. *
  19754. * Human readable conversions are now basically ISO 8601 with a space
  19755. * (instead of 'T') as the date/time separator. This is a good baseline
  19756. * and is platform independent.
  19757. *
  19758. * A shared native helper to provide many conversions. Magic value contains
  19759. * a set of flags. The helper provides:
  19760. *
  19761. * toString()
  19762. * toDateString()
  19763. * toTimeString()
  19764. * toLocaleString()
  19765. * toLocaleDateString()
  19766. * toLocaleTimeString()
  19767. * toUTCString()
  19768. * toISOString()
  19769. *
  19770. * Notes:
  19771. *
  19772. * - Date.prototype.toGMTString() and Date.prototype.toUTCString() are
  19773. * required to be the same Ecmascript function object (!), so it is
  19774. * omitted from here.
  19775. *
  19776. * - Date.prototype.toUTCString(): E5.1 specification does not require a
  19777. * specific format, but result should be human readable. The
  19778. * specification suggests using ISO 8601 format with a space (instead
  19779. * of 'T') separator if a more human readable format is not available.
  19780. *
  19781. * - Date.prototype.toISOString(): unlike other conversion functions,
  19782. * toISOString() requires a RangeError for invalid date values.
  19783. */
  19784. DUK_INTERNAL duk_ret_t duk_bi_date_prototype_tostring_shared(duk_context *ctx) {
  19785. duk_small_uint_t flags = duk__date_get_indirect_magic(ctx);
  19786. return duk__to_string_helper(ctx, flags);
  19787. }
  19788. DUK_INTERNAL duk_ret_t duk_bi_date_prototype_value_of(duk_context *ctx) {
  19789. /* This native function is also used for Date.prototype.getTime()
  19790. * as their behavior is identical.
  19791. */
  19792. duk_double_t d = duk__push_this_get_timeval(ctx, 0 /*flags*/); /* -> [ this ] */
  19793. DUK_ASSERT(DUK_ISFINITE(d) || DUK_ISNAN(d));
  19794. duk_push_number(ctx, d);
  19795. return 1;
  19796. }
  19797. DUK_INTERNAL duk_ret_t duk_bi_date_prototype_to_json(duk_context *ctx) {
  19798. /* Note: toJSON() is a generic function which works even if 'this'
  19799. * is not a Date. The sole argument is ignored.
  19800. */
  19801. duk_push_this(ctx);
  19802. duk_to_object(ctx, -1);
  19803. duk_dup_top(ctx);
  19804. duk_to_primitive(ctx, -1, DUK_HINT_NUMBER);
  19805. if (duk_is_number(ctx, -1)) {
  19806. duk_double_t d = duk_get_number(ctx, -1);
  19807. if (!DUK_ISFINITE(d)) {
  19808. duk_push_null(ctx);
  19809. return 1;
  19810. }
  19811. }
  19812. duk_pop(ctx);
  19813. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_TO_ISO_STRING);
  19814. duk_dup(ctx, -2); /* -> [ O toIsoString O ] */
  19815. duk_call_method(ctx, 0);
  19816. return 1;
  19817. }
  19818. /*
  19819. * Getters.
  19820. *
  19821. * Implementing getters is quite easy. The internal time value is either
  19822. * NaN, or represents milliseconds (without fractions) from Jan 1, 1970.
  19823. * The internal time value can be converted to integer parts, and each
  19824. * part will be normalized and will fit into a 32-bit signed integer.
  19825. *
  19826. * A shared native helper to provide all getters. Magic value contains
  19827. * a set of flags and also packs the date component index argument. The
  19828. * helper provides:
  19829. *
  19830. * getFullYear()
  19831. * getUTCFullYear()
  19832. * getMonth()
  19833. * getUTCMonth()
  19834. * getDate()
  19835. * getUTCDate()
  19836. * getDay()
  19837. * getUTCDay()
  19838. * getHours()
  19839. * getUTCHours()
  19840. * getMinutes()
  19841. * getUTCMinutes()
  19842. * getSeconds()
  19843. * getUTCSeconds()
  19844. * getMilliseconds()
  19845. * getUTCMilliseconds()
  19846. * getYear()
  19847. *
  19848. * Notes:
  19849. *
  19850. * - Date.prototype.getDate(): 'date' means day-of-month, and is
  19851. * zero-based in internal calculations but public API expects it to
  19852. * be one-based.
  19853. *
  19854. * - Date.prototype.getTime() and Date.prototype.valueOf() have identical
  19855. * behavior. They have separate function objects, but share the same C
  19856. * function (duk_bi_date_prototype_value_of).
  19857. */
  19858. DUK_INTERNAL duk_ret_t duk_bi_date_prototype_get_shared(duk_context *ctx) {
  19859. duk_small_uint_t flags_and_idx = duk__date_get_indirect_magic(ctx);
  19860. return duk__get_part_helper(ctx, flags_and_idx);
  19861. }
  19862. DUK_INTERNAL duk_ret_t duk_bi_date_prototype_get_timezone_offset(duk_context *ctx) {
  19863. /*
  19864. * Return (t - LocalTime(t)) in minutes:
  19865. *
  19866. * t - LocalTime(t) = t - (t + LocalTZA + DaylightSavingTA(t))
  19867. * = -(LocalTZA + DaylightSavingTA(t))
  19868. *
  19869. * where DaylightSavingTA() is checked for time 't'.
  19870. *
  19871. * Note that the sign of the result is opposite to common usage,
  19872. * e.g. for EE(S)T which normally is +2h or +3h from UTC, this
  19873. * function returns -120 or -180.
  19874. *
  19875. */
  19876. duk_double_t d;
  19877. duk_int_t tzoffset;
  19878. /* Note: DST adjustment is determined using UTC time. */
  19879. d = duk__push_this_get_timeval(ctx, 0 /*flags*/);
  19880. DUK_ASSERT(DUK_ISFINITE(d) || DUK_ISNAN(d));
  19881. if (DUK_ISNAN(d)) {
  19882. duk_push_nan(ctx);
  19883. } else {
  19884. DUK_ASSERT(DUK_ISFINITE(d));
  19885. tzoffset = DUK__GET_LOCAL_TZOFFSET(d);
  19886. duk_push_int(ctx, -tzoffset / 60);
  19887. }
  19888. return 1;
  19889. }
  19890. /*
  19891. * Setters.
  19892. *
  19893. * Setters are a bit more complicated than getters. Component setters
  19894. * break down the current time value into its (normalized) component
  19895. * parts, replace one or more components with -unnormalized- new values,
  19896. * and the components are then converted back into a time value. As an
  19897. * example of using unnormalized values:
  19898. *
  19899. * var d = new Date(1234567890);
  19900. *
  19901. * is equivalent to:
  19902. *
  19903. * var d = new Date(0);
  19904. * d.setUTCMilliseconds(1234567890);
  19905. *
  19906. * A shared native helper to provide almost all setters. Magic value
  19907. * contains a set of flags and also packs the "maxnargs" argument. The
  19908. * helper provides:
  19909. *
  19910. * setMilliseconds()
  19911. * setUTCMilliseconds()
  19912. * setSeconds()
  19913. * setUTCSeconds()
  19914. * setMinutes()
  19915. * setUTCMinutes()
  19916. * setHours()
  19917. * setUTCHours()
  19918. * setDate()
  19919. * setUTCDate()
  19920. * setMonth()
  19921. * setUTCMonth()
  19922. * setFullYear()
  19923. * setUTCFullYear()
  19924. * setYear()
  19925. *
  19926. * Notes:
  19927. *
  19928. * - Date.prototype.setYear() (Section B addition): special year check
  19929. * is omitted. NaN / Infinity will just flow through and ultimately
  19930. * result in a NaN internal time value.
  19931. *
  19932. * - Date.prototype.setYear() does not have optional arguments for
  19933. * setting month and day-in-month (like setFullYear()), but we indicate
  19934. * 'maxnargs' to be 3 to get the year written to the correct component
  19935. * index in duk__set_part_helper(). The function has nargs == 1, so only
  19936. * the year will be set regardless of actual argument count.
  19937. */
  19938. DUK_INTERNAL duk_ret_t duk_bi_date_prototype_set_shared(duk_context *ctx) {
  19939. duk_small_uint_t flags_and_maxnargs = duk__date_get_indirect_magic(ctx);
  19940. return duk__set_part_helper(ctx, flags_and_maxnargs);
  19941. }
  19942. DUK_INTERNAL duk_ret_t duk_bi_date_prototype_set_time(duk_context *ctx) {
  19943. duk_double_t d;
  19944. (void) duk__push_this_get_timeval(ctx, 0 /*flags*/); /* -> [ timeval this ] */
  19945. d = duk__timeclip(duk_to_number(ctx, 0));
  19946. duk_push_number(ctx, d);
  19947. duk_dup_top(ctx);
  19948. duk_put_prop_stridx(ctx, -3, DUK_STRIDX_INT_VALUE); /* -> [ timeval this timeval ] */
  19949. return 1;
  19950. }
  19951. #line 1 "duk_bi_duktape.c"
  19952. /*
  19953. * Duktape built-ins
  19954. *
  19955. * Size optimization note: it might seem that vararg multipurpose functions
  19956. * like fin(), enc(), and dec() are not very size optimal, but using a single
  19957. * user-visible Ecmascript function saves a lot of run-time footprint; each
  19958. * Function instance takes >100 bytes. Using a shared native helper and a
  19959. * 'magic' value won't save much if there are multiple Function instances
  19960. * anyway.
  19961. */
  19962. /* include removed: duk_internal.h */
  19963. /* Raw helper to extract internal information / statistics about a value.
  19964. * The return values are version specific and must not expose anything
  19965. * that would lead to security issues (e.g. exposing compiled function
  19966. * 'data' buffer might be an issue). Currently only counts and sizes and
  19967. * such are given so there should not be a security impact.
  19968. */
  19969. DUK_INTERNAL duk_ret_t duk_bi_duktape_object_info(duk_context *ctx) {
  19970. duk_hthread *thr = (duk_hthread *) ctx;
  19971. duk_tval *tv;
  19972. duk_heaphdr *h;
  19973. duk_int_t i, n;
  19974. DUK_UNREF(thr);
  19975. /* result array */
  19976. duk_push_array(ctx); /* -> [ val arr ] */
  19977. /* type tag (public) */
  19978. duk_push_int(ctx, duk_get_type(ctx, 0));
  19979. /* address */
  19980. tv = duk_get_tval(ctx, 0);
  19981. DUK_ASSERT(tv != NULL); /* because arg count is 1 */
  19982. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  19983. h = DUK_TVAL_GET_HEAPHDR(tv);
  19984. duk_push_pointer(ctx, (void *) h);
  19985. } else {
  19986. /* internal type tag */
  19987. duk_push_int(ctx, (duk_int_t) DUK_TVAL_GET_TAG(tv));
  19988. goto done;
  19989. }
  19990. DUK_ASSERT(h != NULL);
  19991. /* refcount */
  19992. #ifdef DUK_USE_REFERENCE_COUNTING
  19993. duk_push_size_t(ctx, DUK_HEAPHDR_GET_REFCOUNT(h));
  19994. #else
  19995. duk_push_undefined(ctx);
  19996. #endif
  19997. /* heaphdr size and additional allocation size, followed by
  19998. * type specific stuff (with varying value count)
  19999. */
  20000. switch ((duk_small_int_t) DUK_HEAPHDR_GET_TYPE(h)) {
  20001. case DUK_HTYPE_STRING: {
  20002. duk_hstring *h_str = (duk_hstring *) h;
  20003. duk_push_uint(ctx, (duk_uint_t) (sizeof(duk_hstring) + DUK_HSTRING_GET_BYTELEN(h_str) + 1));
  20004. break;
  20005. }
  20006. case DUK_HTYPE_OBJECT: {
  20007. duk_hobject *h_obj = (duk_hobject *) h;
  20008. duk_small_uint_t hdr_size;
  20009. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h_obj)) {
  20010. hdr_size = (duk_small_uint_t) sizeof(duk_hcompiledfunction);
  20011. } else if (DUK_HOBJECT_IS_NATIVEFUNCTION(h_obj)) {
  20012. hdr_size = (duk_small_uint_t) sizeof(duk_hnativefunction);
  20013. } else if (DUK_HOBJECT_IS_THREAD(h_obj)) {
  20014. hdr_size = (duk_small_uint_t) sizeof(duk_hthread);
  20015. } else {
  20016. hdr_size = (duk_small_uint_t) sizeof(duk_hobject);
  20017. }
  20018. duk_push_uint(ctx, (duk_uint_t) hdr_size);
  20019. duk_push_uint(ctx, (duk_uint_t) DUK_HOBJECT_E_ALLOC_SIZE(h_obj));
  20020. duk_push_uint(ctx, (duk_uint_t) DUK_HOBJECT_GET_ESIZE(h_obj));
  20021. /* Note: e_next indicates the number of gc-reachable entries
  20022. * in the entry part, and also indicates the index where the
  20023. * next new property would be inserted. It does *not* indicate
  20024. * the number of non-NULL keys present in the object. That
  20025. * value could be counted separately but requires a pass through
  20026. * the key list.
  20027. */
  20028. duk_push_uint(ctx, (duk_uint_t) DUK_HOBJECT_GET_ENEXT(h_obj));
  20029. duk_push_uint(ctx, (duk_uint_t) DUK_HOBJECT_GET_ASIZE(h_obj));
  20030. duk_push_uint(ctx, (duk_uint_t) DUK_HOBJECT_GET_HSIZE(h_obj));
  20031. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h_obj)) {
  20032. duk_hbuffer *h_data = (duk_hbuffer *) DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, (duk_hcompiledfunction *) h_obj);
  20033. if (h_data) {
  20034. duk_push_uint(ctx, (duk_uint_t) DUK_HBUFFER_GET_SIZE(h_data));
  20035. } else {
  20036. duk_push_uint(ctx, 0);
  20037. }
  20038. }
  20039. break;
  20040. }
  20041. case DUK_HTYPE_BUFFER: {
  20042. duk_hbuffer *h_buf = (duk_hbuffer *) h;
  20043. if (DUK_HBUFFER_HAS_DYNAMIC(h_buf)) {
  20044. /* XXX: when alloc_size == 0, dynamic buf ptr may now be NULL, in which case
  20045. * the second allocation does not exist.
  20046. */
  20047. duk_hbuffer_dynamic *h_dyn = (duk_hbuffer_dynamic *) h;
  20048. duk_push_uint(ctx, (duk_uint_t) (sizeof(duk_hbuffer_dynamic)));
  20049. duk_push_uint(ctx, (duk_uint_t) (DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(h_dyn)));
  20050. } else {
  20051. duk_push_uint(ctx, (duk_uint_t) (sizeof(duk_hbuffer_fixed) + DUK_HBUFFER_GET_SIZE(h_buf) + 1));
  20052. }
  20053. break;
  20054. }
  20055. }
  20056. done:
  20057. /* set values into ret array */
  20058. /* XXX: primitive to make array from valstack slice */
  20059. n = duk_get_top(ctx);
  20060. for (i = 2; i < n; i++) {
  20061. duk_dup(ctx, i);
  20062. duk_put_prop_index(ctx, 1, i - 2);
  20063. }
  20064. duk_dup(ctx, 1);
  20065. return 1;
  20066. }
  20067. DUK_INTERNAL duk_ret_t duk_bi_duktape_object_act(duk_context *ctx) {
  20068. duk_hthread *thr = (duk_hthread *) ctx;
  20069. duk_activation *act;
  20070. duk_uint_fast32_t pc;
  20071. duk_uint_fast32_t line;
  20072. duk_int_t level;
  20073. /* -1 = top callstack entry, callstack[callstack_top - 1]
  20074. * -callstack_top = bottom callstack entry, callstack[0]
  20075. */
  20076. level = duk_to_int(ctx, 0);
  20077. if (level >= 0 || -level > (duk_int_t) thr->callstack_top) {
  20078. return 0;
  20079. }
  20080. DUK_ASSERT(level >= -((duk_int_t) thr->callstack_top) && level <= -1);
  20081. act = thr->callstack + thr->callstack_top + level;
  20082. duk_push_object(ctx);
  20083. duk_push_tval(ctx, &act->tv_func);
  20084. pc = (duk_uint_fast32_t) act->pc;
  20085. if (pc > 0) {
  20086. /* Relevant PC is just before current one because PC is
  20087. * post-incremented. This should match what error augment
  20088. * code does.
  20089. */
  20090. pc--;
  20091. }
  20092. duk_push_uint(ctx, (duk_uint_t) pc);
  20093. #if defined(DUK_USE_PC2LINE)
  20094. line = duk_hobject_pc2line_query(ctx, -2, pc);
  20095. #else
  20096. line = 0;
  20097. #endif
  20098. duk_push_uint(ctx, (duk_uint_t) line);
  20099. /* Providing access to e.g. act->lex_env would be dangerous: these
  20100. * internal structures must never be accessible to the application.
  20101. * Duktape relies on them having consistent data, and this consistency
  20102. * is only asserted for, not checked for.
  20103. */
  20104. /* [ level obj func pc line ] */
  20105. /* XXX: version specific array format instead? */
  20106. duk_xdef_prop_stridx_wec(ctx, -4, DUK_STRIDX_LINE_NUMBER);
  20107. duk_xdef_prop_stridx_wec(ctx, -3, DUK_STRIDX_PC);
  20108. duk_xdef_prop_stridx_wec(ctx, -2, DUK_STRIDX_LC_FUNCTION);
  20109. return 1;
  20110. }
  20111. DUK_INTERNAL duk_ret_t duk_bi_duktape_object_gc(duk_context *ctx) {
  20112. #ifdef DUK_USE_MARK_AND_SWEEP
  20113. duk_hthread *thr = (duk_hthread *) ctx;
  20114. duk_small_uint_t flags;
  20115. duk_bool_t rc;
  20116. flags = (duk_small_uint_t) duk_get_uint(ctx, 0);
  20117. rc = duk_heap_mark_and_sweep(thr->heap, flags);
  20118. /* XXX: Not sure what the best return value would be in the API.
  20119. * Return a boolean for now. Note that rc == 0 is success (true).
  20120. */
  20121. duk_push_boolean(ctx, !rc);
  20122. return 1;
  20123. #else
  20124. DUK_UNREF(ctx);
  20125. return 0;
  20126. #endif
  20127. }
  20128. DUK_INTERNAL duk_ret_t duk_bi_duktape_object_fin(duk_context *ctx) {
  20129. (void) duk_require_hobject(ctx, 0);
  20130. if (duk_get_top(ctx) >= 2) {
  20131. /* Set: currently a finalizer is disabled by setting it to
  20132. * undefined; this does not remove the property at the moment.
  20133. * The value could be type checked to be either a function
  20134. * or something else; if something else, the property could
  20135. * be deleted.
  20136. */
  20137. duk_set_top(ctx, 2);
  20138. (void) duk_put_prop_stridx(ctx, 0, DUK_STRIDX_INT_FINALIZER);
  20139. return 0;
  20140. } else {
  20141. /* Get. */
  20142. DUK_ASSERT(duk_get_top(ctx) == 1);
  20143. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_INT_FINALIZER);
  20144. return 1;
  20145. }
  20146. }
  20147. DUK_INTERNAL duk_ret_t duk_bi_duktape_object_enc(duk_context *ctx) {
  20148. duk_hthread *thr = (duk_hthread *) ctx;
  20149. duk_hstring *h_str;
  20150. /* Vararg function: must be careful to check/require arguments.
  20151. * The JSON helpers accept invalid indices and treat them like
  20152. * non-existent optional parameters.
  20153. */
  20154. h_str = duk_require_hstring(ctx, 0);
  20155. duk_require_valid_index(ctx, 1);
  20156. if (h_str == DUK_HTHREAD_STRING_HEX(thr)) {
  20157. duk_set_top(ctx, 2);
  20158. duk_hex_encode(ctx, 1);
  20159. DUK_ASSERT_TOP(ctx, 2);
  20160. } else if (h_str == DUK_HTHREAD_STRING_BASE64(thr)) {
  20161. duk_set_top(ctx, 2);
  20162. duk_base64_encode(ctx, 1);
  20163. DUK_ASSERT_TOP(ctx, 2);
  20164. #ifdef DUK_USE_JX
  20165. } else if (h_str == DUK_HTHREAD_STRING_JX(thr)) {
  20166. duk_bi_json_stringify_helper(ctx,
  20167. 1 /*idx_value*/,
  20168. 2 /*idx_replacer*/,
  20169. 3 /*idx_space*/,
  20170. DUK_JSON_FLAG_EXT_CUSTOM |
  20171. DUK_JSON_FLAG_ASCII_ONLY |
  20172. DUK_JSON_FLAG_AVOID_KEY_QUOTES /*flags*/);
  20173. #endif
  20174. #ifdef DUK_USE_JC
  20175. } else if (h_str == DUK_HTHREAD_STRING_JC(thr)) {
  20176. duk_bi_json_stringify_helper(ctx,
  20177. 1 /*idx_value*/,
  20178. 2 /*idx_replacer*/,
  20179. 3 /*idx_space*/,
  20180. DUK_JSON_FLAG_EXT_COMPATIBLE |
  20181. DUK_JSON_FLAG_ASCII_ONLY /*flags*/);
  20182. #endif
  20183. } else {
  20184. return DUK_RET_TYPE_ERROR;
  20185. }
  20186. return 1;
  20187. }
  20188. DUK_INTERNAL duk_ret_t duk_bi_duktape_object_dec(duk_context *ctx) {
  20189. duk_hthread *thr = (duk_hthread *) ctx;
  20190. duk_hstring *h_str;
  20191. /* Vararg function: must be careful to check/require arguments.
  20192. * The JSON helpers accept invalid indices and treat them like
  20193. * non-existent optional parameters.
  20194. */
  20195. h_str = duk_require_hstring(ctx, 0);
  20196. duk_require_valid_index(ctx, 1);
  20197. if (h_str == DUK_HTHREAD_STRING_HEX(thr)) {
  20198. duk_set_top(ctx, 2);
  20199. duk_hex_decode(ctx, 1);
  20200. DUK_ASSERT_TOP(ctx, 2);
  20201. } else if (h_str == DUK_HTHREAD_STRING_BASE64(thr)) {
  20202. duk_set_top(ctx, 2);
  20203. duk_base64_decode(ctx, 1);
  20204. DUK_ASSERT_TOP(ctx, 2);
  20205. #ifdef DUK_USE_JX
  20206. } else if (h_str == DUK_HTHREAD_STRING_JX(thr)) {
  20207. duk_bi_json_parse_helper(ctx,
  20208. 1 /*idx_value*/,
  20209. 2 /*idx_replacer*/,
  20210. DUK_JSON_FLAG_EXT_CUSTOM /*flags*/);
  20211. #endif
  20212. #ifdef DUK_USE_JC
  20213. } else if (h_str == DUK_HTHREAD_STRING_JC(thr)) {
  20214. duk_bi_json_parse_helper(ctx,
  20215. 1 /*idx_value*/,
  20216. 2 /*idx_replacer*/,
  20217. DUK_JSON_FLAG_EXT_COMPATIBLE /*flags*/);
  20218. #endif
  20219. } else {
  20220. return DUK_RET_TYPE_ERROR;
  20221. }
  20222. return 1;
  20223. }
  20224. /*
  20225. * Compact an object
  20226. */
  20227. DUK_INTERNAL duk_ret_t duk_bi_duktape_object_compact(duk_context *ctx) {
  20228. DUK_ASSERT_TOP(ctx, 1);
  20229. duk_compact(ctx, 0);
  20230. return 1; /* return the argument object */
  20231. }
  20232. #line 1 "duk_bi_error.c"
  20233. /*
  20234. * Error built-ins
  20235. */
  20236. /* include removed: duk_internal.h */
  20237. DUK_INTERNAL duk_ret_t duk_bi_error_constructor_shared(duk_context *ctx) {
  20238. /* Behavior for constructor and non-constructor call is
  20239. * the same except for augmenting the created error. When
  20240. * called as a constructor, the caller (duk_new()) will handle
  20241. * augmentation; when called as normal function, we need to do
  20242. * it here.
  20243. */
  20244. duk_hthread *thr = (duk_hthread *) ctx;
  20245. duk_small_int_t bidx_prototype = duk_get_current_magic(ctx);
  20246. /* same for both error and each subclass like TypeError */
  20247. duk_uint_t flags_and_class = DUK_HOBJECT_FLAG_EXTENSIBLE |
  20248. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_ERROR);
  20249. DUK_UNREF(thr);
  20250. duk_push_object_helper(ctx, flags_and_class, bidx_prototype);
  20251. /* If message is undefined, the own property 'message' is not set at
  20252. * all to save property space. An empty message is inherited anyway.
  20253. */
  20254. if (!duk_is_undefined(ctx, 0)) {
  20255. duk_to_string(ctx, 0);
  20256. duk_dup(ctx, 0); /* [ message error message ] */
  20257. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_MESSAGE, DUK_PROPDESC_FLAGS_WC);
  20258. }
  20259. /* Augment the error if called as a normal function. __FILE__ and __LINE__
  20260. * are not desirable in this case.
  20261. */
  20262. #ifdef DUK_USE_AUGMENT_ERROR_CREATE
  20263. if (!duk_is_constructor_call(ctx)) {
  20264. duk_err_augment_error_create(thr, thr, NULL, 0, 1 /*noblame_fileline*/);
  20265. }
  20266. #endif
  20267. return 1;
  20268. }
  20269. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_to_string(duk_context *ctx) {
  20270. /* XXX: optimize with more direct internal access */
  20271. duk_push_this(ctx);
  20272. (void) duk_require_hobject_or_lfunc_coerce(ctx, -1);
  20273. /* [ ... this ] */
  20274. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_NAME);
  20275. if (duk_is_undefined(ctx, -1)) {
  20276. duk_pop(ctx);
  20277. duk_push_string(ctx, "Error");
  20278. } else {
  20279. duk_to_string(ctx, -1);
  20280. }
  20281. /* [ ... this name ] */
  20282. /* XXX: Are steps 6 and 7 in E5 Section 15.11.4.4 duplicated by
  20283. * accident or are they actually needed? The first ToString()
  20284. * could conceivably return 'undefined'.
  20285. */
  20286. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_MESSAGE);
  20287. if (duk_is_undefined(ctx, -1)) {
  20288. duk_pop(ctx);
  20289. duk_push_string(ctx, "");
  20290. } else {
  20291. duk_to_string(ctx, -1);
  20292. }
  20293. /* [ ... this name message ] */
  20294. if (duk_get_length(ctx, -2) == 0) {
  20295. /* name is empty -> return message */
  20296. return 1;
  20297. }
  20298. if (duk_get_length(ctx, -1) == 0) {
  20299. /* message is empty -> return name */
  20300. duk_pop(ctx);
  20301. return 1;
  20302. }
  20303. duk_push_string(ctx, ": ");
  20304. duk_insert(ctx, -2); /* ... name ': ' message */
  20305. duk_concat(ctx, 3);
  20306. return 1;
  20307. }
  20308. #ifdef DUK_USE_TRACEBACKS
  20309. /*
  20310. * Traceback handling
  20311. *
  20312. * The unified helper decodes the traceback and produces various requested
  20313. * outputs. It should be optimized for size, and may leave garbage on stack,
  20314. * only the topmost return value matters. For instance, traceback separator
  20315. * and decoded strings are pushed even when looking for filename only.
  20316. *
  20317. * NOTE: although _Tracedata is an internal property, user code can currently
  20318. * write to the array (or replace it with something other than an array).
  20319. * The code below must tolerate arbitrary _Tracedata. It can throw errors
  20320. * etc, but cannot cause a segfault or memory unsafe behavior.
  20321. */
  20322. /* constants arbitrary, chosen for small loads */
  20323. #define DUK__OUTPUT_TYPE_TRACEBACK (-1)
  20324. #define DUK__OUTPUT_TYPE_FILENAME 0
  20325. #define DUK__OUTPUT_TYPE_LINENUMBER 1
  20326. DUK_LOCAL duk_ret_t duk__traceback_getter_helper(duk_context *ctx, duk_small_int_t output_type) {
  20327. duk_hthread *thr = (duk_hthread *) ctx;
  20328. duk_idx_t idx_td;
  20329. duk_small_int_t i; /* traceback depth fits into 16 bits */
  20330. duk_small_int_t t; /* stack type fits into 16 bits */
  20331. const char *str_tailcalled = " tailcalled";
  20332. const char *str_strict = " strict";
  20333. const char *str_construct = " construct";
  20334. const char *str_prevyield = " preventsyield";
  20335. const char *str_directeval = " directeval";
  20336. const char *str_empty = "";
  20337. DUK_ASSERT_TOP(ctx, 0); /* fixed arg count */
  20338. duk_push_this(ctx);
  20339. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_TRACEDATA);
  20340. idx_td = duk_get_top_index(ctx);
  20341. duk_push_hstring_stridx(ctx, DUK_STRIDX_NEWLINE_TAB);
  20342. duk_push_this(ctx);
  20343. duk_to_string(ctx, -1);
  20344. /* [ ... this tracedata sep ToString(this) ] */
  20345. /* XXX: skip null filename? */
  20346. if (duk_check_type(ctx, idx_td, DUK_TYPE_OBJECT)) {
  20347. /* Current tracedata contains 2 entries per callstack entry. */
  20348. for (i = 0; ; i += 2) {
  20349. duk_int_t pc;
  20350. duk_int_t line;
  20351. duk_int_t flags;
  20352. duk_double_t d;
  20353. const char *funcname;
  20354. const char *filename;
  20355. duk_hobject *h_func;
  20356. duk_hstring *h_name;
  20357. duk_require_stack(ctx, 5);
  20358. duk_get_prop_index(ctx, idx_td, i);
  20359. duk_get_prop_index(ctx, idx_td, i + 1);
  20360. d = duk_to_number(ctx, -1);
  20361. pc = (duk_int_t) DUK_FMOD(d, DUK_DOUBLE_2TO32);
  20362. flags = (duk_int_t) DUK_FLOOR(d / DUK_DOUBLE_2TO32);
  20363. t = (duk_small_int_t) duk_get_type(ctx, -2);
  20364. if (t == DUK_TYPE_OBJECT || t == DUK_TYPE_LIGHTFUNC) {
  20365. /*
  20366. * Ecmascript/native function call or lightfunc call
  20367. */
  20368. /* [ ... v1(func) v2(pc+flags) ] */
  20369. h_func = duk_get_hobject(ctx, -2); /* NULL for lightfunc */
  20370. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_NAME);
  20371. duk_get_prop_stridx(ctx, -3, DUK_STRIDX_FILE_NAME);
  20372. #if defined(DUK_USE_PC2LINE)
  20373. line = duk_hobject_pc2line_query(ctx, -4, (duk_uint_fast32_t) pc);
  20374. #else
  20375. line = 0;
  20376. #endif
  20377. /* [ ... v1 v2 name filename ] */
  20378. if (output_type == DUK__OUTPUT_TYPE_FILENAME) {
  20379. return 1;
  20380. } else if (output_type == DUK__OUTPUT_TYPE_LINENUMBER) {
  20381. duk_push_int(ctx, line);
  20382. return 1;
  20383. }
  20384. h_name = duk_get_hstring(ctx, -2); /* may be NULL */
  20385. funcname = (h_name == NULL || h_name == DUK_HTHREAD_STRING_EMPTY_STRING(thr)) ?
  20386. "anon" : (const char *) DUK_HSTRING_GET_DATA(h_name);
  20387. filename = duk_get_string(ctx, -1);
  20388. filename = filename ? filename : "";
  20389. DUK_ASSERT(funcname != NULL);
  20390. DUK_ASSERT(filename != NULL);
  20391. if (h_func == NULL) {
  20392. duk_push_sprintf(ctx, "%s light%s%s%s%s%s",
  20393. (const char *) funcname,
  20394. (const char *) ((flags & DUK_ACT_FLAG_STRICT) ? str_strict : str_empty),
  20395. (const char *) ((flags & DUK_ACT_FLAG_TAILCALLED) ? str_tailcalled : str_empty),
  20396. (const char *) ((flags & DUK_ACT_FLAG_CONSTRUCT) ? str_construct : str_empty),
  20397. (const char *) ((flags & DUK_ACT_FLAG_DIRECT_EVAL) ? str_directeval : str_empty),
  20398. (const char *) ((flags & DUK_ACT_FLAG_PREVENT_YIELD) ? str_prevyield : str_empty));
  20399. } else if (DUK_HOBJECT_HAS_NATIVEFUNCTION(h_func)) {
  20400. duk_push_sprintf(ctx, "%s %s native%s%s%s%s%s",
  20401. (const char *) funcname,
  20402. (const char *) filename,
  20403. (const char *) ((flags & DUK_ACT_FLAG_STRICT) ? str_strict : str_empty),
  20404. (const char *) ((flags & DUK_ACT_FLAG_TAILCALLED) ? str_tailcalled : str_empty),
  20405. (const char *) ((flags & DUK_ACT_FLAG_CONSTRUCT) ? str_construct : str_empty),
  20406. (const char *) ((flags & DUK_ACT_FLAG_DIRECT_EVAL) ? str_directeval : str_empty),
  20407. (const char *) ((flags & DUK_ACT_FLAG_PREVENT_YIELD) ? str_prevyield : str_empty));
  20408. } else {
  20409. duk_push_sprintf(ctx, "%s %s:%ld%s%s%s%s%s",
  20410. (const char *) funcname,
  20411. (const char *) filename,
  20412. (long) line,
  20413. (const char *) ((flags & DUK_ACT_FLAG_STRICT) ? str_strict : str_empty),
  20414. (const char *) ((flags & DUK_ACT_FLAG_TAILCALLED) ? str_tailcalled : str_empty),
  20415. (const char *) ((flags & DUK_ACT_FLAG_CONSTRUCT) ? str_construct : str_empty),
  20416. (const char *) ((flags & DUK_ACT_FLAG_DIRECT_EVAL) ? str_directeval : str_empty),
  20417. (const char *) ((flags & DUK_ACT_FLAG_PREVENT_YIELD) ? str_prevyield : str_empty));
  20418. }
  20419. duk_replace(ctx, -5); /* [ ... v1 v2 name filename str ] -> [ ... str v2 name filename ] */
  20420. duk_pop_n(ctx, 3); /* -> [ ... str ] */
  20421. } else if (t == DUK_TYPE_STRING) {
  20422. /*
  20423. * __FILE__ / __LINE__ entry, here 'pc' is line number directly.
  20424. * Sometimes __FILE__ / __LINE__ is reported as the source for
  20425. * the error (fileName, lineNumber), sometimes not.
  20426. */
  20427. /* [ ... v1(filename) v2(line+flags) ] */
  20428. if (!(flags & DUK_TB_FLAG_NOBLAME_FILELINE)) {
  20429. if (output_type == DUK__OUTPUT_TYPE_FILENAME) {
  20430. duk_pop(ctx);
  20431. return 1;
  20432. } else if (output_type == DUK__OUTPUT_TYPE_LINENUMBER) {
  20433. duk_push_int(ctx, pc);
  20434. return 1;
  20435. }
  20436. }
  20437. duk_push_sprintf(ctx, "%s:%ld",
  20438. (const char *) duk_get_string(ctx, -2), (long) pc);
  20439. duk_replace(ctx, -3); /* [ ... v1 v2 str ] -> [ ... str v2 ] */
  20440. duk_pop(ctx); /* -> [ ... str ] */
  20441. } else {
  20442. /* unknown, ignore */
  20443. duk_pop_2(ctx);
  20444. break;
  20445. }
  20446. }
  20447. if (i >= DUK_USE_TRACEBACK_DEPTH * 2) {
  20448. /* Possibly truncated; there is no explicit truncation
  20449. * marker so this is the best we can do.
  20450. */
  20451. duk_push_hstring_stridx(ctx, DUK_STRIDX_BRACKETED_ELLIPSIS);
  20452. }
  20453. }
  20454. /* [ ... this tracedata sep ToString(this) str1 ... strN ] */
  20455. if (output_type != DUK__OUTPUT_TYPE_TRACEBACK) {
  20456. return 0;
  20457. } else {
  20458. duk_join(ctx, duk_get_top(ctx) - (idx_td + 2) /*count, not including sep*/);
  20459. return 1;
  20460. }
  20461. }
  20462. /* XXX: output type could be encoded into native function 'magic' value to
  20463. * save space.
  20464. */
  20465. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_stack_getter(duk_context *ctx) {
  20466. return duk__traceback_getter_helper(ctx, DUK__OUTPUT_TYPE_TRACEBACK);
  20467. }
  20468. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_filename_getter(duk_context *ctx) {
  20469. return duk__traceback_getter_helper(ctx, DUK__OUTPUT_TYPE_FILENAME);
  20470. }
  20471. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_linenumber_getter(duk_context *ctx) {
  20472. return duk__traceback_getter_helper(ctx, DUK__OUTPUT_TYPE_LINENUMBER);
  20473. }
  20474. #undef DUK__OUTPUT_TYPE_TRACEBACK
  20475. #undef DUK__OUTPUT_TYPE_FILENAME
  20476. #undef DUK__OUTPUT_TYPE_LINENUMBER
  20477. #else /* DUK_USE_TRACEBACKS */
  20478. /*
  20479. * Traceback handling when tracebacks disabled.
  20480. *
  20481. * The fileName / lineNumber stubs are now necessary because built-in
  20482. * data will include the accessor properties in Error.prototype. If those
  20483. * are removed for builds without tracebacks, these can also be removed.
  20484. * 'stack' should still be present and produce a ToString() equivalent:
  20485. * this is useful for user code which prints a stacktrace and expects to
  20486. * see something useful. A normal stacktrace also begins with a ToString()
  20487. * of the error so this makes sense.
  20488. */
  20489. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_stack_getter(duk_context *ctx) {
  20490. /* XXX: remove this native function and map 'stack' accessor
  20491. * to the toString() implementation directly.
  20492. */
  20493. return duk_bi_error_prototype_to_string(ctx);
  20494. }
  20495. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_filename_getter(duk_context *ctx) {
  20496. DUK_UNREF(ctx);
  20497. return 0;
  20498. }
  20499. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_linenumber_getter(duk_context *ctx) {
  20500. DUK_UNREF(ctx);
  20501. return 0;
  20502. }
  20503. #endif /* DUK_USE_TRACEBACKS */
  20504. DUK_INTERNAL duk_ret_t duk_bi_error_prototype_nop_setter(duk_context *ctx) {
  20505. /* Attempt to write 'stack', 'fileName', 'lineNumber' is a silent no-op.
  20506. * User can use Object.defineProperty() to override this behavior.
  20507. */
  20508. DUK_ASSERT_TOP(ctx, 1); /* fixed arg count */
  20509. DUK_UNREF(ctx);
  20510. return 0;
  20511. }
  20512. #line 1 "duk_bi_function.c"
  20513. /*
  20514. * Function built-ins
  20515. */
  20516. /* include removed: duk_internal.h */
  20517. DUK_INTERNAL duk_ret_t duk_bi_function_constructor(duk_context *ctx) {
  20518. duk_hthread *thr = (duk_hthread *) ctx;
  20519. duk_hstring *h_sourcecode;
  20520. duk_idx_t nargs;
  20521. duk_idx_t i;
  20522. duk_small_uint_t comp_flags;
  20523. duk_hcompiledfunction *func;
  20524. duk_hobject *outer_lex_env;
  20525. duk_hobject *outer_var_env;
  20526. /* normal and constructor calls have identical semantics */
  20527. nargs = duk_get_top(ctx);
  20528. for (i = 0; i < nargs; i++) {
  20529. duk_to_string(ctx, i);
  20530. }
  20531. if (nargs == 0) {
  20532. duk_push_string(ctx, "");
  20533. duk_push_string(ctx, "");
  20534. } else if (nargs == 1) {
  20535. /* XXX: cover this with the generic >1 case? */
  20536. duk_push_string(ctx, "");
  20537. } else {
  20538. duk_insert(ctx, 0); /* [ arg1 ... argN-1 body] -> [body arg1 ... argN-1] */
  20539. duk_push_string(ctx, ",");
  20540. duk_insert(ctx, 1);
  20541. duk_join(ctx, nargs - 1);
  20542. }
  20543. /* [ body formals ], formals is comma separated list that needs to be parsed */
  20544. DUK_ASSERT_TOP(ctx, 2);
  20545. /* XXX: this placeholder is not always correct, but use for now.
  20546. * It will fail in corner cases; see test-dev-func-cons-args.js.
  20547. */
  20548. duk_push_string(ctx, "function(");
  20549. duk_dup(ctx, 1);
  20550. duk_push_string(ctx, "){");
  20551. duk_dup(ctx, 0);
  20552. duk_push_string(ctx, "}");
  20553. duk_concat(ctx, 5);
  20554. /* [ body formals source ] */
  20555. DUK_ASSERT_TOP(ctx, 3);
  20556. /* strictness is not inherited, intentional */
  20557. comp_flags = DUK_JS_COMPILE_FLAG_FUNCEXPR;
  20558. duk_push_hstring_stridx(ctx, DUK_STRIDX_COMPILE); /* XXX: copy from caller? */ /* XXX: ignored now */
  20559. h_sourcecode = duk_require_hstring(ctx, -2);
  20560. duk_js_compile(thr,
  20561. (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h_sourcecode),
  20562. (duk_size_t) DUK_HSTRING_GET_BYTELEN(h_sourcecode),
  20563. comp_flags);
  20564. func = (duk_hcompiledfunction *) duk_get_hobject(ctx, -1);
  20565. DUK_ASSERT(func != NULL);
  20566. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION((duk_hobject *) func));
  20567. /* [ body formals source template ] */
  20568. /* only outer_lex_env matters, as functions always get a new
  20569. * variable declaration environment.
  20570. */
  20571. outer_lex_env = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  20572. outer_var_env = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  20573. duk_js_push_closure(thr, func, outer_var_env, outer_lex_env);
  20574. /* [ body formals source template closure ] */
  20575. return 1;
  20576. }
  20577. DUK_INTERNAL duk_ret_t duk_bi_function_prototype(duk_context *ctx) {
  20578. /* ignore arguments, return undefined (E5 Section 15.3.4) */
  20579. DUK_UNREF(ctx);
  20580. return 0;
  20581. }
  20582. DUK_INTERNAL duk_ret_t duk_bi_function_prototype_to_string(duk_context *ctx) {
  20583. duk_tval *tv;
  20584. /*
  20585. * E5 Section 15.3.4.2 places few requirements on the output of
  20586. * this function:
  20587. *
  20588. * - The result is an implementation dependent representation
  20589. * of the function; in particular
  20590. *
  20591. * - The result must follow the syntax of a FunctionDeclaration.
  20592. * In particular, the function must have a name (even in the
  20593. * case of an anonymous function or a function with an empty
  20594. * name).
  20595. *
  20596. * - Note in particular that the output does NOT need to compile
  20597. * into anything useful.
  20598. */
  20599. /* XXX: faster internal way to get this */
  20600. duk_push_this(ctx);
  20601. tv = duk_get_tval(ctx, -1);
  20602. DUK_ASSERT(tv != NULL);
  20603. if (DUK_TVAL_IS_OBJECT(tv)) {
  20604. duk_hobject *obj = DUK_TVAL_GET_OBJECT(tv);
  20605. const char *func_name = DUK_STR_ANON;
  20606. /* XXX: rework, it would be nice to avoid C formatting functions to
  20607. * ensure there are no Unicode issues.
  20608. */
  20609. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_NAME);
  20610. if (!duk_is_undefined(ctx, -1)) {
  20611. func_name = duk_to_string(ctx, -1);
  20612. DUK_ASSERT(func_name != NULL);
  20613. if (func_name[0] == (char) 0) {
  20614. func_name = DUK_STR_ANON;
  20615. }
  20616. }
  20617. if (DUK_HOBJECT_HAS_COMPILEDFUNCTION(obj)) {
  20618. /* XXX: actual source, if available */
  20619. duk_push_sprintf(ctx, "function %s() {/* ecmascript */}", (const char *) func_name);
  20620. } else if (DUK_HOBJECT_HAS_NATIVEFUNCTION(obj)) {
  20621. duk_push_sprintf(ctx, "function %s() {/* native */}", (const char *) func_name);
  20622. } else if (DUK_HOBJECT_HAS_BOUND(obj)) {
  20623. duk_push_sprintf(ctx, "function %s() {/* bound */}", (const char *) func_name);
  20624. } else {
  20625. goto type_error;
  20626. }
  20627. } else if (DUK_TVAL_IS_LIGHTFUNC(tv)) {
  20628. duk_push_lightfunc_tostring(ctx, tv);
  20629. } else {
  20630. goto type_error;
  20631. }
  20632. return 1;
  20633. type_error:
  20634. return DUK_RET_TYPE_ERROR;
  20635. }
  20636. DUK_INTERNAL duk_ret_t duk_bi_function_prototype_apply(duk_context *ctx) {
  20637. duk_idx_t len;
  20638. duk_idx_t i;
  20639. DUK_ASSERT_TOP(ctx, 2); /* not a vararg function */
  20640. duk_push_this(ctx);
  20641. if (!duk_is_callable(ctx, -1)) {
  20642. DUK_DDD(DUK_DDDPRINT("func is not callable"));
  20643. goto type_error;
  20644. }
  20645. duk_insert(ctx, 0);
  20646. DUK_ASSERT_TOP(ctx, 3);
  20647. DUK_DDD(DUK_DDDPRINT("func=%!iT, thisArg=%!iT, argArray=%!iT",
  20648. (duk_tval *) duk_get_tval(ctx, 0),
  20649. (duk_tval *) duk_get_tval(ctx, 1),
  20650. (duk_tval *) duk_get_tval(ctx, 2)));
  20651. /* [ func thisArg argArray ] */
  20652. if (duk_is_null_or_undefined(ctx, 2)) {
  20653. DUK_DDD(DUK_DDDPRINT("argArray is null/undefined, no args"));
  20654. len = 0;
  20655. } else if (!duk_is_object(ctx, 2)) {
  20656. goto type_error;
  20657. } else {
  20658. DUK_DDD(DUK_DDDPRINT("argArray is an object"));
  20659. /* XXX: make this an internal helper */
  20660. duk_get_prop_stridx(ctx, 2, DUK_STRIDX_LENGTH);
  20661. len = (duk_idx_t) duk_to_uint32(ctx, -1); /* ToUint32() coercion required */
  20662. duk_pop(ctx);
  20663. duk_require_stack(ctx, len);
  20664. DUK_DDD(DUK_DDDPRINT("argArray length is %ld", (long) len));
  20665. for (i = 0; i < len; i++) {
  20666. duk_get_prop_index(ctx, 2, i);
  20667. }
  20668. }
  20669. duk_remove(ctx, 2);
  20670. DUK_ASSERT_TOP(ctx, 2 + len);
  20671. /* [ func thisArg arg1 ... argN ] */
  20672. DUK_DDD(DUK_DDDPRINT("apply, func=%!iT, thisArg=%!iT, len=%ld",
  20673. (duk_tval *) duk_get_tval(ctx, 0),
  20674. (duk_tval *) duk_get_tval(ctx, 1),
  20675. (long) len));
  20676. duk_call_method(ctx, len);
  20677. return 1;
  20678. type_error:
  20679. return DUK_RET_TYPE_ERROR;
  20680. }
  20681. DUK_INTERNAL duk_ret_t duk_bi_function_prototype_call(duk_context *ctx) {
  20682. duk_idx_t nargs;
  20683. /* Step 1 is not necessary because duk_call_method() will take
  20684. * care of it.
  20685. */
  20686. /* vararg function, thisArg needs special handling */
  20687. nargs = duk_get_top(ctx); /* = 1 + arg count */
  20688. if (nargs == 0) {
  20689. duk_push_undefined(ctx);
  20690. nargs++;
  20691. }
  20692. DUK_ASSERT(nargs >= 1);
  20693. /* [ thisArg arg1 ... argN ] */
  20694. duk_push_this(ctx); /* 'func' in the algorithm */
  20695. duk_insert(ctx, 0);
  20696. /* [ func thisArg arg1 ... argN ] */
  20697. DUK_DDD(DUK_DDDPRINT("func=%!iT, thisArg=%!iT, argcount=%ld, top=%ld",
  20698. (duk_tval *) duk_get_tval(ctx, 0),
  20699. (duk_tval *) duk_get_tval(ctx, 1),
  20700. (long) (nargs - 1),
  20701. (long) duk_get_top(ctx)));
  20702. duk_call_method(ctx, nargs - 1);
  20703. return 1;
  20704. }
  20705. /* XXX: the implementation now assumes "chained" bound functions,
  20706. * whereas "collapsed" bound functions (where there is ever only
  20707. * one bound function which directly points to a non-bound, final
  20708. * function) would require a "collapsing" implementation which
  20709. * merges argument lists etc here.
  20710. */
  20711. DUK_INTERNAL duk_ret_t duk_bi_function_prototype_bind(duk_context *ctx) {
  20712. duk_hobject *h_bound;
  20713. duk_hobject *h_target;
  20714. duk_idx_t nargs;
  20715. duk_idx_t i;
  20716. /* vararg function, careful arg handling (e.g. thisArg may not be present) */
  20717. nargs = duk_get_top(ctx); /* = 1 + arg count */
  20718. if (nargs == 0) {
  20719. duk_push_undefined(ctx);
  20720. nargs++;
  20721. }
  20722. DUK_ASSERT(nargs >= 1);
  20723. duk_push_this(ctx);
  20724. if (!duk_is_callable(ctx, -1)) {
  20725. DUK_DDD(DUK_DDDPRINT("func is not callable"));
  20726. goto type_error;
  20727. }
  20728. /* [ thisArg arg1 ... argN func ] (thisArg+args == nargs total) */
  20729. DUK_ASSERT_TOP(ctx, nargs + 1);
  20730. /* create bound function object */
  20731. duk_push_object_helper(ctx,
  20732. DUK_HOBJECT_FLAG_EXTENSIBLE |
  20733. DUK_HOBJECT_FLAG_BOUND |
  20734. DUK_HOBJECT_FLAG_CONSTRUCTABLE |
  20735. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_FUNCTION),
  20736. DUK_BIDX_FUNCTION_PROTOTYPE);
  20737. h_bound = duk_get_hobject(ctx, -1);
  20738. DUK_ASSERT(h_bound != NULL);
  20739. /* [ thisArg arg1 ... argN func boundFunc ] */
  20740. duk_dup(ctx, -2); /* func */
  20741. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_TARGET, DUK_PROPDESC_FLAGS_NONE);
  20742. duk_dup(ctx, 0); /* thisArg */
  20743. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_THIS, DUK_PROPDESC_FLAGS_NONE);
  20744. duk_push_array(ctx);
  20745. /* [ thisArg arg1 ... argN func boundFunc argArray ] */
  20746. for (i = 0; i < nargs - 1; i++) {
  20747. duk_dup(ctx, 1 + i);
  20748. duk_put_prop_index(ctx, -2, i);
  20749. }
  20750. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_ARGS, DUK_PROPDESC_FLAGS_NONE);
  20751. /* [ thisArg arg1 ... argN func boundFunc ] */
  20752. /* bound function 'length' property is interesting */
  20753. h_target = duk_get_hobject(ctx, -2);
  20754. if (h_target == NULL || /* lightfunc */
  20755. DUK_HOBJECT_GET_CLASS_NUMBER(h_target) == DUK_HOBJECT_CLASS_FUNCTION) {
  20756. /* For lightfuncs, simply read the virtual property. */
  20757. duk_int_t tmp;
  20758. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH);
  20759. tmp = duk_to_int(ctx, -1) - (nargs - 1); /* step 15.a */
  20760. duk_pop(ctx);
  20761. duk_push_int(ctx, (tmp < 0 ? 0 : tmp));
  20762. } else {
  20763. duk_push_int(ctx, 0);
  20764. }
  20765. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_NONE); /* attrs in E5 Section 15.3.5.1 */
  20766. /* caller and arguments must use the same thrower, [[ThrowTypeError]] */
  20767. duk_xdef_prop_stridx_thrower(ctx, -1, DUK_STRIDX_CALLER, DUK_PROPDESC_FLAGS_NONE);
  20768. duk_xdef_prop_stridx_thrower(ctx, -1, DUK_STRIDX_LC_ARGUMENTS, DUK_PROPDESC_FLAGS_NONE);
  20769. /* these non-standard properties are copied for convenience */
  20770. /* XXX: 'copy properties' API call? */
  20771. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_NAME);
  20772. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_NAME, DUK_PROPDESC_FLAGS_WC);
  20773. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_FILE_NAME);
  20774. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_FILE_NAME, DUK_PROPDESC_FLAGS_WC);
  20775. /* The 'strict' flag is copied to get the special [[Get]] of E5.1
  20776. * Section 15.3.5.4 to apply when a 'caller' value is a strict bound
  20777. * function. Not sure if this is correct, because the specification
  20778. * is a bit ambiguous on this point but it would make sense.
  20779. */
  20780. if (h_target == NULL) {
  20781. /* Lightfuncs are always strict. */
  20782. DUK_HOBJECT_SET_STRICT(h_bound);
  20783. } else if (DUK_HOBJECT_HAS_STRICT(h_target)) {
  20784. DUK_HOBJECT_SET_STRICT(h_bound);
  20785. }
  20786. DUK_DDD(DUK_DDDPRINT("created bound function: %!iT", (duk_tval *) duk_get_tval(ctx, -1)));
  20787. return 1;
  20788. type_error:
  20789. return DUK_RET_TYPE_ERROR;
  20790. }
  20791. #line 1 "duk_bi_global.c"
  20792. /*
  20793. * Global object built-ins
  20794. */
  20795. /* include removed: duk_internal.h */
  20796. /*
  20797. * Encoding/decoding helpers
  20798. */
  20799. /* Macros for creating and checking bitmasks for character encoding.
  20800. * Bit number is a bit counterintuitive, but minimizes code size.
  20801. */
  20802. #define DUK__MKBITS(a,b,c,d,e,f,g,h) ((duk_uint8_t) ( \
  20803. ((a) << 0) | ((b) << 1) | ((c) << 2) | ((d) << 3) | \
  20804. ((e) << 4) | ((f) << 5) | ((g) << 6) | ((h) << 7) \
  20805. ))
  20806. #define DUK__CHECK_BITMASK(table,cp) ((table)[(cp) >> 3] & (1 << ((cp) & 0x07)))
  20807. /* E5.1 Section 15.1.3.3: uriReserved + uriUnescaped + '#' */
  20808. DUK_LOCAL const duk_uint8_t duk__encode_uriunescaped_table[16] = {
  20809. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x00-0x0f */
  20810. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x10-0x1f */
  20811. DUK__MKBITS(0, 1, 0, 1, 1, 0, 1, 1), DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), /* 0x20-0x2f */
  20812. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 1, 0, 1, 0, 1), /* 0x30-0x3f */
  20813. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), /* 0x40-0x4f */
  20814. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 0, 0, 0, 0, 1), /* 0x50-0x5f */
  20815. DUK__MKBITS(0, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), /* 0x60-0x6f */
  20816. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 0, 0, 0, 1, 0), /* 0x70-0x7f */
  20817. };
  20818. /* E5.1 Section 15.1.3.4: uriUnescaped */
  20819. DUK_LOCAL const duk_uint8_t duk__encode_uricomponent_unescaped_table[16] = {
  20820. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x00-0x0f */
  20821. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x10-0x1f */
  20822. DUK__MKBITS(0, 1, 0, 0, 0, 0, 0, 1), DUK__MKBITS(1, 1, 1, 0, 0, 1, 1, 0), /* 0x20-0x2f */
  20823. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 0, 0, 0, 0, 0, 0), /* 0x30-0x3f */
  20824. DUK__MKBITS(0, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), /* 0x40-0x4f */
  20825. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 0, 0, 0, 0, 1), /* 0x50-0x5f */
  20826. DUK__MKBITS(0, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), /* 0x60-0x6f */
  20827. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 0, 0, 0, 1, 0), /* 0x70-0x7f */
  20828. };
  20829. /* E5.1 Section 15.1.3.1: uriReserved + '#' */
  20830. DUK_LOCAL const duk_uint8_t duk__decode_uri_reserved_table[16] = {
  20831. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x00-0x0f */
  20832. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x10-0x1f */
  20833. DUK__MKBITS(0, 0, 0, 1, 1, 0, 1, 0), DUK__MKBITS(0, 0, 0, 1, 1, 0, 0, 1), /* 0x20-0x2f */
  20834. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 1, 1, 0, 1, 0, 1), /* 0x30-0x3f */
  20835. DUK__MKBITS(1, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x40-0x4f */
  20836. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x50-0x5f */
  20837. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x60-0x6f */
  20838. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x70-0x7f */
  20839. };
  20840. /* E5.1 Section 15.1.3.2: empty */
  20841. DUK_LOCAL const duk_uint8_t duk__decode_uri_component_reserved_table[16] = {
  20842. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x00-0x0f */
  20843. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x10-0x1f */
  20844. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x20-0x2f */
  20845. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x30-0x3f */
  20846. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x40-0x4f */
  20847. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x50-0x5f */
  20848. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x60-0x6f */
  20849. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x70-0x7f */
  20850. };
  20851. #ifdef DUK_USE_SECTION_B
  20852. /* E5.1 Section B.2.2, step 7. */
  20853. DUK_LOCAL const duk_uint8_t duk__escape_unescaped_table[16] = {
  20854. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x00-0x0f */
  20855. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), /* 0x10-0x1f */
  20856. DUK__MKBITS(0, 0, 0, 0, 0, 0, 0, 0), DUK__MKBITS(0, 0, 1, 1, 0, 1, 1, 1), /* 0x20-0x2f */
  20857. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 0, 0, 0, 0, 0, 0), /* 0x30-0x3f */
  20858. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), /* 0x40-0x4f */
  20859. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 0, 0, 0, 0, 1), /* 0x50-0x5f */
  20860. DUK__MKBITS(0, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), /* 0x60-0x6f */
  20861. DUK__MKBITS(1, 1, 1, 1, 1, 1, 1, 1), DUK__MKBITS(1, 1, 1, 0, 0, 0, 0, 0) /* 0x70-0x7f */
  20862. };
  20863. #endif /* DUK_USE_SECTION_B */
  20864. typedef struct {
  20865. duk_hthread *thr;
  20866. duk_hstring *h_str;
  20867. duk_hbuffer_dynamic *h_buf;
  20868. const duk_uint8_t *p;
  20869. const duk_uint8_t *p_start;
  20870. const duk_uint8_t *p_end;
  20871. } duk__transform_context;
  20872. typedef void (*duk__transform_callback)(duk__transform_context *tfm_ctx, void *udata, duk_codepoint_t cp);
  20873. /* XXX: refactor and share with other code */
  20874. DUK_LOCAL duk_small_int_t duk__decode_hex_escape(const duk_uint8_t *p, duk_small_int_t n) {
  20875. duk_small_int_t ch;
  20876. duk_small_int_t t = 0;
  20877. while (n > 0) {
  20878. t = t * 16;
  20879. ch = (duk_small_int_t) duk_hex_dectab[*p++];
  20880. if (DUK_LIKELY(ch >= 0)) {
  20881. t += ch;
  20882. } else {
  20883. return -1;
  20884. }
  20885. n--;
  20886. }
  20887. return t;
  20888. }
  20889. DUK_LOCAL int duk__transform_helper(duk_context *ctx, duk__transform_callback callback, void *udata) {
  20890. duk_hthread *thr = (duk_hthread *) ctx;
  20891. duk__transform_context tfm_ctx_alloc;
  20892. duk__transform_context *tfm_ctx = &tfm_ctx_alloc;
  20893. duk_codepoint_t cp;
  20894. tfm_ctx->thr = thr;
  20895. tfm_ctx->h_str = duk_to_hstring(ctx, 0);
  20896. DUK_ASSERT(tfm_ctx->h_str != NULL);
  20897. (void) duk_push_dynamic_buffer(ctx, 0);
  20898. tfm_ctx->h_buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  20899. DUK_ASSERT(tfm_ctx->h_buf != NULL);
  20900. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(tfm_ctx->h_buf));
  20901. tfm_ctx->p_start = DUK_HSTRING_GET_DATA(tfm_ctx->h_str);
  20902. tfm_ctx->p_end = tfm_ctx->p_start + DUK_HSTRING_GET_BYTELEN(tfm_ctx->h_str);
  20903. tfm_ctx->p = tfm_ctx->p_start;
  20904. while (tfm_ctx->p < tfm_ctx->p_end) {
  20905. cp = (duk_codepoint_t) duk_unicode_decode_xutf8_checked(thr, &tfm_ctx->p, tfm_ctx->p_start, tfm_ctx->p_end);
  20906. callback(tfm_ctx, udata, cp);
  20907. }
  20908. duk_to_string(ctx, -1);
  20909. return 1;
  20910. }
  20911. DUK_LOCAL void duk__transform_callback_encode_uri(duk__transform_context *tfm_ctx, void *udata, duk_codepoint_t cp) {
  20912. duk_uint8_t xutf8_buf[DUK_UNICODE_MAX_XUTF8_LENGTH];
  20913. duk_uint8_t buf[3];
  20914. duk_small_int_t len;
  20915. duk_codepoint_t cp1, cp2;
  20916. duk_small_int_t i, t;
  20917. const duk_uint8_t *unescaped_table = (duk_uint8_t *) udata;
  20918. if (cp < 0) {
  20919. goto uri_error;
  20920. } else if ((cp < 0x80L) && DUK__CHECK_BITMASK(unescaped_table, cp)) {
  20921. duk_hbuffer_append_byte(tfm_ctx->thr, tfm_ctx->h_buf, (duk_uint8_t) cp);
  20922. return;
  20923. } else if (cp >= 0xdc00L && cp <= 0xdfffL) {
  20924. goto uri_error;
  20925. } else if (cp >= 0xd800L && cp <= 0xdbffL) {
  20926. /* Needs lookahead */
  20927. if (duk_unicode_decode_xutf8(tfm_ctx->thr, &tfm_ctx->p, tfm_ctx->p_start, tfm_ctx->p_end, (duk_ucodepoint_t *) &cp2) == 0) {
  20928. goto uri_error;
  20929. }
  20930. if (!(cp2 >= 0xdc00L && cp2 <= 0xdfffL)) {
  20931. goto uri_error;
  20932. }
  20933. cp1 = cp;
  20934. cp = ((cp1 - 0xd800L) << 10) + (cp2 - 0xdc00L) + 0x10000L;
  20935. } else if (cp > 0x10ffffL) {
  20936. /* Although we can allow non-BMP characters (they'll decode
  20937. * back into surrogate pairs), we don't allow extended UTF-8
  20938. * characters; they would encode to URIs which won't decode
  20939. * back because of strict UTF-8 checks in URI decoding.
  20940. * (However, we could just as well allow them here.)
  20941. */
  20942. goto uri_error;
  20943. } else {
  20944. /* Non-BMP characters within valid UTF-8 range: encode as is.
  20945. * They'll decode back into surrogate pairs.
  20946. */
  20947. ;
  20948. }
  20949. len = duk_unicode_encode_xutf8((duk_ucodepoint_t) cp, xutf8_buf);
  20950. buf[0] = (duk_uint8_t) '%';
  20951. for (i = 0; i < len; i++) {
  20952. t = (int) xutf8_buf[i];
  20953. buf[1] = (duk_uint8_t) duk_uc_nybbles[t >> 4];
  20954. buf[2] = (duk_uint8_t) duk_uc_nybbles[t & 0x0f];
  20955. duk_hbuffer_append_bytes(tfm_ctx->thr, tfm_ctx->h_buf, buf, 3);
  20956. }
  20957. return;
  20958. uri_error:
  20959. DUK_ERROR(tfm_ctx->thr, DUK_ERR_URI_ERROR, "invalid input");
  20960. }
  20961. DUK_LOCAL void duk__transform_callback_decode_uri(duk__transform_context *tfm_ctx, void *udata, duk_codepoint_t cp) {
  20962. const duk_uint8_t *reserved_table = (duk_uint8_t *) udata;
  20963. duk_small_uint_t utf8_blen;
  20964. duk_codepoint_t min_cp;
  20965. duk_small_int_t t; /* must be signed */
  20966. duk_small_uint_t i;
  20967. if (cp == (duk_codepoint_t) '%') {
  20968. const duk_uint8_t *p = tfm_ctx->p;
  20969. duk_size_t left = (duk_size_t) (tfm_ctx->p_end - p); /* bytes left */
  20970. DUK_DDD(DUK_DDDPRINT("percent encoding, left=%ld", (long) left));
  20971. if (left < 2) {
  20972. goto uri_error;
  20973. }
  20974. t = duk__decode_hex_escape(p, 2);
  20975. DUK_DDD(DUK_DDDPRINT("first byte: %ld", (long) t));
  20976. if (t < 0) {
  20977. goto uri_error;
  20978. }
  20979. if (t < 0x80) {
  20980. if (DUK__CHECK_BITMASK(reserved_table, t)) {
  20981. /* decode '%xx' to '%xx' if decoded char in reserved set */
  20982. DUK_ASSERT(tfm_ctx->p - 1 >= tfm_ctx->p_start);
  20983. duk_hbuffer_append_bytes(tfm_ctx->thr, tfm_ctx->h_buf, (duk_uint8_t *) (p - 1), 3);
  20984. } else {
  20985. duk_hbuffer_append_byte(tfm_ctx->thr, tfm_ctx->h_buf, (duk_uint8_t) t);
  20986. }
  20987. tfm_ctx->p += 2;
  20988. return;
  20989. }
  20990. /* Decode UTF-8 codepoint from a sequence of hex escapes. The
  20991. * first byte of the sequence has been decoded to 't'.
  20992. *
  20993. * Note that UTF-8 validation must be strict according to the
  20994. * specification: E5.1 Section 15.1.3, decode algorithm step
  20995. * 4.d.vii.8. URIError from non-shortest encodings is also
  20996. * specifically noted in the spec.
  20997. */
  20998. DUK_ASSERT(t >= 0x80);
  20999. if (t < 0xc0) {
  21000. /* continuation byte */
  21001. goto uri_error;
  21002. } else if (t < 0xe0) {
  21003. /* 110x xxxx; 2 bytes */
  21004. utf8_blen = 2;
  21005. min_cp = 0x80L;
  21006. cp = t & 0x1f;
  21007. } else if (t < 0xf0) {
  21008. /* 1110 xxxx; 3 bytes */
  21009. utf8_blen = 3;
  21010. min_cp = 0x800L;
  21011. cp = t & 0x0f;
  21012. } else if (t < 0xf8) {
  21013. /* 1111 0xxx; 4 bytes */
  21014. utf8_blen = 4;
  21015. min_cp = 0x10000L;
  21016. cp = t & 0x07;
  21017. } else {
  21018. /* extended utf-8 not allowed for URIs */
  21019. goto uri_error;
  21020. }
  21021. if (left < utf8_blen * 3 - 1) {
  21022. /* '%xx%xx...%xx', p points to char after first '%' */
  21023. goto uri_error;
  21024. }
  21025. p += 3;
  21026. for (i = 1; i < utf8_blen; i++) {
  21027. /* p points to digit part ('%xy', p points to 'x') */
  21028. t = duk__decode_hex_escape(p, 2);
  21029. DUK_DDD(DUK_DDDPRINT("i=%ld utf8_blen=%ld cp=%ld t=0x%02lx",
  21030. (long) i, (long) utf8_blen, (long) cp, (unsigned long) t));
  21031. if (t < 0) {
  21032. goto uri_error;
  21033. }
  21034. if ((t & 0xc0) != 0x80) {
  21035. goto uri_error;
  21036. }
  21037. cp = (cp << 6) + (t & 0x3f);
  21038. p += 3;
  21039. }
  21040. p--; /* p overshoots */
  21041. tfm_ctx->p = p;
  21042. DUK_DDD(DUK_DDDPRINT("final cp=%ld, min_cp=%ld", (long) cp, (long) min_cp));
  21043. if (cp < min_cp || cp > 0x10ffffL || (cp >= 0xd800L && cp <= 0xdfffL)) {
  21044. goto uri_error;
  21045. }
  21046. /* The E5.1 algorithm checks whether or not a decoded codepoint
  21047. * is below 0x80 and perhaps may be in the "reserved" set.
  21048. * This seems pointless because the single byte UTF-8 case is
  21049. * handled separately, and non-shortest encodings are rejected.
  21050. * So, 'cp' cannot be below 0x80 here, and thus cannot be in
  21051. * the reserved set.
  21052. */
  21053. /* utf-8 validation ensures these */
  21054. DUK_ASSERT(cp >= 0x80L && cp <= 0x10ffffL);
  21055. if (cp >= 0x10000L) {
  21056. cp -= 0x10000L;
  21057. DUK_ASSERT(cp < 0x100000L);
  21058. duk_hbuffer_append_xutf8(tfm_ctx->thr, tfm_ctx->h_buf, (duk_ucodepoint_t) ((cp >> 10) + 0xd800L));
  21059. duk_hbuffer_append_xutf8(tfm_ctx->thr, tfm_ctx->h_buf, (duk_ucodepoint_t) ((cp & 0x03ffUL) + 0xdc00L));
  21060. } else {
  21061. duk_hbuffer_append_xutf8(tfm_ctx->thr, tfm_ctx->h_buf, (duk_ucodepoint_t) cp);
  21062. }
  21063. } else {
  21064. duk_hbuffer_append_xutf8(tfm_ctx->thr, tfm_ctx->h_buf, (duk_ucodepoint_t) cp);
  21065. }
  21066. return;
  21067. uri_error:
  21068. DUK_ERROR(tfm_ctx->thr, DUK_ERR_URI_ERROR, "invalid input");
  21069. }
  21070. #ifdef DUK_USE_SECTION_B
  21071. DUK_LOCAL void duk__transform_callback_escape(duk__transform_context *tfm_ctx, void *udata, duk_codepoint_t cp) {
  21072. duk_uint8_t buf[6];
  21073. duk_small_int_t len;
  21074. DUK_UNREF(udata);
  21075. if (cp < 0) {
  21076. goto esc_error;
  21077. } else if ((cp < 0x80L) && DUK__CHECK_BITMASK(duk__escape_unescaped_table, cp)) {
  21078. buf[0] = (duk_uint8_t) cp;
  21079. len = 1;
  21080. } else if (cp < 0x100L) {
  21081. buf[0] = (duk_uint8_t) '%';
  21082. buf[1] = (duk_uint8_t) duk_uc_nybbles[cp >> 4];
  21083. buf[2] = (duk_uint8_t) duk_uc_nybbles[cp & 0x0f];
  21084. len = 3;
  21085. } else if (cp < 0x10000L) {
  21086. buf[0] = (duk_uint8_t) '%';
  21087. buf[1] = (duk_uint8_t) 'u';
  21088. buf[2] = (duk_uint8_t) duk_uc_nybbles[cp >> 12];
  21089. buf[3] = (duk_uint8_t) duk_uc_nybbles[(cp >> 8) & 0x0f];
  21090. buf[4] = (duk_uint8_t) duk_uc_nybbles[(cp >> 4) & 0x0f];
  21091. buf[5] = (duk_uint8_t) duk_uc_nybbles[cp & 0x0f];
  21092. len = 6;
  21093. } else {
  21094. /* Characters outside BMP cannot be escape()'d. We could
  21095. * encode them as surrogate pairs (for codepoints inside
  21096. * valid UTF-8 range, but not extended UTF-8). Because
  21097. * escape() and unescape() are legacy functions, we don't.
  21098. */
  21099. goto esc_error;
  21100. }
  21101. duk_hbuffer_append_bytes(tfm_ctx->thr, tfm_ctx->h_buf, buf, len);
  21102. return;
  21103. esc_error:
  21104. DUK_ERROR(tfm_ctx->thr, DUK_ERR_TYPE_ERROR, "invalid input");
  21105. }
  21106. DUK_LOCAL void duk__transform_callback_unescape(duk__transform_context *tfm_ctx, void *udata, duk_codepoint_t cp) {
  21107. duk_small_int_t t;
  21108. DUK_UNREF(udata);
  21109. if (cp == (duk_codepoint_t) '%') {
  21110. const duk_uint8_t *p = tfm_ctx->p;
  21111. duk_size_t left = (duk_size_t) (tfm_ctx->p_end - p); /* bytes left */
  21112. if (left >= 5 && p[0] == 'u' &&
  21113. ((t = duk__decode_hex_escape(p + 1, 4)) >= 0)) {
  21114. cp = (duk_codepoint_t) t;
  21115. tfm_ctx->p += 5;
  21116. } else if (left >= 2 &&
  21117. ((t = duk__decode_hex_escape(p, 2)) >= 0)) {
  21118. cp = (duk_codepoint_t) t;
  21119. tfm_ctx->p += 2;
  21120. }
  21121. }
  21122. duk_hbuffer_append_xutf8(tfm_ctx->thr, tfm_ctx->h_buf, cp);
  21123. }
  21124. #endif /* DUK_USE_SECTION_B */
  21125. /*
  21126. * Eval
  21127. *
  21128. * Eval needs to handle both a "direct eval" and an "indirect eval".
  21129. * Direct eval handling needs access to the caller's activation so that its
  21130. * lexical environment can be accessed. A direct eval is only possible from
  21131. * Ecmascript code; an indirect eval call is possible also from C code.
  21132. * When an indirect eval call is made from C code, there may not be a
  21133. * calling activation at all which needs careful handling.
  21134. */
  21135. DUK_INTERNAL duk_ret_t duk_bi_global_object_eval(duk_context *ctx) {
  21136. duk_hthread *thr = (duk_hthread *) ctx;
  21137. duk_hstring *h;
  21138. duk_activation *act_caller;
  21139. duk_activation *act_eval;
  21140. duk_activation *act;
  21141. duk_hcompiledfunction *func;
  21142. duk_hobject *outer_lex_env;
  21143. duk_hobject *outer_var_env;
  21144. duk_bool_t this_to_global = 1;
  21145. duk_small_uint_t comp_flags;
  21146. DUK_ASSERT_TOP(ctx, 1);
  21147. DUK_ASSERT(thr->callstack_top >= 1); /* at least this function exists */
  21148. DUK_ASSERT(((thr->callstack + thr->callstack_top - 1)->flags & DUK_ACT_FLAG_DIRECT_EVAL) == 0 || /* indirect eval */
  21149. (thr->callstack_top >= 2)); /* if direct eval, calling activation must exist */
  21150. /*
  21151. * callstack_top - 1 --> this function
  21152. * callstack_top - 2 --> caller (may not exist)
  21153. *
  21154. * If called directly from C, callstack_top might be 1. If calling
  21155. * activation doesn't exist, call must be indirect.
  21156. */
  21157. h = duk_get_hstring(ctx, 0);
  21158. if (!h) {
  21159. return 1; /* return arg as-is */
  21160. }
  21161. /* [ source ] */
  21162. comp_flags = DUK_JS_COMPILE_FLAG_EVAL;
  21163. act_eval = thr->callstack + thr->callstack_top - 1; /* this function */
  21164. if (thr->callstack_top >= 2) {
  21165. /* Have a calling activation, check for direct eval (otherwise
  21166. * assume indirect eval.
  21167. */
  21168. act_caller = thr->callstack + thr->callstack_top - 2; /* caller */
  21169. if ((act_caller->flags & DUK_ACT_FLAG_STRICT) &&
  21170. (act_eval->flags & DUK_ACT_FLAG_DIRECT_EVAL)) {
  21171. /* Only direct eval inherits strictness from calling code
  21172. * (E5.1 Section 10.1.1).
  21173. */
  21174. comp_flags |= DUK_JS_COMPILE_FLAG_STRICT;
  21175. }
  21176. } else {
  21177. DUK_ASSERT((act_eval->flags & DUK_ACT_FLAG_DIRECT_EVAL) == 0);
  21178. }
  21179. act_caller = NULL; /* avoid dereference after potential callstack realloc */
  21180. act_eval = NULL;
  21181. duk_push_hstring_stridx(ctx, DUK_STRIDX_INPUT); /* XXX: copy from caller? */
  21182. duk_js_compile(thr,
  21183. (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h),
  21184. (duk_size_t) DUK_HSTRING_GET_BYTELEN(h),
  21185. comp_flags);
  21186. func = (duk_hcompiledfunction *) duk_get_hobject(ctx, -1);
  21187. DUK_ASSERT(func != NULL);
  21188. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION((duk_hobject *) func));
  21189. /* [ source template ] */
  21190. /* E5 Section 10.4.2 */
  21191. DUK_ASSERT(thr->callstack_top >= 1);
  21192. act = thr->callstack + thr->callstack_top - 1; /* this function */
  21193. if (act->flags & DUK_ACT_FLAG_DIRECT_EVAL) {
  21194. DUK_ASSERT(thr->callstack_top >= 2);
  21195. act = thr->callstack + thr->callstack_top - 2; /* caller */
  21196. if (act->lex_env == NULL) {
  21197. DUK_ASSERT(act->var_env == NULL);
  21198. DUK_DDD(DUK_DDDPRINT("delayed environment initialization"));
  21199. /* this may have side effects, so re-lookup act */
  21200. duk_js_init_activation_environment_records_delayed(thr, act);
  21201. act = thr->callstack + thr->callstack_top - 2;
  21202. }
  21203. DUK_ASSERT(act->lex_env != NULL);
  21204. DUK_ASSERT(act->var_env != NULL);
  21205. this_to_global = 0;
  21206. if (DUK_HOBJECT_HAS_STRICT((duk_hobject *) func)) {
  21207. duk_hobject *new_env;
  21208. duk_hobject *act_lex_env;
  21209. DUK_DDD(DUK_DDDPRINT("direct eval call to a strict function -> "
  21210. "var_env and lex_env to a fresh env, "
  21211. "this_binding to caller's this_binding"));
  21212. act = thr->callstack + thr->callstack_top - 2; /* caller */
  21213. act_lex_env = act->lex_env;
  21214. act = NULL; /* invalidated */
  21215. (void) duk_push_object_helper_proto(ctx,
  21216. DUK_HOBJECT_FLAG_EXTENSIBLE |
  21217. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_DECENV),
  21218. act_lex_env);
  21219. new_env = duk_require_hobject(ctx, -1);
  21220. DUK_ASSERT(new_env != NULL);
  21221. DUK_DDD(DUK_DDDPRINT("new_env allocated: %!iO",
  21222. (duk_heaphdr *) new_env));
  21223. outer_lex_env = new_env;
  21224. outer_var_env = new_env;
  21225. duk_insert(ctx, 0); /* stash to bottom of value stack to keep new_env reachable */
  21226. /* compiler's responsibility */
  21227. DUK_ASSERT(DUK_HOBJECT_HAS_NEWENV((duk_hobject *) func));
  21228. } else {
  21229. DUK_DDD(DUK_DDDPRINT("direct eval call to a non-strict function -> "
  21230. "var_env and lex_env to caller's envs, "
  21231. "this_binding to caller's this_binding"));
  21232. outer_lex_env = act->lex_env;
  21233. outer_var_env = act->var_env;
  21234. /* compiler's responsibility */
  21235. DUK_ASSERT(!DUK_HOBJECT_HAS_NEWENV((duk_hobject *) func));
  21236. }
  21237. } else {
  21238. DUK_DDD(DUK_DDDPRINT("indirect eval call -> var_env and lex_env to "
  21239. "global object, this_binding to global object"));
  21240. this_to_global = 1;
  21241. outer_lex_env = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  21242. outer_var_env = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  21243. }
  21244. act = NULL;
  21245. duk_js_push_closure(thr, func, outer_var_env, outer_lex_env);
  21246. /* [ source template closure ] */
  21247. if (this_to_global) {
  21248. DUK_ASSERT(thr->builtins[DUK_BIDX_GLOBAL] != NULL);
  21249. duk_push_hobject_bidx(ctx, DUK_BIDX_GLOBAL);
  21250. } else {
  21251. duk_tval *tv;
  21252. DUK_ASSERT(thr->callstack_top >= 2);
  21253. act = thr->callstack + thr->callstack_top - 2; /* caller */
  21254. tv = thr->valstack + act->idx_bottom - 1; /* this is just beneath bottom */
  21255. DUK_ASSERT(tv >= thr->valstack);
  21256. duk_push_tval(ctx, tv);
  21257. }
  21258. DUK_DDD(DUK_DDDPRINT("eval -> lex_env=%!iO, var_env=%!iO, this_binding=%!T",
  21259. (duk_heaphdr *) outer_lex_env,
  21260. (duk_heaphdr *) outer_var_env,
  21261. (duk_tval *) duk_get_tval(ctx, -1)));
  21262. /* [ source template closure this ] */
  21263. duk_call_method(ctx, 0);
  21264. /* [ source template result ] */
  21265. return 1;
  21266. }
  21267. /*
  21268. * Parsing of ints and floats
  21269. */
  21270. DUK_INTERNAL duk_ret_t duk_bi_global_object_parse_int(duk_context *ctx) {
  21271. duk_bool_t strip_prefix;
  21272. duk_int32_t radix;
  21273. duk_small_uint_t s2n_flags;
  21274. DUK_ASSERT_TOP(ctx, 2);
  21275. duk_to_string(ctx, 0);
  21276. strip_prefix = 1;
  21277. radix = duk_to_int32(ctx, 1);
  21278. if (radix != 0) {
  21279. if (radix < 2 || radix > 36) {
  21280. goto ret_nan;
  21281. }
  21282. /* For octal, setting strip_prefix=0 is not necessary, as zero
  21283. * is tolerated anyway:
  21284. *
  21285. * parseInt('123', 8) === parseInt('0123', 8) with or without strip_prefix
  21286. * parseInt('123', 16) === parseInt('0x123', 16) requires strip_prefix = 1
  21287. */
  21288. if (radix != 16) {
  21289. strip_prefix = 0;
  21290. }
  21291. } else {
  21292. radix = 10;
  21293. }
  21294. s2n_flags = DUK_S2N_FLAG_TRIM_WHITE |
  21295. DUK_S2N_FLAG_ALLOW_GARBAGE |
  21296. DUK_S2N_FLAG_ALLOW_PLUS |
  21297. DUK_S2N_FLAG_ALLOW_MINUS |
  21298. DUK_S2N_FLAG_ALLOW_LEADING_ZERO |
  21299. #ifdef DUK_USE_OCTAL_SUPPORT
  21300. (strip_prefix ? (DUK_S2N_FLAG_ALLOW_AUTO_HEX_INT | DUK_S2N_FLAG_ALLOW_AUTO_OCT_INT) : 0)
  21301. #else
  21302. (strip_prefix ? DUK_S2N_FLAG_ALLOW_AUTO_HEX_INT : 0)
  21303. #endif
  21304. ;
  21305. duk_dup(ctx, 0);
  21306. duk_numconv_parse(ctx, radix, s2n_flags);
  21307. return 1;
  21308. ret_nan:
  21309. duk_push_nan(ctx);
  21310. return 1;
  21311. }
  21312. DUK_INTERNAL duk_ret_t duk_bi_global_object_parse_float(duk_context *ctx) {
  21313. duk_small_uint_t s2n_flags;
  21314. duk_int32_t radix;
  21315. DUK_ASSERT_TOP(ctx, 1);
  21316. duk_to_string(ctx, 0);
  21317. radix = 10;
  21318. /* XXX: check flags */
  21319. s2n_flags = DUK_S2N_FLAG_TRIM_WHITE |
  21320. DUK_S2N_FLAG_ALLOW_EXP |
  21321. DUK_S2N_FLAG_ALLOW_GARBAGE |
  21322. DUK_S2N_FLAG_ALLOW_PLUS |
  21323. DUK_S2N_FLAG_ALLOW_MINUS |
  21324. DUK_S2N_FLAG_ALLOW_INF |
  21325. DUK_S2N_FLAG_ALLOW_FRAC |
  21326. DUK_S2N_FLAG_ALLOW_NAKED_FRAC |
  21327. DUK_S2N_FLAG_ALLOW_EMPTY_FRAC |
  21328. DUK_S2N_FLAG_ALLOW_LEADING_ZERO;
  21329. duk_numconv_parse(ctx, radix, s2n_flags);
  21330. return 1;
  21331. }
  21332. /*
  21333. * Number checkers
  21334. */
  21335. DUK_INTERNAL duk_ret_t duk_bi_global_object_is_nan(duk_context *ctx) {
  21336. duk_double_t d = duk_to_number(ctx, 0);
  21337. duk_push_boolean(ctx, DUK_ISNAN(d));
  21338. return 1;
  21339. }
  21340. DUK_INTERNAL duk_ret_t duk_bi_global_object_is_finite(duk_context *ctx) {
  21341. duk_double_t d = duk_to_number(ctx, 0);
  21342. duk_push_boolean(ctx, DUK_ISFINITE(d));
  21343. return 1;
  21344. }
  21345. /*
  21346. * URI handling
  21347. */
  21348. DUK_INTERNAL duk_ret_t duk_bi_global_object_decode_uri(duk_context *ctx) {
  21349. return duk__transform_helper(ctx, duk__transform_callback_decode_uri, (void *) duk__decode_uri_reserved_table);
  21350. }
  21351. DUK_INTERNAL duk_ret_t duk_bi_global_object_decode_uri_component(duk_context *ctx) {
  21352. return duk__transform_helper(ctx, duk__transform_callback_decode_uri, (void *) duk__decode_uri_component_reserved_table);
  21353. }
  21354. DUK_INTERNAL duk_ret_t duk_bi_global_object_encode_uri(duk_context *ctx) {
  21355. return duk__transform_helper(ctx, duk__transform_callback_encode_uri, (void *) duk__encode_uriunescaped_table);
  21356. }
  21357. DUK_INTERNAL duk_ret_t duk_bi_global_object_encode_uri_component(duk_context *ctx) {
  21358. return duk__transform_helper(ctx, duk__transform_callback_encode_uri, (void *) duk__encode_uricomponent_unescaped_table);
  21359. }
  21360. #ifdef DUK_USE_SECTION_B
  21361. DUK_INTERNAL duk_ret_t duk_bi_global_object_escape(duk_context *ctx) {
  21362. return duk__transform_helper(ctx, duk__transform_callback_escape, (void *) NULL);
  21363. }
  21364. DUK_INTERNAL duk_ret_t duk_bi_global_object_unescape(duk_context *ctx) {
  21365. return duk__transform_helper(ctx, duk__transform_callback_unescape, (void *) NULL);
  21366. }
  21367. #else /* DUK_USE_SECTION_B */
  21368. DUK_INTERNAL duk_ret_t duk_bi_global_object_escape(duk_context *ctx) {
  21369. DUK_UNREF(ctx);
  21370. return DUK_RET_UNSUPPORTED_ERROR;
  21371. }
  21372. DUK_INTERNAL duk_ret_t duk_bi_global_object_unescape(duk_context *ctx) {
  21373. DUK_UNREF(ctx);
  21374. return DUK_RET_UNSUPPORTED_ERROR;
  21375. }
  21376. #endif /* DUK_USE_SECTION_B */
  21377. #if defined(DUK_USE_BROWSER_LIKE) && (defined(DUK_USE_FILE_IO) || defined(DUK_USE_DEBUGGER_SUPPORT))
  21378. DUK_INTERNAL duk_ret_t duk_bi_global_object_print_helper(duk_context *ctx) {
  21379. duk_hthread *thr = (duk_hthread *) ctx;
  21380. duk_int_t magic;
  21381. duk_idx_t nargs;
  21382. const duk_uint8_t *buf;
  21383. duk_size_t sz_buf;
  21384. const char nl = (const char) DUK_ASC_LF;
  21385. #ifndef DUK_USE_PREFER_SIZE
  21386. duk_uint8_t buf_stack[256];
  21387. #endif
  21388. #ifdef DUK_USE_FILE_IO
  21389. duk_file *f_out;
  21390. #endif
  21391. magic = duk_get_current_magic(ctx);
  21392. DUK_UNREF(magic);
  21393. nargs = duk_get_top(ctx);
  21394. /* If argument count is 1 and first argument is a buffer, write the buffer
  21395. * as raw data into the file without a newline; this allows exact control
  21396. * over stdout/stderr without an additional entrypoint (useful for now).
  21397. *
  21398. * Otherwise current print/alert semantics are to ToString() coerce
  21399. * arguments, join them with a single space, and append a newline.
  21400. */
  21401. if (nargs == 1 && duk_is_buffer(ctx, 0)) {
  21402. buf = (const duk_uint8_t *) duk_get_buffer(ctx, 0, &sz_buf);
  21403. DUK_ASSERT(buf != NULL);
  21404. } else if (nargs > 0) {
  21405. #ifdef DUK_USE_PREFER_SIZE
  21406. /* Compact but lots of churn. */
  21407. duk_push_hstring_stridx(thr, DUK_STRIDX_SPACE);
  21408. duk_insert(ctx, 0);
  21409. duk_join(ctx, nargs);
  21410. duk_push_string(thr, "\n");
  21411. duk_concat(ctx, 2);
  21412. buf = (const duk_uint8_t *) duk_get_lstring(ctx, -1, &sz_buf);
  21413. DUK_ASSERT(buf != NULL);
  21414. #else /* DUK_USE_PREFER_SIZE */
  21415. /* Higher footprint, less churn. */
  21416. duk_idx_t i;
  21417. duk_size_t sz_str;
  21418. const duk_uint8_t *p_str;
  21419. duk_uint8_t *p;
  21420. sz_buf = (duk_size_t) nargs; /* spaces (nargs - 1) + newline */
  21421. for (i = 0; i < nargs; i++) {
  21422. (void) duk_to_lstring(ctx, i, &sz_str);
  21423. sz_buf += sz_str;
  21424. }
  21425. if (sz_buf <= sizeof(buf_stack)) {
  21426. buf = (const duk_uint8_t *) buf_stack;
  21427. } else {
  21428. buf = (const duk_uint8_t *) duk_push_fixed_buffer(ctx, sz_buf);
  21429. DUK_ASSERT(buf != NULL);
  21430. }
  21431. p = (duk_uint8_t *) buf;
  21432. for (i = 0; i < nargs; i++) {
  21433. p_str = (const duk_uint8_t *) duk_get_lstring(ctx, i, &sz_str);
  21434. DUK_ASSERT(p_str != NULL);
  21435. DUK_MEMCPY((void *) p, (const void *) p_str, sz_str);
  21436. p += sz_str;
  21437. *p++ = (duk_uint8_t) (i == nargs - 1 ? DUK_ASC_LF : DUK_ASC_SPACE);
  21438. }
  21439. DUK_ASSERT((const duk_uint8_t *) p == buf + sz_total);
  21440. #endif /* DUK_USE_PREFER_SIZE */
  21441. } else {
  21442. buf = (const duk_uint8_t *) &nl;
  21443. sz_buf = 1;
  21444. }
  21445. /* 'buf' contains the string to write, 'sz_buf' contains the length
  21446. * (which may be zero).
  21447. */
  21448. DUK_ASSERT(buf != NULL);
  21449. if (sz_buf == 0) {
  21450. return 0;
  21451. }
  21452. #ifdef DUK_USE_FILE_IO
  21453. f_out = (magic ? DUK_STDERR : DUK_STDOUT);
  21454. DUK_FWRITE((const void *) buf, 1, (size_t) sz_buf, f_out);
  21455. DUK_FFLUSH(f_out);
  21456. #endif
  21457. #if defined(DUK_USE_DEBUGGER_SUPPORT) && defined(DUK_USE_DEBUGGER_FWD_PRINTALERT)
  21458. if (DUK_HEAP_IS_DEBUGGER_ATTACHED(thr->heap)) {
  21459. duk_debug_write_notify(thr, magic ? DUK_DBG_CMD_ALERT : DUK_DBG_CMD_PRINT);
  21460. duk_debug_write_string(thr, (const char *) buf, sz_buf);
  21461. duk_debug_write_eom(thr);
  21462. }
  21463. #endif
  21464. return 0;
  21465. }
  21466. #elif defined(DUK_USE_BROWSER_LIKE) /* print provider */
  21467. DUK_INTERNAL duk_ret_t duk_bi_global_object_print_helper(duk_context *ctx) {
  21468. DUK_UNREF(ctx);
  21469. return 0;
  21470. }
  21471. #else /* print provider */
  21472. DUK_INTERNAL duk_ret_t duk_bi_global_object_print_helper(duk_context *ctx) {
  21473. DUK_UNREF(ctx);
  21474. return DUK_RET_UNSUPPORTED_ERROR;
  21475. }
  21476. #endif /* print provider */
  21477. /*
  21478. * CommonJS require() and modules support
  21479. */
  21480. #if defined(DUK_USE_COMMONJS_MODULES)
  21481. DUK_LOCAL void duk__bi_global_resolve_module_id(duk_context *ctx, const char *req_id, const char *mod_id) {
  21482. duk_hthread *thr = (duk_hthread *) ctx;
  21483. duk_size_t mod_id_len;
  21484. duk_size_t req_id_len;
  21485. duk_uint8_t buf_in[DUK_BI_COMMONJS_MODULE_ID_LIMIT];
  21486. duk_uint8_t buf_out[DUK_BI_COMMONJS_MODULE_ID_LIMIT];
  21487. duk_uint8_t *p;
  21488. duk_uint8_t *q;
  21489. DUK_ASSERT(req_id != NULL);
  21490. /* mod_id may be NULL */
  21491. DUK_ASSERT(sizeof(buf_out) >= sizeof(buf_in)); /* bound checking requires this */
  21492. /*
  21493. * A few notes on the algorithm:
  21494. *
  21495. * - Terms are not allowed to begin with a period unless the term
  21496. * is either '.' or '..'. This simplifies implementation (and
  21497. * is within CommonJS modules specification).
  21498. *
  21499. * - There are few output bound checks here. This is on purpose:
  21500. * we check the input length and rely on the output never being
  21501. * longer than the input, so we cannot run out of output space.
  21502. *
  21503. * - Non-ASCII characters are processed as individual bytes and
  21504. * need no special treatment. However, U+0000 terminates the
  21505. * algorithm; this is not an issue because U+0000 is not a
  21506. * desirable term character anyway.
  21507. */
  21508. /*
  21509. * Set up the resolution input which is the requested ID directly
  21510. * (if absolute or no current module path) or with current module
  21511. * ID prepended (if relative and current module path exists).
  21512. *
  21513. * Suppose current module is 'foo/bar' and relative path is './quux'.
  21514. * The 'bar' component must be replaced so the initial input here is
  21515. * 'foo/bar/.././quux'.
  21516. */
  21517. req_id_len = DUK_STRLEN(req_id);
  21518. if (mod_id != NULL && req_id[0] == '.') {
  21519. mod_id_len = DUK_STRLEN(mod_id);
  21520. if (mod_id_len + 4 + req_id_len + 1 >= sizeof(buf_in)) {
  21521. DUK_DD(DUK_DDPRINT("resolve error: current and requested module ID don't fit into resolve input buffer"));
  21522. goto resolve_error;
  21523. }
  21524. (void) DUK_SNPRINTF((char *) buf_in, sizeof(buf_in), "%s/../%s", (const char *) mod_id, (const char *) req_id);
  21525. } else {
  21526. if (req_id_len + 1 >= sizeof(buf_in)) {
  21527. DUK_DD(DUK_DDPRINT("resolve error: requested module ID doesn't fit into resolve input buffer"));
  21528. goto resolve_error;
  21529. }
  21530. (void) DUK_SNPRINTF((char *) buf_in, sizeof(buf_in), "%s", (const char *) req_id);
  21531. }
  21532. buf_in[sizeof(buf_in) - 1] = (duk_uint8_t) 0;
  21533. DUK_DDD(DUK_DDDPRINT("input module id: '%s'", (const char *) buf_in));
  21534. /*
  21535. * Resolution loop. At the top of the loop we're expecting a valid
  21536. * term: '.', '..', or a non-empty identifier not starting with a period.
  21537. */
  21538. p = buf_in;
  21539. q = buf_out;
  21540. for (;;) {
  21541. duk_uint_fast8_t c;
  21542. /* Here 'p' always points to the start of a term. */
  21543. DUK_DDD(DUK_DDDPRINT("resolve loop top: p -> '%s', q=%p, buf_out=%p",
  21544. (const char *) p, (void *) q, (void *) buf_out));
  21545. c = *p++;
  21546. if (DUK_UNLIKELY(c == 0)) {
  21547. DUK_DD(DUK_DDPRINT("resolve error: requested ID must end with a non-empty term"));
  21548. goto resolve_error;
  21549. } else if (DUK_UNLIKELY(c == '.')) {
  21550. c = *p++;
  21551. if (c == '/') {
  21552. /* Term was '.' and is eaten entirely (including dup slashes). */
  21553. goto eat_dup_slashes;
  21554. }
  21555. if (c == '.' && *p == '/') {
  21556. /* Term was '..', backtrack resolved name by one component.
  21557. * q[-1] = previous slash (or beyond start of buffer)
  21558. * q[-2] = last char of previous component (or beyond start of buffer)
  21559. */
  21560. p++; /* eat (first) input slash */
  21561. DUK_ASSERT(q >= buf_out);
  21562. if (q == buf_out) {
  21563. DUK_DD(DUK_DDPRINT("resolve error: term was '..' but nothing to backtrack"));
  21564. goto resolve_error;
  21565. }
  21566. DUK_ASSERT(*(q - 1) == '/');
  21567. q--; /* backtrack to last output slash */
  21568. for (;;) {
  21569. /* Backtrack to previous slash or start of buffer. */
  21570. DUK_ASSERT(q >= buf_out);
  21571. if (q == buf_out) {
  21572. break;
  21573. }
  21574. if (*(q - 1) == '/') {
  21575. break;
  21576. }
  21577. q--;
  21578. }
  21579. goto eat_dup_slashes;
  21580. }
  21581. DUK_DD(DUK_DDPRINT("resolve error: term begins with '.' but is not '.' or '..' (not allowed now)"));
  21582. goto resolve_error;
  21583. } else if (DUK_UNLIKELY(c == '/')) {
  21584. /* e.g. require('/foo'), empty terms not allowed */
  21585. DUK_DD(DUK_DDPRINT("resolve error: empty term (not allowed now)"));
  21586. goto resolve_error;
  21587. } else {
  21588. for (;;) {
  21589. /* Copy term name until end or '/'. */
  21590. *q++ = c;
  21591. c = *p++;
  21592. if (DUK_UNLIKELY(c == 0)) {
  21593. goto loop_done;
  21594. } else if (DUK_UNLIKELY(c == '/')) {
  21595. *q++ = '/';
  21596. break;
  21597. } else {
  21598. /* write on next loop */
  21599. }
  21600. }
  21601. }
  21602. eat_dup_slashes:
  21603. for (;;) {
  21604. /* eat dup slashes */
  21605. c = *p;
  21606. if (DUK_LIKELY(c != '/')) {
  21607. break;
  21608. }
  21609. p++;
  21610. }
  21611. }
  21612. loop_done:
  21613. duk_push_lstring(ctx, (const char *) buf_out, (size_t) (q - buf_out));
  21614. return;
  21615. resolve_error:
  21616. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "cannot resolve module id: %s", (const char *) req_id);
  21617. }
  21618. #endif /* DUK_USE_COMMONJS_MODULES */
  21619. #if defined(DUK_USE_COMMONJS_MODULES)
  21620. DUK_INTERNAL duk_ret_t duk_bi_global_object_require(duk_context *ctx) {
  21621. const char *str_req_id; /* requested identifier */
  21622. const char *str_mod_id; /* require.id of current module */
  21623. /* NOTE: we try to minimize code size by avoiding unnecessary pops,
  21624. * so the stack looks a bit cluttered in this function. DUK_ASSERT_TOP()
  21625. * assertions are used to ensure stack configuration is correct at each
  21626. * step.
  21627. */
  21628. /*
  21629. * Resolve module identifier into canonical absolute form.
  21630. */
  21631. str_req_id = duk_require_string(ctx, 0);
  21632. duk_push_current_function(ctx);
  21633. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_ID);
  21634. str_mod_id = duk_get_string(ctx, 2); /* ignore non-strings */
  21635. DUK_DDD(DUK_DDDPRINT("resolve module id: requested=%!T, currentmodule=%!T",
  21636. (duk_tval *) duk_get_tval(ctx, 0),
  21637. (duk_tval *) duk_get_tval(ctx, 2)));
  21638. duk__bi_global_resolve_module_id(ctx, str_req_id, str_mod_id);
  21639. str_req_id = NULL;
  21640. str_mod_id = NULL;
  21641. DUK_DDD(DUK_DDDPRINT("resolved module id: requested=%!T, currentmodule=%!T, result=%!T",
  21642. (duk_tval *) duk_get_tval(ctx, 0),
  21643. (duk_tval *) duk_get_tval(ctx, 2),
  21644. (duk_tval *) duk_get_tval(ctx, 3)));
  21645. /* [ requested_id require require.id resolved_id ] */
  21646. DUK_ASSERT_TOP(ctx, 4);
  21647. /*
  21648. * Cached module check.
  21649. *
  21650. * If module has been loaded or its loading has already begun without
  21651. * finishing, return the same cached value ('exports'). The value is
  21652. * registered when module load starts so that circular references can
  21653. * be supported to some extent.
  21654. */
  21655. /* [ requested_id require require.id resolved_id ] */
  21656. DUK_ASSERT_TOP(ctx, 4);
  21657. duk_push_hobject_bidx(ctx, DUK_BIDX_DUKTAPE);
  21658. duk_get_prop_stridx(ctx, 4, DUK_STRIDX_MOD_LOADED); /* Duktape.modLoaded */
  21659. (void) duk_require_hobject(ctx, 5);
  21660. /* [ requested_id require require.id resolved_id Duktape Duktape.modLoaded ] */
  21661. DUK_ASSERT_TOP(ctx, 6);
  21662. duk_dup(ctx, 3);
  21663. if (duk_get_prop(ctx, 5)) {
  21664. /* [ requested_id require require.id resolved_id Duktape Duktape.modLoaded Duktape.modLoaded[id] ] */
  21665. DUK_DD(DUK_DDPRINT("module already loaded: %!T",
  21666. (duk_tval *) duk_get_tval(ctx, 3)));
  21667. return 1;
  21668. }
  21669. /* [ requested_id require require.id resolved_id Duktape Duktape.modLoaded undefined ] */
  21670. DUK_ASSERT_TOP(ctx, 7);
  21671. /*
  21672. * Module not loaded (and loading not started previously).
  21673. *
  21674. * Create a new require() function with 'id' set to resolved ID
  21675. * of module being loaded. Also create 'exports' and 'module'
  21676. * tables but don't register exports to the loaded table yet.
  21677. * We don't want to do that unless the user module search callbacks
  21678. * succeeds in finding the module.
  21679. */
  21680. DUK_DD(DUK_DDPRINT("module not yet loaded: %!T",
  21681. (duk_tval *) duk_get_tval(ctx, 3)));
  21682. /* Fresh require: require.id is left configurable (but not writable)
  21683. * so that is not easy to accidentally tweak it, but it can still be
  21684. * done with Object.defineProperty().
  21685. *
  21686. * XXX: require.id could also be just made non-configurable, as there
  21687. * is no practical reason to touch it.
  21688. */
  21689. duk_push_c_function(ctx, duk_bi_global_object_require, 1 /*nargs*/);
  21690. duk_dup(ctx, 3);
  21691. duk_xdef_prop_stridx(ctx, 7, DUK_STRIDX_ID, DUK_PROPDESC_FLAGS_C); /* a fresh require() with require.id = resolved target module id */
  21692. /* Exports table. */
  21693. duk_push_object(ctx);
  21694. /* Module table: module.id is non-writable and non-configurable, as
  21695. * the CommonJS spec suggests this if possible.
  21696. */
  21697. duk_push_object(ctx);
  21698. duk_dup(ctx, 3); /* resolved id: require(id) must return this same module */
  21699. duk_xdef_prop_stridx(ctx, 9, DUK_STRIDX_ID, DUK_PROPDESC_FLAGS_NONE);
  21700. /* [ requested_id require require.id resolved_id Duktape Duktape.modLoaded undefined fresh_require exports module ] */
  21701. DUK_ASSERT_TOP(ctx, 10);
  21702. /*
  21703. * Call user provided module search function and build the wrapped
  21704. * module source code (if necessary). The module search function
  21705. * can be used to implement pure Ecmacsript, pure C, and mixed
  21706. * Ecmascript/C modules.
  21707. *
  21708. * The module search function can operate on the exports table directly
  21709. * (e.g. DLL code can register values to it). It can also return a
  21710. * string which is interpreted as module source code (if a non-string
  21711. * is returned the module is assumed to be a pure C one). If a module
  21712. * cannot be found, an error must be thrown by the user callback.
  21713. *
  21714. * NOTE: the current arrangement allows C modules to be implemented
  21715. * but since the exports table is registered to Duktape.modLoaded only
  21716. * after the search function returns, circular requires / partially
  21717. * loaded modules don't work for C modules. This is rarely an issue,
  21718. * as C modules usually simply expose a set of helper functions.
  21719. */
  21720. duk_push_string(ctx, "(function(require,exports,module){");
  21721. /* Duktape.modSearch(resolved_id, fresh_require, exports, module). */
  21722. duk_get_prop_stridx(ctx, 4, DUK_STRIDX_MOD_SEARCH); /* Duktape.modSearch */
  21723. duk_dup(ctx, 3);
  21724. duk_dup(ctx, 7);
  21725. duk_dup(ctx, 8);
  21726. duk_dup(ctx, 9); /* [ ... Duktape.modSearch resolved_id fresh_require exports module ] */
  21727. duk_call(ctx, 4 /*nargs*/); /* -> [ ... source ] */
  21728. DUK_ASSERT_TOP(ctx, 12);
  21729. /* Because user callback did not throw an error, remember exports table. */
  21730. duk_dup(ctx, 3);
  21731. duk_dup(ctx, 8);
  21732. duk_xdef_prop(ctx, 5, DUK_PROPDESC_FLAGS_EC); /* Duktape.modLoaded[resolved_id] = exports */
  21733. /* If user callback did not return source code, module loading
  21734. * is finished (user callback initialized exports table directly).
  21735. */
  21736. if (!duk_is_string(ctx, 11)) {
  21737. /* User callback did not return source code, so
  21738. * module loading is finished.
  21739. */
  21740. duk_dup(ctx, 8);
  21741. return 1;
  21742. }
  21743. /* Finish the wrapped module source. Force resolved module ID as the
  21744. * fileName so it gets set for functions defined within a module. This
  21745. * also ensures loggers created within the module get the module ID as
  21746. * their default logger name.
  21747. */
  21748. duk_push_string(ctx, "})");
  21749. duk_concat(ctx, 3);
  21750. duk_dup(ctx, 3); /* resolved module ID for fileName */
  21751. duk_eval_raw(ctx, NULL, 0, DUK_COMPILE_EVAL);
  21752. /* XXX: The module wrapper function is currently anonymous and is shown
  21753. * in stack traces. It would be nice to force it to match the module
  21754. * name (perhaps just the cleaned up last term). At the moment 'name'
  21755. * is write protected so we can't change it directly. Note that we must
  21756. * not introduce an actual name binding into the function scope (which
  21757. * is usually the case with a named function) because it would affect
  21758. * the scope seen by the module and shadow accesses to globals of the
  21759. * same name.
  21760. */
  21761. /*
  21762. * Call the wrapped module function.
  21763. */
  21764. /* [ requested_id require require.id resolved_id Duktape Duktape.modLoaded undefined fresh_require exports module mod_func ] */
  21765. DUK_ASSERT_TOP(ctx, 11);
  21766. duk_dup(ctx, 8); /* exports (this binding) */
  21767. duk_dup(ctx, 7); /* fresh require (argument) */
  21768. duk_dup(ctx, 8); /* exports (argument) */
  21769. duk_dup(ctx, 9); /* module (argument) */
  21770. /* [ requested_id require require.id resolved_id Duktape Duktape.modLoaded undefined fresh_require exports module mod_func exports fresh_require exports module ] */
  21771. DUK_ASSERT_TOP(ctx, 15);
  21772. duk_call_method(ctx, 3 /*nargs*/);
  21773. /* [ requested_id require require.id resolved_id Duktape Duktape.modLoaded undefined fresh_require exports module result(ignored) ] */
  21774. DUK_ASSERT_TOP(ctx, 11);
  21775. duk_pop_2(ctx);
  21776. return 1; /* return exports */
  21777. }
  21778. #else
  21779. DUK_INTERNAL duk_ret_t duk_bi_global_object_require(duk_context *ctx) {
  21780. DUK_UNREF(ctx);
  21781. return DUK_RET_UNSUPPORTED_ERROR;
  21782. }
  21783. #endif /* DUK_USE_COMMONJS_MODULES */
  21784. #line 1 "duk_bi_json.c"
  21785. /*
  21786. * JSON built-ins.
  21787. *
  21788. * See doc/json.txt.
  21789. *
  21790. * Codepoints are handled as duk_uint_fast32_t to ensure that the full
  21791. * unsigned 32-bit range is supported. This matters to e.g. JX.
  21792. */
  21793. /* include removed: duk_internal.h */
  21794. /*
  21795. * Local defines and forward declarations.
  21796. */
  21797. DUK_LOCAL_DECL void duk__dec_syntax_error(duk_json_dec_ctx *js_ctx);
  21798. DUK_LOCAL_DECL void duk__dec_eat_white(duk_json_dec_ctx *js_ctx);
  21799. DUK_LOCAL_DECL duk_small_int_t duk__dec_peek(duk_json_dec_ctx *js_ctx);
  21800. DUK_LOCAL_DECL duk_small_int_t duk__dec_get(duk_json_dec_ctx *js_ctx);
  21801. DUK_LOCAL_DECL duk_small_int_t duk__dec_get_nonwhite(duk_json_dec_ctx *js_ctx);
  21802. DUK_LOCAL_DECL duk_uint_fast32_t duk__dec_decode_hex_escape(duk_json_dec_ctx *js_ctx, duk_small_uint_t n);
  21803. DUK_LOCAL_DECL void duk__dec_req_stridx(duk_json_dec_ctx *js_ctx, duk_small_uint_t stridx);
  21804. DUK_LOCAL_DECL void duk__dec_string(duk_json_dec_ctx *js_ctx);
  21805. #ifdef DUK_USE_JX
  21806. DUK_LOCAL_DECL void duk__dec_plain_string(duk_json_dec_ctx *js_ctx);
  21807. DUK_LOCAL_DECL void duk__dec_pointer(duk_json_dec_ctx *js_ctx);
  21808. DUK_LOCAL_DECL void duk__dec_buffer(duk_json_dec_ctx *js_ctx);
  21809. #endif
  21810. DUK_LOCAL_DECL void duk__dec_number(duk_json_dec_ctx *js_ctx);
  21811. DUK_LOCAL_DECL void duk__dec_objarr_entry(duk_json_dec_ctx *js_ctx);
  21812. DUK_LOCAL_DECL void duk__dec_objarr_exit(duk_json_dec_ctx *js_ctx);
  21813. DUK_LOCAL_DECL void duk__dec_object(duk_json_dec_ctx *js_ctx);
  21814. DUK_LOCAL_DECL void duk__dec_array(duk_json_dec_ctx *js_ctx);
  21815. DUK_LOCAL_DECL void duk__dec_value(duk_json_dec_ctx *js_ctx);
  21816. DUK_LOCAL_DECL void duk__dec_reviver_walk(duk_json_dec_ctx *js_ctx);
  21817. DUK_LOCAL_DECL void duk__emit_1(duk_json_enc_ctx *js_ctx, duk_uint_fast8_t ch);
  21818. DUK_LOCAL_DECL void duk__emit_2(duk_json_enc_ctx *js_ctx, duk_uint_fast16_t packed_chars);
  21819. DUK_LOCAL_DECL void duk__emit_esc_auto(duk_json_enc_ctx *js_ctx, duk_uint_fast32_t cp);
  21820. DUK_LOCAL_DECL void duk__emit_xutf8(duk_json_enc_ctx *js_ctx, duk_uint_fast32_t cp);
  21821. DUK_LOCAL_DECL void duk__emit_hstring(duk_json_enc_ctx *js_ctx, duk_hstring *h);
  21822. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  21823. DUK_LOCAL_DECL void duk__emit_cstring(duk_json_enc_ctx *js_ctx, const char *p);
  21824. #endif
  21825. DUK_LOCAL_DECL void duk__emit_stridx(duk_json_enc_ctx *js_ctx, duk_small_uint_t stridx);
  21826. DUK_LOCAL_DECL duk_bool_t duk__enc_key_quotes_needed(duk_hstring *h_key);
  21827. DUK_LOCAL_DECL void duk__enc_quote_string(duk_json_enc_ctx *js_ctx, duk_hstring *h_str);
  21828. DUK_LOCAL_DECL void duk__enc_objarr_entry(duk_json_enc_ctx *js_ctx, duk_hstring **h_stepback, duk_hstring **h_indent, duk_idx_t *entry_top);
  21829. DUK_LOCAL_DECL void duk__enc_objarr_exit(duk_json_enc_ctx *js_ctx, duk_hstring **h_stepback, duk_hstring **h_indent, duk_idx_t *entry_top);
  21830. DUK_LOCAL_DECL void duk__enc_object(duk_json_enc_ctx *js_ctx);
  21831. DUK_LOCAL_DECL void duk__enc_array(duk_json_enc_ctx *js_ctx);
  21832. DUK_LOCAL_DECL duk_bool_t duk__enc_value1(duk_json_enc_ctx *js_ctx, duk_idx_t idx_holder);
  21833. DUK_LOCAL_DECL void duk__enc_value2(duk_json_enc_ctx *js_ctx);
  21834. DUK_LOCAL_DECL duk_bool_t duk__enc_allow_into_proplist(duk_tval *tv);
  21835. /*
  21836. * Parsing implementation.
  21837. *
  21838. * JSON lexer is now separate from duk_lexer.c because there are numerous
  21839. * small differences making it difficult to share the lexer.
  21840. *
  21841. * The parser here works with raw bytes directly; this works because all
  21842. * JSON delimiters are ASCII characters. Invalid xUTF-8 encoded values
  21843. * inside strings will be passed on without normalization; this is not a
  21844. * compliance concern because compliant inputs will always be valid
  21845. * CESU-8 encodings.
  21846. */
  21847. DUK_LOCAL void duk__dec_syntax_error(duk_json_dec_ctx *js_ctx) {
  21848. /* Shared handler to minimize parser size. Cause will be
  21849. * hidden, unfortunately, but we'll have an offset which
  21850. * is often quite enough.
  21851. */
  21852. DUK_ERROR(js_ctx->thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_FMT_INVALID_JSON,
  21853. (long) (js_ctx->p - js_ctx->p_start));
  21854. }
  21855. DUK_LOCAL void duk__dec_eat_white(duk_json_dec_ctx *js_ctx) {
  21856. duk_small_uint_t t;
  21857. for (;;) {
  21858. if (js_ctx->p >= js_ctx->p_end) {
  21859. break;
  21860. }
  21861. t = (*js_ctx->p);
  21862. if (!(t == 0x20 || t == 0x0a || t == 0x0d || t == 0x09)) {
  21863. break;
  21864. }
  21865. js_ctx->p++;
  21866. }
  21867. }
  21868. DUK_LOCAL duk_small_int_t duk__dec_peek(duk_json_dec_ctx *js_ctx) {
  21869. if (js_ctx->p >= js_ctx->p_end) {
  21870. return -1;
  21871. } else {
  21872. return (duk_small_int_t) (*js_ctx->p);
  21873. }
  21874. }
  21875. DUK_LOCAL duk_small_int_t duk__dec_get(duk_json_dec_ctx *js_ctx) {
  21876. /* Multiple EOFs will now be supplied to the caller. This could also be
  21877. * changed so that reading the second EOF would cause an error automatically.
  21878. */
  21879. if (js_ctx->p >= js_ctx->p_end) {
  21880. return -1;
  21881. } else {
  21882. return (duk_small_int_t) (*js_ctx->p++);
  21883. }
  21884. }
  21885. DUK_LOCAL duk_small_int_t duk__dec_get_nonwhite(duk_json_dec_ctx *js_ctx) {
  21886. duk__dec_eat_white(js_ctx);
  21887. return duk__dec_get(js_ctx);
  21888. }
  21889. /* For JX, expressing the whole unsigned 32-bit range matters. */
  21890. DUK_LOCAL duk_uint_fast32_t duk__dec_decode_hex_escape(duk_json_dec_ctx *js_ctx, duk_small_uint_t n) {
  21891. duk_small_uint_t i;
  21892. duk_uint_fast32_t res = 0;
  21893. duk_small_int_t x;
  21894. for (i = 0; i < n; i++) {
  21895. /* XXX: share helper from lexer; duk_lexer.c / hexval(). */
  21896. x = duk__dec_get(js_ctx);
  21897. DUK_ASSERT((x >= 0 && x <= 0xff) || (x == -1));
  21898. DUK_DDD(DUK_DDDPRINT("decode_hex_escape: i=%ld, n=%ld, res=%ld, x=%ld",
  21899. (long) i, (long) n, (long) res, (long) x));
  21900. /* x == -1 will map to 0xff, dectab returns -1 which causes syntax_error */
  21901. x = duk_hex_dectab[x & 0xff];
  21902. if (DUK_LIKELY(x >= 0)) {
  21903. res = (res * 16) + x;
  21904. } else {
  21905. /* catches EOF and invalid digits */
  21906. goto syntax_error;
  21907. }
  21908. }
  21909. DUK_DDD(DUK_DDDPRINT("final hex decoded value: %ld", (long) res));
  21910. return res;
  21911. syntax_error:
  21912. duk__dec_syntax_error(js_ctx);
  21913. DUK_UNREACHABLE();
  21914. return 0;
  21915. }
  21916. DUK_LOCAL void duk__dec_req_stridx(duk_json_dec_ctx *js_ctx, duk_small_uint_t stridx) {
  21917. duk_hstring *h;
  21918. duk_uint8_t *p;
  21919. duk_uint8_t *p_end;
  21920. duk_small_int_t x;
  21921. /* First character has already been eaten and checked by the caller. */
  21922. DUK_ASSERT_DISABLE(stridx >= 0); /* unsigned */
  21923. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  21924. h = DUK_HTHREAD_GET_STRING(js_ctx->thr, stridx);
  21925. DUK_ASSERT(h != NULL);
  21926. p = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h);
  21927. p_end = ((duk_uint8_t *) DUK_HSTRING_GET_DATA(h)) +
  21928. DUK_HSTRING_GET_BYTELEN(h);
  21929. DUK_ASSERT(*(js_ctx->p - 1) == *p); /* first character has been matched */
  21930. p++; /* first char */
  21931. while (p < p_end) {
  21932. x = duk__dec_get(js_ctx);
  21933. if ((duk_small_int_t) (*p) != x) {
  21934. /* catches EOF */
  21935. goto syntax_error;
  21936. }
  21937. p++;
  21938. }
  21939. return;
  21940. syntax_error:
  21941. duk__dec_syntax_error(js_ctx);
  21942. DUK_UNREACHABLE();
  21943. }
  21944. DUK_LOCAL void duk__dec_string(duk_json_dec_ctx *js_ctx) {
  21945. duk_hthread *thr = js_ctx->thr;
  21946. duk_context *ctx = (duk_context *) thr;
  21947. duk_hbuffer_dynamic *h_buf;
  21948. duk_small_int_t x;
  21949. duk_uint_fast32_t cp;
  21950. /* '"' was eaten by caller */
  21951. /* Note that we currently parse -bytes-, not codepoints.
  21952. * All non-ASCII extended UTF-8 will encode to bytes >= 0x80,
  21953. * so they'll simply pass through (valid UTF-8 or not).
  21954. */
  21955. duk_push_dynamic_buffer(ctx, 0);
  21956. h_buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  21957. DUK_ASSERT(h_buf != NULL);
  21958. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(h_buf));
  21959. for (;;) {
  21960. x = duk__dec_get(js_ctx);
  21961. if (x == DUK_ASC_DOUBLEQUOTE) {
  21962. break;
  21963. } else if (x == DUK_ASC_BACKSLASH) {
  21964. /* EOF (-1) will be cast to an unsigned value first
  21965. * and then re-cast for the switch. In any case, it
  21966. * will match the default case (syntax error).
  21967. */
  21968. cp = (duk_uint_fast32_t) duk__dec_get(js_ctx);
  21969. switch ((int) cp) {
  21970. case DUK_ASC_BACKSLASH: break;
  21971. case DUK_ASC_DOUBLEQUOTE: break;
  21972. case DUK_ASC_SLASH: break;
  21973. case DUK_ASC_LC_T: cp = 0x09; break;
  21974. case DUK_ASC_LC_N: cp = 0x0a; break;
  21975. case DUK_ASC_LC_R: cp = 0x0d; break;
  21976. case DUK_ASC_LC_F: cp = 0x0c; break;
  21977. case DUK_ASC_LC_B: cp = 0x08; break;
  21978. case DUK_ASC_LC_U: {
  21979. cp = duk__dec_decode_hex_escape(js_ctx, 4);
  21980. break;
  21981. }
  21982. #ifdef DUK_USE_JX
  21983. case DUK_ASC_UC_U: {
  21984. if (js_ctx->flag_ext_custom) {
  21985. cp = duk__dec_decode_hex_escape(js_ctx, 8);
  21986. } else {
  21987. goto syntax_error;
  21988. }
  21989. break;
  21990. }
  21991. case DUK_ASC_LC_X: {
  21992. if (js_ctx->flag_ext_custom) {
  21993. cp = duk__dec_decode_hex_escape(js_ctx, 2);
  21994. } else {
  21995. goto syntax_error;
  21996. }
  21997. break;
  21998. }
  21999. #endif /* DUK_USE_JX */
  22000. default:
  22001. /* catches EOF (-1) */
  22002. goto syntax_error;
  22003. }
  22004. duk_hbuffer_append_xutf8(thr, h_buf, (duk_uint32_t) cp);
  22005. } else if (x < 0x20) {
  22006. /* catches EOF (-1) */
  22007. goto syntax_error;
  22008. } else {
  22009. duk_hbuffer_append_byte(thr, h_buf, (duk_uint8_t) x);
  22010. }
  22011. }
  22012. duk_to_string(ctx, -1);
  22013. /* [ ... str ] */
  22014. return;
  22015. syntax_error:
  22016. duk__dec_syntax_error(js_ctx);
  22017. DUK_UNREACHABLE();
  22018. }
  22019. #ifdef DUK_USE_JX
  22020. /* Decode a plain string consisting entirely of identifier characters.
  22021. * Used to parse plain keys (e.g. "foo: 123").
  22022. */
  22023. DUK_LOCAL void duk__dec_plain_string(duk_json_dec_ctx *js_ctx) {
  22024. duk_hthread *thr = js_ctx->thr;
  22025. duk_context *ctx = (duk_context *) thr;
  22026. const duk_uint8_t *p;
  22027. duk_small_int_t x;
  22028. /* Caller has already eaten the first char so backtrack one byte. */
  22029. js_ctx->p--; /* safe */
  22030. p = js_ctx->p;
  22031. /* Here again we parse bytes, and non-ASCII UTF-8 will cause end of
  22032. * parsing (which is correct except if there are non-shortest encodings).
  22033. * There is also no need to check explicitly for end of input buffer as
  22034. * the input is NUL padded and NUL will exit the parsing loop.
  22035. *
  22036. * Because no unescaping takes place, we can just scan to the end of the
  22037. * plain string and intern from the input buffer.
  22038. */
  22039. for (;;) {
  22040. x = *p;
  22041. /* There is no need to check the first character specially here
  22042. * (i.e. reject digits): the caller only accepts valid initial
  22043. * characters and won't call us if the first character is a digit.
  22044. * This also ensures that the plain string won't be empty.
  22045. */
  22046. if (!duk_unicode_is_identifier_part((duk_codepoint_t) x)) {
  22047. break;
  22048. }
  22049. p++;
  22050. }
  22051. duk_push_lstring(ctx, (const char *) js_ctx->p, (duk_size_t) (p - js_ctx->p));
  22052. js_ctx->p = p;
  22053. /* [ ... str ] */
  22054. }
  22055. #endif /* DUK_USE_JX */
  22056. #ifdef DUK_USE_JX
  22057. DUK_LOCAL void duk__dec_pointer(duk_json_dec_ctx *js_ctx) {
  22058. duk_hthread *thr = js_ctx->thr;
  22059. duk_context *ctx = (duk_context *) thr;
  22060. const duk_uint8_t *p;
  22061. duk_small_int_t x;
  22062. void *voidptr;
  22063. /* Caller has already eaten the first character ('(') which we don't need. */
  22064. p = js_ctx->p;
  22065. for (;;) {
  22066. x = *p;
  22067. /* Assume that the native representation never contains a closing
  22068. * parenthesis.
  22069. */
  22070. if (x == DUK_ASC_RPAREN) {
  22071. break;
  22072. } else if (x <= 0) {
  22073. /* NUL term or -1 (EOF), NUL check would suffice */
  22074. goto syntax_error;
  22075. }
  22076. p++;
  22077. }
  22078. /* There is no need to NUL delimit the sscanf() call: trailing garbage is
  22079. * ignored and there is always a NUL terminator which will force an error
  22080. * if no error is encountered before it. It's possible that the scan
  22081. * would scan further than between [js_ctx->p,p[ though and we'd advance
  22082. * by less than the scanned value.
  22083. *
  22084. * Because pointers are platform specific, a failure to scan a pointer
  22085. * results in a null pointer which is a better placeholder than a missing
  22086. * value or an error.
  22087. */
  22088. voidptr = NULL;
  22089. (void) DUK_SSCANF((const char *) js_ctx->p, DUK_STR_FMT_PTR, &voidptr);
  22090. duk_push_pointer(ctx, voidptr);
  22091. js_ctx->p = p + 1; /* skip ')' */
  22092. /* [ ... ptr ] */
  22093. return;
  22094. syntax_error:
  22095. duk__dec_syntax_error(js_ctx);
  22096. DUK_UNREACHABLE();
  22097. }
  22098. #endif /* DUK_USE_JX */
  22099. #ifdef DUK_USE_JX
  22100. DUK_LOCAL void duk__dec_buffer(duk_json_dec_ctx *js_ctx) {
  22101. duk_hthread *thr = js_ctx->thr;
  22102. duk_context *ctx = (duk_context *) thr;
  22103. const duk_uint8_t *p;
  22104. duk_small_int_t x;
  22105. /* Caller has already eaten the first character ('|') which we don't need. */
  22106. p = js_ctx->p;
  22107. for (;;) {
  22108. x = *p;
  22109. /* This loop intentionally does not ensure characters are valid
  22110. * ([0-9a-fA-F]) because the hex decode call below will do that.
  22111. */
  22112. if (x == DUK_ASC_PIPE) {
  22113. break;
  22114. } else if (x <= 0) {
  22115. /* NUL term or -1 (EOF), NUL check would suffice */
  22116. goto syntax_error;
  22117. }
  22118. p++;
  22119. }
  22120. duk_push_lstring(ctx, (const char *) js_ctx->p, (duk_size_t) (p - js_ctx->p));
  22121. duk_hex_decode(ctx, -1);
  22122. js_ctx->p = p + 1; /* skip '|' */
  22123. /* [ ... buf ] */
  22124. return;
  22125. syntax_error:
  22126. duk__dec_syntax_error(js_ctx);
  22127. DUK_UNREACHABLE();
  22128. }
  22129. #endif /* DUK_USE_JX */
  22130. /* Parse a number, other than NaN or +/- Infinity */
  22131. DUK_LOCAL void duk__dec_number(duk_json_dec_ctx *js_ctx) {
  22132. duk_context *ctx = (duk_context *) js_ctx->thr;
  22133. const duk_uint8_t *p_start;
  22134. duk_small_int_t x;
  22135. duk_small_uint_t s2n_flags;
  22136. DUK_DDD(DUK_DDDPRINT("parse_number"));
  22137. /* Caller has already eaten the first character so backtrack one
  22138. * byte. This is correct because the first character is either
  22139. * '-' or a digit (i.e. an ASCII character).
  22140. */
  22141. js_ctx->p--; /* safe */
  22142. p_start = js_ctx->p;
  22143. /* First pass parse is very lenient (e.g. allows '1.2.3') and extracts a
  22144. * string for strict number parsing.
  22145. */
  22146. for (;;) {
  22147. x = duk__dec_peek(js_ctx);
  22148. DUK_DDD(DUK_DDDPRINT("parse_number: p_start=%p, p=%p, p_end=%p, x=%ld",
  22149. (void *) p_start, (void *) js_ctx->p,
  22150. (void *) js_ctx->p_end, (long) x));
  22151. if (!((x >= DUK_ASC_0 && x <= DUK_ASC_9) ||
  22152. (x == DUK_ASC_PERIOD || x == DUK_ASC_LC_E ||
  22153. x == DUK_ASC_UC_E || x == DUK_ASC_MINUS || x == DUK_ASC_PLUS))) {
  22154. /* Plus sign must be accepted for positive exponents
  22155. * (e.g. '1.5e+2').
  22156. */
  22157. break;
  22158. }
  22159. js_ctx->p++; /* safe, because matched char */
  22160. }
  22161. DUK_ASSERT(js_ctx->p > p_start);
  22162. duk_push_lstring(ctx, (const char *) p_start, (duk_size_t) (js_ctx->p - p_start));
  22163. s2n_flags = DUK_S2N_FLAG_ALLOW_EXP |
  22164. DUK_S2N_FLAG_ALLOW_MINUS | /* but don't allow leading plus */
  22165. DUK_S2N_FLAG_ALLOW_FRAC;
  22166. DUK_DDD(DUK_DDDPRINT("parse_number: string before parsing: %!T",
  22167. (duk_tval *) duk_get_tval(ctx, -1)));
  22168. duk_numconv_parse(ctx, 10 /*radix*/, s2n_flags);
  22169. if (duk_is_nan(ctx, -1)) {
  22170. duk__dec_syntax_error(js_ctx);
  22171. }
  22172. DUK_ASSERT(duk_is_number(ctx, -1));
  22173. DUK_DDD(DUK_DDDPRINT("parse_number: final number: %!T",
  22174. (duk_tval *) duk_get_tval(ctx, -1)));
  22175. /* [ ... num ] */
  22176. }
  22177. DUK_LOCAL void duk__dec_objarr_entry(duk_json_dec_ctx *js_ctx) {
  22178. duk_context *ctx = (duk_context *) js_ctx->thr;
  22179. duk_require_stack(ctx, DUK_JSON_DEC_REQSTACK);
  22180. /* c recursion check */
  22181. DUK_ASSERT(js_ctx->recursion_depth >= 0);
  22182. DUK_ASSERT(js_ctx->recursion_depth <= js_ctx->recursion_limit);
  22183. if (js_ctx->recursion_depth >= js_ctx->recursion_limit) {
  22184. DUK_ERROR((duk_hthread *) ctx, DUK_ERR_RANGE_ERROR, DUK_STR_JSONDEC_RECLIMIT);
  22185. }
  22186. js_ctx->recursion_depth++;
  22187. }
  22188. DUK_LOCAL void duk__dec_objarr_exit(duk_json_dec_ctx *js_ctx) {
  22189. /* c recursion check */
  22190. DUK_ASSERT(js_ctx->recursion_depth > 0);
  22191. DUK_ASSERT(js_ctx->recursion_depth <= js_ctx->recursion_limit);
  22192. js_ctx->recursion_depth--;
  22193. }
  22194. DUK_LOCAL void duk__dec_object(duk_json_dec_ctx *js_ctx) {
  22195. duk_context *ctx = (duk_context *) js_ctx->thr;
  22196. duk_int_t key_count; /* XXX: a "first" flag would suffice */
  22197. duk_small_int_t x;
  22198. DUK_DDD(DUK_DDDPRINT("parse_object"));
  22199. duk__dec_objarr_entry(js_ctx);
  22200. duk_push_object(ctx);
  22201. /* Initial '{' has been checked and eaten by caller. */
  22202. key_count = 0;
  22203. for (;;) {
  22204. x = duk__dec_get_nonwhite(js_ctx);
  22205. DUK_DDD(DUK_DDDPRINT("parse_object: obj=%!T, x=%ld, key_count=%ld",
  22206. (duk_tval *) duk_get_tval(ctx, -1),
  22207. (long) x, (long) key_count));
  22208. /* handle comma and closing brace */
  22209. if (x == DUK_ASC_COMMA && key_count > 0) {
  22210. /* accept comma, expect new value */
  22211. x = duk__dec_get_nonwhite(js_ctx);
  22212. } else if (x == DUK_ASC_RCURLY) {
  22213. /* eat closing brace */
  22214. break;
  22215. } else if (key_count == 0) {
  22216. /* accept anything, expect first value (EOF will be
  22217. * caught by key parsing below.
  22218. */
  22219. ;
  22220. } else {
  22221. /* catches EOF (and initial comma) */
  22222. goto syntax_error;
  22223. }
  22224. /* parse key and value */
  22225. if (x == DUK_ASC_DOUBLEQUOTE) {
  22226. duk__dec_string(js_ctx);
  22227. #ifdef DUK_USE_JX
  22228. } else if (js_ctx->flag_ext_custom &&
  22229. duk_unicode_is_identifier_start((duk_codepoint_t) x)) {
  22230. duk__dec_plain_string(js_ctx);
  22231. #endif
  22232. } else {
  22233. goto syntax_error;
  22234. }
  22235. /* [ ... obj key ] */
  22236. x = duk__dec_get_nonwhite(js_ctx);
  22237. if (x != DUK_ASC_COLON) {
  22238. goto syntax_error;
  22239. }
  22240. duk__dec_value(js_ctx);
  22241. /* [ ... obj key val ] */
  22242. duk_xdef_prop_wec(ctx, -3);
  22243. /* [ ... obj ] */
  22244. key_count++;
  22245. }
  22246. /* [ ... obj ] */
  22247. DUK_DDD(DUK_DDDPRINT("parse_object: final object is %!T",
  22248. (duk_tval *) duk_get_tval(ctx, -1)));
  22249. duk__dec_objarr_exit(js_ctx);
  22250. return;
  22251. syntax_error:
  22252. duk__dec_syntax_error(js_ctx);
  22253. DUK_UNREACHABLE();
  22254. }
  22255. DUK_LOCAL void duk__dec_array(duk_json_dec_ctx *js_ctx) {
  22256. duk_context *ctx = (duk_context *) js_ctx->thr;
  22257. duk_uarridx_t arr_idx;
  22258. duk_small_int_t x;
  22259. DUK_DDD(DUK_DDDPRINT("parse_array"));
  22260. duk__dec_objarr_entry(js_ctx);
  22261. duk_push_array(ctx);
  22262. /* Initial '[' has been checked and eaten by caller. */
  22263. arr_idx = 0;
  22264. for (;;) {
  22265. x = duk__dec_get_nonwhite(js_ctx);
  22266. DUK_DDD(DUK_DDDPRINT("parse_array: arr=%!T, x=%ld, arr_idx=%ld",
  22267. (duk_tval *) duk_get_tval(ctx, -1),
  22268. (long) x, (long) arr_idx));
  22269. /* handle comma and closing bracket */
  22270. if ((x == DUK_ASC_COMMA) && (arr_idx != 0)) {
  22271. /* accept comma, expect new value */
  22272. ;
  22273. } else if (x == DUK_ASC_RBRACKET) {
  22274. /* eat closing bracket */
  22275. break;
  22276. } else if (arr_idx == 0) {
  22277. /* accept anything, expect first value (EOF will be
  22278. * caught by duk__dec_value() below.
  22279. */
  22280. js_ctx->p--; /* backtrack (safe) */
  22281. } else {
  22282. /* catches EOF (and initial comma) */
  22283. goto syntax_error;
  22284. }
  22285. /* parse value */
  22286. duk__dec_value(js_ctx);
  22287. /* [ ... arr val ] */
  22288. duk_xdef_prop_index_wec(ctx, -2, arr_idx);
  22289. arr_idx++;
  22290. }
  22291. /* Must set 'length' explicitly when using duk_xdef_prop_xxx() to
  22292. * set the values.
  22293. */
  22294. duk_set_length(ctx, -1, arr_idx);
  22295. /* [ ... arr ] */
  22296. DUK_DDD(DUK_DDDPRINT("parse_array: final array is %!T",
  22297. (duk_tval *) duk_get_tval(ctx, -1)));
  22298. duk__dec_objarr_exit(js_ctx);
  22299. return;
  22300. syntax_error:
  22301. duk__dec_syntax_error(js_ctx);
  22302. DUK_UNREACHABLE();
  22303. }
  22304. DUK_LOCAL void duk__dec_value(duk_json_dec_ctx *js_ctx) {
  22305. duk_context *ctx = (duk_context *) js_ctx->thr;
  22306. duk_small_int_t x;
  22307. x = duk__dec_get_nonwhite(js_ctx);
  22308. DUK_DDD(DUK_DDDPRINT("parse_value: initial x=%ld", (long) x));
  22309. /* Note: duk__dec_req_stridx() backtracks one char */
  22310. if (x == DUK_ASC_DOUBLEQUOTE) {
  22311. duk__dec_string(js_ctx);
  22312. } else if ((x >= DUK_ASC_0 && x <= DUK_ASC_9) || (x == DUK_ASC_MINUS)) {
  22313. #ifdef DUK_USE_JX
  22314. if (js_ctx->flag_ext_custom && duk__dec_peek(js_ctx) == DUK_ASC_UC_I) {
  22315. duk__dec_req_stridx(js_ctx, DUK_STRIDX_MINUS_INFINITY); /* "-Infinity" */
  22316. duk_push_number(ctx, -DUK_DOUBLE_INFINITY);
  22317. } else {
  22318. #else
  22319. { /* unconditional block */
  22320. #endif
  22321. /* We already ate 'x', so duk__dec_number() will back up one byte. */
  22322. duk__dec_number(js_ctx);
  22323. }
  22324. } else if (x == DUK_ASC_LC_T) {
  22325. duk__dec_req_stridx(js_ctx, DUK_STRIDX_TRUE);
  22326. duk_push_true(ctx);
  22327. } else if (x == DUK_ASC_LC_F) {
  22328. duk__dec_req_stridx(js_ctx, DUK_STRIDX_FALSE);
  22329. duk_push_false(ctx);
  22330. } else if (x == DUK_ASC_LC_N) {
  22331. duk__dec_req_stridx(js_ctx, DUK_STRIDX_LC_NULL);
  22332. duk_push_null(ctx);
  22333. #ifdef DUK_USE_JX
  22334. } else if (js_ctx->flag_ext_custom && x == DUK_ASC_LC_U) {
  22335. duk__dec_req_stridx(js_ctx, DUK_STRIDX_LC_UNDEFINED);
  22336. duk_push_undefined(ctx);
  22337. } else if (js_ctx->flag_ext_custom && x == DUK_ASC_UC_N) {
  22338. duk__dec_req_stridx(js_ctx, DUK_STRIDX_NAN);
  22339. duk_push_nan(ctx);
  22340. } else if (js_ctx->flag_ext_custom && x == DUK_ASC_UC_I) {
  22341. duk__dec_req_stridx(js_ctx, DUK_STRIDX_INFINITY);
  22342. duk_push_number(ctx, DUK_DOUBLE_INFINITY);
  22343. } else if (js_ctx->flag_ext_custom && x == DUK_ASC_LPAREN) {
  22344. duk__dec_pointer(js_ctx);
  22345. } else if (js_ctx->flag_ext_custom && x == DUK_ASC_PIPE) {
  22346. duk__dec_buffer(js_ctx);
  22347. #endif
  22348. } else if (x == DUK_ASC_LCURLY) {
  22349. duk__dec_object(js_ctx);
  22350. } else if (x == DUK_ASC_LBRACKET) {
  22351. duk__dec_array(js_ctx);
  22352. } else {
  22353. /* catches EOF */
  22354. goto syntax_error;
  22355. }
  22356. duk__dec_eat_white(js_ctx);
  22357. /* [ ... val ] */
  22358. return;
  22359. syntax_error:
  22360. duk__dec_syntax_error(js_ctx);
  22361. DUK_UNREACHABLE();
  22362. }
  22363. /* Recursive value reviver, implements the Walk() algorithm. No C recursion
  22364. * check is done here because the initial parsing step will already ensure
  22365. * there is a reasonable limit on C recursion depth and hence object depth.
  22366. */
  22367. DUK_LOCAL void duk__dec_reviver_walk(duk_json_dec_ctx *js_ctx) {
  22368. duk_context *ctx = (duk_context *) js_ctx->thr;
  22369. duk_hobject *h;
  22370. duk_uarridx_t i, arr_len;
  22371. DUK_DDD(DUK_DDDPRINT("walk: top=%ld, holder=%!T, name=%!T",
  22372. (long) duk_get_top(ctx),
  22373. (duk_tval *) duk_get_tval(ctx, -2),
  22374. (duk_tval *) duk_get_tval(ctx, -1)));
  22375. duk_dup_top(ctx);
  22376. duk_get_prop(ctx, -3); /* -> [ ... holder name val ] */
  22377. h = duk_get_hobject(ctx, -1);
  22378. if (h != NULL) {
  22379. if (DUK_HOBJECT_GET_CLASS_NUMBER(h) == DUK_HOBJECT_CLASS_ARRAY) {
  22380. arr_len = (duk_uarridx_t) duk_get_length(ctx, -1);
  22381. for (i = 0; i < arr_len; i++) {
  22382. /* [ ... holder name val ] */
  22383. DUK_DDD(DUK_DDDPRINT("walk: array, top=%ld, i=%ld, arr_len=%ld, holder=%!T, name=%!T, val=%!T",
  22384. (long) duk_get_top(ctx), (long) i, (long) arr_len,
  22385. (duk_tval *) duk_get_tval(ctx, -3), (duk_tval *) duk_get_tval(ctx, -2),
  22386. (duk_tval *) duk_get_tval(ctx, -1)));
  22387. /* XXX: push_uint_string / push_u32_string */
  22388. duk_dup_top(ctx);
  22389. duk_push_uint(ctx, (duk_uint_t) i);
  22390. duk_to_string(ctx, -1); /* -> [ ... holder name val val ToString(i) ] */
  22391. duk__dec_reviver_walk(js_ctx); /* -> [ ... holder name val new_elem ] */
  22392. if (duk_is_undefined(ctx, -1)) {
  22393. duk_pop(ctx);
  22394. duk_del_prop_index(ctx, -1, i);
  22395. } else {
  22396. /* XXX: duk_xdef_prop_index_wec() would be more appropriate
  22397. * here but it currently makes some assumptions that might
  22398. * not hold (e.g. that previous property is not an accessor).
  22399. */
  22400. duk_put_prop_index(ctx, -2, i);
  22401. }
  22402. }
  22403. } else {
  22404. /* [ ... holder name val ] */
  22405. duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY /*flags*/);
  22406. while (duk_next(ctx, -1 /*enum_index*/, 0 /*get_value*/)) {
  22407. DUK_DDD(DUK_DDDPRINT("walk: object, top=%ld, holder=%!T, name=%!T, val=%!T, enum=%!iT, obj_key=%!T",
  22408. (long) duk_get_top(ctx), (duk_tval *) duk_get_tval(ctx, -5),
  22409. (duk_tval *) duk_get_tval(ctx, -4), (duk_tval *) duk_get_tval(ctx, -3),
  22410. (duk_tval *) duk_get_tval(ctx, -2), (duk_tval *) duk_get_tval(ctx, -1)));
  22411. /* [ ... holder name val enum obj_key ] */
  22412. duk_dup(ctx, -3);
  22413. duk_dup(ctx, -2);
  22414. /* [ ... holder name val enum obj_key val obj_key ] */
  22415. duk__dec_reviver_walk(js_ctx);
  22416. /* [ ... holder name val enum obj_key new_elem ] */
  22417. if (duk_is_undefined(ctx, -1)) {
  22418. duk_pop(ctx);
  22419. duk_del_prop(ctx, -3);
  22420. } else {
  22421. /* XXX: duk_xdef_prop_index_wec() would be more appropriate
  22422. * here but it currently makes some assumptions that might
  22423. * not hold (e.g. that previous property is not an accessor).
  22424. *
  22425. * Using duk_put_prop() works incorrectly with '__proto__'
  22426. * if the own property with that name has been deleted. This
  22427. * does not happen normally, but a clever reviver can trigger
  22428. * that, see complex reviver case in: test-bug-json-parse-__proto__.js.
  22429. */
  22430. duk_put_prop(ctx, -4);
  22431. }
  22432. }
  22433. duk_pop(ctx); /* pop enum */
  22434. }
  22435. }
  22436. /* [ ... holder name val ] */
  22437. duk_dup(ctx, js_ctx->idx_reviver);
  22438. duk_insert(ctx, -4); /* -> [ ... reviver holder name val ] */
  22439. duk_call_method(ctx, 2); /* -> [ ... res ] */
  22440. DUK_DDD(DUK_DDDPRINT("walk: top=%ld, result=%!T",
  22441. (long) duk_get_top(ctx), (duk_tval *) duk_get_tval(ctx, -1)));
  22442. }
  22443. /*
  22444. * Stringify implementation.
  22445. */
  22446. #define DUK__EMIT_1(js_ctx,ch) duk__emit_1((js_ctx), (duk_uint_fast8_t) (ch))
  22447. #define DUK__EMIT_2(js_ctx,ch1,ch2) duk__emit_2((js_ctx), (((duk_uint_fast16_t)(ch1)) << 8) + (duk_uint_fast16_t)(ch2))
  22448. #define DUK__EMIT_ESC_AUTO(js_ctx,cp) duk__emit_esc_auto((js_ctx), (cp))
  22449. #define DUK__EMIT_XUTF8(js_ctx,cp) duk__emit_xutf8((js_ctx), (cp))
  22450. #define DUK__EMIT_HSTR(js_ctx,h) duk__emit_hstring((js_ctx), (h))
  22451. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  22452. #define DUK__EMIT_CSTR(js_ctx,p) duk__emit_cstring((js_ctx), (p))
  22453. #endif
  22454. #define DUK__EMIT_STRIDX(js_ctx,i) duk__emit_stridx((js_ctx), (i))
  22455. DUK_LOCAL void duk__emit_1(duk_json_enc_ctx *js_ctx, duk_uint_fast8_t ch) {
  22456. duk_hbuffer_append_byte(js_ctx->thr, js_ctx->h_buf, (duk_uint8_t) ch);
  22457. }
  22458. DUK_LOCAL void duk__emit_2(duk_json_enc_ctx *js_ctx, duk_uint_fast16_t packed_chars) {
  22459. duk_uint8_t buf[2];
  22460. buf[0] = (duk_uint8_t) (packed_chars >> 8);
  22461. buf[1] = (duk_uint8_t) (packed_chars & 0xff);
  22462. duk_hbuffer_append_bytes(js_ctx->thr, js_ctx->h_buf, (duk_uint8_t *) buf, 2);
  22463. }
  22464. #define DUK__MKESC(nybbles,esc1,esc2) \
  22465. (((duk_uint_fast32_t) (nybbles)) << 16) | \
  22466. (((duk_uint_fast32_t) (esc1)) << 8) | \
  22467. ((duk_uint_fast32_t) (esc2))
  22468. DUK_LOCAL void duk__emit_esc_auto(duk_json_enc_ctx *js_ctx, duk_uint_fast32_t cp) {
  22469. duk_uint8_t buf[2];
  22470. duk_uint_fast32_t tmp;
  22471. duk_small_uint_t dig;
  22472. /* Select appropriate escape format automatically, and set 'tmp' to a
  22473. * value encoding both the escape format character and the nybble count:
  22474. *
  22475. * (nybble_count << 16) | (escape_char1) | (escape_char2)
  22476. */
  22477. #ifdef DUK_USE_JX
  22478. if (DUK_LIKELY(cp < 0x100UL)) {
  22479. if (DUK_UNLIKELY(js_ctx->flag_ext_custom)) {
  22480. tmp = DUK__MKESC(2, DUK_ASC_BACKSLASH, DUK_ASC_LC_X);
  22481. } else {
  22482. tmp = DUK__MKESC(4, DUK_ASC_BACKSLASH, DUK_ASC_LC_U);
  22483. }
  22484. } else
  22485. #endif
  22486. if (DUK_LIKELY(cp < 0x10000UL)) {
  22487. tmp = DUK__MKESC(4, DUK_ASC_BACKSLASH, DUK_ASC_LC_U);
  22488. } else {
  22489. #ifdef DUK_USE_JX
  22490. if (DUK_LIKELY(js_ctx->flag_ext_custom)) {
  22491. tmp = DUK__MKESC(8, DUK_ASC_BACKSLASH, DUK_ASC_UC_U);
  22492. } else
  22493. #endif
  22494. {
  22495. /* In compatible mode and standard JSON mode, output
  22496. * something useful for non-BMP characters. This won't
  22497. * roundtrip but will still be more or less readable and
  22498. * more useful than an error.
  22499. */
  22500. tmp = DUK__MKESC(8, DUK_ASC_UC_U, DUK_ASC_PLUS);
  22501. }
  22502. }
  22503. buf[0] = (duk_uint8_t) ((tmp >> 8) & 0xff);
  22504. buf[1] = (duk_uint8_t) (tmp & 0xff);
  22505. duk_hbuffer_append_bytes(js_ctx->thr, js_ctx->h_buf, buf, 2);
  22506. tmp = tmp >> 16;
  22507. while (tmp > 0) {
  22508. tmp--;
  22509. dig = (duk_small_uint_t) ((cp >> (4 * tmp)) & 0x0f);
  22510. duk_hbuffer_append_byte(js_ctx->thr, js_ctx->h_buf, duk_lc_digits[dig]);
  22511. }
  22512. }
  22513. DUK_LOCAL void duk__emit_xutf8(duk_json_enc_ctx *js_ctx, duk_uint_fast32_t cp) {
  22514. (void) duk_hbuffer_append_xutf8(js_ctx->thr, js_ctx->h_buf, cp);
  22515. }
  22516. DUK_LOCAL void duk__emit_hstring(duk_json_enc_ctx *js_ctx, duk_hstring *h) {
  22517. DUK_ASSERT(h != NULL);
  22518. duk_hbuffer_append_bytes(js_ctx->thr,
  22519. js_ctx->h_buf,
  22520. (duk_uint8_t *) DUK_HSTRING_GET_DATA(h),
  22521. (duk_size_t) DUK_HSTRING_GET_BYTELEN(h));
  22522. }
  22523. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  22524. DUK_LOCAL void duk__emit_cstring(duk_json_enc_ctx *js_ctx, const char *p) {
  22525. DUK_ASSERT(p != NULL);
  22526. (void) duk_hbuffer_append_cstring(js_ctx->thr, js_ctx->h_buf, p);
  22527. }
  22528. #endif
  22529. DUK_LOCAL void duk__emit_stridx(duk_json_enc_ctx *js_ctx, duk_small_uint_t stridx) {
  22530. DUK_ASSERT_DISABLE(stridx >= 0); /* unsigned */
  22531. DUK_ASSERT(stridx < DUK_HEAP_NUM_STRINGS);
  22532. duk__emit_hstring(js_ctx, DUK_HTHREAD_GET_STRING(js_ctx->thr, stridx));
  22533. }
  22534. /* Check whether key quotes would be needed (custom encoding). */
  22535. DUK_LOCAL duk_bool_t duk__enc_key_quotes_needed(duk_hstring *h_key) {
  22536. const duk_uint8_t *p, *p_start, *p_end;
  22537. duk_small_uint_t ch;
  22538. DUK_ASSERT(h_key != NULL);
  22539. p_start = DUK_HSTRING_GET_DATA(h_key);
  22540. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_key);
  22541. p = p_start;
  22542. DUK_DDD(DUK_DDDPRINT("duk__enc_key_quotes_needed: h_key=%!O, p_start=%p, p_end=%p, p=%p",
  22543. (duk_heaphdr *) h_key, (void *) p_start, (void *) p_end, (void *) p));
  22544. /* Since we only accept ASCII characters, there is no need for
  22545. * actual decoding. A non-ASCII character will be >= 0x80 which
  22546. * causes a false return value immediately.
  22547. */
  22548. if (p == p_end) {
  22549. /* Zero length string is not accepted without quotes */
  22550. return 1;
  22551. }
  22552. while (p < p_end) {
  22553. ch = (duk_small_uint_t) (*p);
  22554. /* Accept ASCII IdentifierStart and IdentifierPart if not first char.
  22555. * Function selection is a bit uncommon.
  22556. */
  22557. if ((p > p_start ? duk_unicode_is_identifier_part :
  22558. duk_unicode_is_identifier_start) ((duk_codepoint_t) ch)) {
  22559. p++;
  22560. continue;
  22561. }
  22562. /* all non-ASCII characters also come here (first byte >= 0x80) */
  22563. return 1;
  22564. }
  22565. return 0;
  22566. }
  22567. /* The Quote(value) operation: quote a string.
  22568. *
  22569. * Stack policy: [ ] -> [ ].
  22570. */
  22571. DUK_LOCAL duk_uint8_t duk__quote_esc[14] = {
  22572. DUK_ASC_NUL, DUK_ASC_NUL, DUK_ASC_NUL, DUK_ASC_NUL,
  22573. DUK_ASC_NUL, DUK_ASC_NUL, DUK_ASC_NUL, DUK_ASC_NUL,
  22574. DUK_ASC_LC_B, DUK_ASC_LC_T, DUK_ASC_LC_N, DUK_ASC_NUL,
  22575. DUK_ASC_LC_F, DUK_ASC_LC_R
  22576. };
  22577. DUK_LOCAL void duk__enc_quote_string(duk_json_enc_ctx *js_ctx, duk_hstring *h_str) {
  22578. duk_hthread *thr = js_ctx->thr;
  22579. const duk_uint8_t *p, *p_start, *p_end, *p_tmp;
  22580. duk_ucodepoint_t cp; /* typed for duk_unicode_decode_xutf8() */
  22581. DUK_DDD(DUK_DDDPRINT("duk__enc_quote_string: h_str=%!O", (duk_heaphdr *) h_str));
  22582. DUK_ASSERT(h_str != NULL);
  22583. p_start = DUK_HSTRING_GET_DATA(h_str);
  22584. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_str);
  22585. p = p_start;
  22586. DUK__EMIT_1(js_ctx, DUK_ASC_DOUBLEQUOTE);
  22587. while (p < p_end) {
  22588. cp = *p;
  22589. if (DUK_LIKELY(cp <= 0x7f)) {
  22590. /* ascii fast path: avoid decoding utf-8 */
  22591. p++;
  22592. if (cp == 0x22 || cp == 0x5c) {
  22593. /* double quote or backslash */
  22594. DUK__EMIT_2(js_ctx, DUK_ASC_BACKSLASH, cp);
  22595. } else if (cp < 0x20) {
  22596. duk_uint_fast8_t esc_char;
  22597. /* This approach is a bit shorter than a straight
  22598. * if-else-ladder and also a bit faster.
  22599. */
  22600. if (cp < (sizeof(duk__quote_esc) / sizeof(duk_uint8_t)) &&
  22601. (esc_char = duk__quote_esc[cp]) != 0) {
  22602. DUK__EMIT_2(js_ctx, DUK_ASC_BACKSLASH, esc_char);
  22603. } else {
  22604. DUK__EMIT_ESC_AUTO(js_ctx, cp);
  22605. }
  22606. } else if (cp == 0x7f && js_ctx->flag_ascii_only) {
  22607. DUK__EMIT_ESC_AUTO(js_ctx, cp);
  22608. } else {
  22609. /* any other printable -> as is */
  22610. DUK__EMIT_1(js_ctx, cp);
  22611. }
  22612. } else {
  22613. /* slow path decode */
  22614. /* If XUTF-8 decoding fails, treat the offending byte as a codepoint directly
  22615. * and go forward one byte. This is of course very lossy, but allows some kind
  22616. * of output to be produced even for internal strings which don't conform to
  22617. * XUTF-8. All standard Ecmascript strings are always CESU-8, so this behavior
  22618. * does not violate the Ecmascript specification. The behavior is applied to
  22619. * all modes, including Ecmascript standard JSON. Because the current XUTF-8
  22620. * decoding is not very strict, this behavior only really affects initial bytes
  22621. * and truncated codepoints.
  22622. *
  22623. * XXX: another alternative would be to scan forwards to start of next codepoint
  22624. * (or end of input) and emit just one replacement codepoint.
  22625. */
  22626. p_tmp = p;
  22627. if (!duk_unicode_decode_xutf8(thr, &p, p_start, p_end, &cp)) {
  22628. /* Decode failed. */
  22629. cp = *p_tmp;
  22630. p = p_tmp + 1;
  22631. }
  22632. #ifdef DUK_USE_NONSTD_JSON_ESC_U2028_U2029
  22633. if (js_ctx->flag_ascii_only || cp == 0x2028 || cp == 0x2029) {
  22634. #else
  22635. if (js_ctx->flag_ascii_only) {
  22636. #endif
  22637. DUK__EMIT_ESC_AUTO(js_ctx, cp);
  22638. } else {
  22639. /* as is */
  22640. DUK__EMIT_XUTF8(js_ctx, cp);
  22641. }
  22642. }
  22643. }
  22644. DUK__EMIT_1(js_ctx, DUK_ASC_DOUBLEQUOTE);
  22645. }
  22646. /* Shared entry handling for object/array serialization: indent/stepback,
  22647. * loop detection.
  22648. */
  22649. DUK_LOCAL void duk__enc_objarr_entry(duk_json_enc_ctx *js_ctx, duk_hstring **h_stepback, duk_hstring **h_indent, duk_idx_t *entry_top) {
  22650. duk_context *ctx = (duk_context *) js_ctx->thr;
  22651. duk_hobject *h_target;
  22652. *entry_top = duk_get_top(ctx);
  22653. duk_require_stack(ctx, DUK_JSON_ENC_REQSTACK);
  22654. /* loop check */
  22655. h_target = duk_get_hobject(ctx, -1); /* object or array */
  22656. DUK_ASSERT(h_target != NULL);
  22657. duk_push_sprintf(ctx, DUK_STR_FMT_PTR, (void *) h_target);
  22658. duk_dup_top(ctx); /* -> [ ... voidp voidp ] */
  22659. if (duk_has_prop(ctx, js_ctx->idx_loop)) {
  22660. DUK_ERROR((duk_hthread *) ctx, DUK_ERR_TYPE_ERROR, DUK_STR_CYCLIC_INPUT);
  22661. }
  22662. duk_push_true(ctx); /* -> [ ... voidp true ] */
  22663. duk_put_prop(ctx, js_ctx->idx_loop); /* -> [ ... ] */
  22664. /* c recursion check */
  22665. DUK_ASSERT(js_ctx->recursion_depth >= 0);
  22666. DUK_ASSERT(js_ctx->recursion_depth <= js_ctx->recursion_limit);
  22667. if (js_ctx->recursion_depth >= js_ctx->recursion_limit) {
  22668. DUK_ERROR((duk_hthread *) ctx, DUK_ERR_RANGE_ERROR, DUK_STR_JSONENC_RECLIMIT);
  22669. }
  22670. js_ctx->recursion_depth++;
  22671. /* figure out indent and stepback */
  22672. *h_indent = NULL;
  22673. *h_stepback = NULL;
  22674. if (js_ctx->h_gap != NULL) {
  22675. DUK_ASSERT(js_ctx->h_indent != NULL);
  22676. *h_stepback = js_ctx->h_indent;
  22677. duk_push_hstring(ctx, js_ctx->h_indent);
  22678. duk_push_hstring(ctx, js_ctx->h_gap);
  22679. duk_concat(ctx, 2);
  22680. js_ctx->h_indent = duk_get_hstring(ctx, -1);
  22681. *h_indent = js_ctx->h_indent;
  22682. DUK_ASSERT(js_ctx->h_indent != NULL);
  22683. /* The new indent string is left at value stack top, and will
  22684. * be popped by the shared exit handler.
  22685. */
  22686. } else {
  22687. DUK_ASSERT(js_ctx->h_indent == NULL);
  22688. }
  22689. DUK_DDD(DUK_DDDPRINT("shared entry finished: top=%ld, loop=%!T",
  22690. (long) duk_get_top(ctx), (duk_tval *) duk_get_tval(ctx, js_ctx->idx_loop)));
  22691. }
  22692. /* Shared exit handling for object/array serialization. */
  22693. DUK_LOCAL void duk__enc_objarr_exit(duk_json_enc_ctx *js_ctx, duk_hstring **h_stepback, duk_hstring **h_indent, duk_idx_t *entry_top) {
  22694. duk_context *ctx = (duk_context *) js_ctx->thr;
  22695. duk_hobject *h_target;
  22696. DUK_UNREF(h_indent);
  22697. if (js_ctx->h_gap != NULL) {
  22698. DUK_ASSERT(js_ctx->h_indent != NULL);
  22699. DUK_ASSERT(*h_stepback != NULL);
  22700. DUK_ASSERT(*h_indent != NULL);
  22701. js_ctx->h_indent = *h_stepback; /* previous js_ctx->h_indent */
  22702. /* Note: we don't need to pop anything because the duk_set_top()
  22703. * at the end will take care of it.
  22704. */
  22705. } else {
  22706. DUK_ASSERT(js_ctx->h_indent == NULL);
  22707. DUK_ASSERT(*h_stepback == NULL);
  22708. DUK_ASSERT(*h_indent == NULL);
  22709. }
  22710. /* c recursion check */
  22711. DUK_ASSERT(js_ctx->recursion_depth > 0);
  22712. DUK_ASSERT(js_ctx->recursion_depth <= js_ctx->recursion_limit);
  22713. js_ctx->recursion_depth--;
  22714. /* loop check */
  22715. h_target = duk_get_hobject(ctx, *entry_top - 1); /* original target at entry_top - 1 */
  22716. DUK_ASSERT(h_target != NULL);
  22717. duk_push_sprintf(ctx, DUK_STR_FMT_PTR, (void *) h_target);
  22718. duk_del_prop(ctx, js_ctx->idx_loop); /* -> [ ... ] */
  22719. /* restore stack top after unbalanced code paths */
  22720. duk_set_top(ctx, *entry_top);
  22721. DUK_DDD(DUK_DDDPRINT("shared entry finished: top=%ld, loop=%!T",
  22722. (long) duk_get_top(ctx), (duk_tval *) duk_get_tval(ctx, js_ctx->idx_loop)));
  22723. }
  22724. /* The JO(value) operation: encode object.
  22725. *
  22726. * Stack policy: [ object ] -> [ object ].
  22727. */
  22728. DUK_LOCAL void duk__enc_object(duk_json_enc_ctx *js_ctx) {
  22729. duk_context *ctx = (duk_context *) js_ctx->thr;
  22730. duk_hstring *h_stepback;
  22731. duk_hstring *h_indent;
  22732. duk_hstring *h_key;
  22733. duk_idx_t entry_top;
  22734. duk_idx_t idx_obj;
  22735. duk_idx_t idx_keys;
  22736. duk_bool_t first;
  22737. duk_bool_t undef;
  22738. duk_uarridx_t arr_len, i;
  22739. DUK_DDD(DUK_DDDPRINT("duk__enc_object: obj=%!T", (duk_tval *) duk_get_tval(ctx, -1)));
  22740. duk__enc_objarr_entry(js_ctx, &h_stepback, &h_indent, &entry_top);
  22741. idx_obj = entry_top - 1;
  22742. if (js_ctx->idx_proplist >= 0) {
  22743. idx_keys = js_ctx->idx_proplist;
  22744. } else {
  22745. /* XXX: would be nice to enumerate an object at specified index */
  22746. duk_dup(ctx, idx_obj);
  22747. (void) duk_hobject_get_enumerated_keys(ctx, DUK_ENUM_OWN_PROPERTIES_ONLY /*flags*/); /* [ ... target ] -> [ ... target keys ] */
  22748. idx_keys = duk_require_normalize_index(ctx, -1);
  22749. /* leave stack unbalanced on purpose */
  22750. }
  22751. DUK_DDD(DUK_DDDPRINT("idx_keys=%ld, h_keys=%!T",
  22752. (long) idx_keys, (duk_tval *) duk_get_tval(ctx, idx_keys)));
  22753. /* Steps 8-10 have been merged to avoid a "partial" variable. */
  22754. DUK__EMIT_1(js_ctx, DUK_ASC_LCURLY);
  22755. /* XXX: keys is an internal object with all keys to be processed
  22756. * in its (gapless) array part. Because nobody can touch the keys
  22757. * object, we could iterate its array part directly (keeping in mind
  22758. * that it can be reallocated).
  22759. */
  22760. arr_len = (duk_uarridx_t) duk_get_length(ctx, idx_keys);
  22761. first = 1;
  22762. for (i = 0; i < arr_len; i++) {
  22763. duk_get_prop_index(ctx, idx_keys, i); /* -> [ ... key ] */
  22764. DUK_DDD(DUK_DDDPRINT("object property loop: holder=%!T, key=%!T",
  22765. (duk_tval *) duk_get_tval(ctx, idx_obj),
  22766. (duk_tval *) duk_get_tval(ctx, -1)));
  22767. undef = duk__enc_value1(js_ctx, idx_obj);
  22768. if (undef) {
  22769. /* Value would yield 'undefined', so skip key altogether.
  22770. * Side effects have already happened.
  22771. */
  22772. continue;
  22773. }
  22774. /* [ ... key val ] */
  22775. if (first) {
  22776. first = 0;
  22777. } else {
  22778. DUK__EMIT_1(js_ctx, DUK_ASC_COMMA);
  22779. }
  22780. if (h_indent != NULL) {
  22781. DUK__EMIT_1(js_ctx, 0x0a);
  22782. DUK__EMIT_HSTR(js_ctx, h_indent);
  22783. }
  22784. h_key = duk_get_hstring(ctx, -2);
  22785. DUK_ASSERT(h_key != NULL);
  22786. if (js_ctx->flag_avoid_key_quotes && !duk__enc_key_quotes_needed(h_key)) {
  22787. /* emit key as is */
  22788. DUK__EMIT_HSTR(js_ctx, h_key);
  22789. } else {
  22790. duk__enc_quote_string(js_ctx, h_key);
  22791. }
  22792. if (h_indent != NULL) {
  22793. DUK__EMIT_2(js_ctx, DUK_ASC_COLON, DUK_ASC_SPACE);
  22794. } else {
  22795. DUK__EMIT_1(js_ctx, DUK_ASC_COLON);
  22796. }
  22797. /* [ ... key val ] */
  22798. duk__enc_value2(js_ctx); /* -> [ ... ] */
  22799. }
  22800. if (!first) {
  22801. if (h_stepback != NULL) {
  22802. DUK_ASSERT(h_indent != NULL);
  22803. DUK__EMIT_1(js_ctx, 0x0a);
  22804. DUK__EMIT_HSTR(js_ctx, h_stepback);
  22805. }
  22806. }
  22807. DUK__EMIT_1(js_ctx, DUK_ASC_RCURLY);
  22808. duk__enc_objarr_exit(js_ctx, &h_stepback, &h_indent, &entry_top);
  22809. DUK_ASSERT_TOP(ctx, entry_top);
  22810. }
  22811. /* The JA(value) operation: encode array.
  22812. *
  22813. * Stack policy: [ array ] -> [ array ].
  22814. */
  22815. DUK_LOCAL void duk__enc_array(duk_json_enc_ctx *js_ctx) {
  22816. duk_context *ctx = (duk_context *) js_ctx->thr;
  22817. duk_hstring *h_stepback;
  22818. duk_hstring *h_indent;
  22819. duk_idx_t entry_top;
  22820. duk_idx_t idx_arr;
  22821. duk_bool_t undef;
  22822. duk_uarridx_t i, arr_len;
  22823. DUK_DDD(DUK_DDDPRINT("duk__enc_array: array=%!T",
  22824. (duk_tval *) duk_get_tval(ctx, -1)));
  22825. duk__enc_objarr_entry(js_ctx, &h_stepback, &h_indent, &entry_top);
  22826. idx_arr = entry_top - 1;
  22827. /* Steps 8-10 have been merged to avoid a "partial" variable. */
  22828. DUK__EMIT_1(js_ctx, DUK_ASC_LBRACKET);
  22829. arr_len = (duk_uarridx_t) duk_get_length(ctx, idx_arr);
  22830. for (i = 0; i < arr_len; i++) {
  22831. DUK_DDD(DUK_DDDPRINT("array entry loop: array=%!T, h_indent=%!O, h_stepback=%!O, index=%ld, arr_len=%ld",
  22832. (duk_tval *) duk_get_tval(ctx, idx_arr), (duk_heaphdr *) h_indent,
  22833. (duk_heaphdr *) h_stepback, (long) i, (long) arr_len));
  22834. if (i > 0) {
  22835. DUK__EMIT_1(js_ctx, DUK_ASC_COMMA);
  22836. }
  22837. if (h_indent != NULL) {
  22838. DUK__EMIT_1(js_ctx, 0x0a);
  22839. DUK__EMIT_HSTR(js_ctx, h_indent);
  22840. }
  22841. /* XXX: duk_push_uint_string() */
  22842. duk_push_uint(ctx, (duk_uint_t) i);
  22843. duk_to_string(ctx, -1); /* -> [ ... key ] */
  22844. undef = duk__enc_value1(js_ctx, idx_arr);
  22845. if (undef) {
  22846. DUK__EMIT_STRIDX(js_ctx, DUK_STRIDX_LC_NULL);
  22847. } else {
  22848. /* [ ... key val ] */
  22849. duk__enc_value2(js_ctx);
  22850. }
  22851. }
  22852. if (arr_len > 0) {
  22853. if (h_stepback != NULL) {
  22854. DUK_ASSERT(h_indent != NULL);
  22855. DUK__EMIT_1(js_ctx, 0x0a);
  22856. DUK__EMIT_HSTR(js_ctx, h_stepback);
  22857. }
  22858. }
  22859. DUK__EMIT_1(js_ctx, DUK_ASC_RBRACKET);
  22860. duk__enc_objarr_exit(js_ctx, &h_stepback, &h_indent, &entry_top);
  22861. DUK_ASSERT_TOP(ctx, entry_top);
  22862. }
  22863. /* The Str(key, holder) operation: encode value, steps 1-4.
  22864. *
  22865. * Returns non-zero if the value between steps 4 and 5 would yield an
  22866. * 'undefined' final result. This is useful in JO() because we need to
  22867. * get the side effects out, but need to know whether or not a key will
  22868. * be omitted from the serialization.
  22869. *
  22870. * Stack policy: [ ... key ] -> [ ... key val ] if retval == 0.
  22871. * -> [ ... ] if retval != 0.
  22872. */
  22873. DUK_LOCAL duk_bool_t duk__enc_value1(duk_json_enc_ctx *js_ctx, duk_idx_t idx_holder) {
  22874. duk_context *ctx = (duk_context *) js_ctx->thr;
  22875. duk_hobject *h;
  22876. duk_tval *tv;
  22877. duk_small_int_t c;
  22878. DUK_DDD(DUK_DDDPRINT("duk__enc_value1: idx_holder=%ld, holder=%!T, key=%!T",
  22879. (long) idx_holder, (duk_tval *) duk_get_tval(ctx, idx_holder),
  22880. (duk_tval *) duk_get_tval(ctx, -1)));
  22881. duk_dup_top(ctx); /* -> [ ... key key ] */
  22882. duk_get_prop(ctx, idx_holder); /* -> [ ... key val ] */
  22883. DUK_DDD(DUK_DDDPRINT("value=%!T", (duk_tval *) duk_get_tval(ctx, -1)));
  22884. h = duk_get_hobject_or_lfunc_coerce(ctx, -1);
  22885. if (h != NULL) {
  22886. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_TO_JSON);
  22887. h = duk_get_hobject_or_lfunc_coerce(ctx, -1); /* toJSON() can also be a lightfunc */
  22888. if (h != NULL && DUK_HOBJECT_IS_CALLABLE(h)) {
  22889. DUK_DDD(DUK_DDDPRINT("value is object, has callable toJSON() -> call it"));
  22890. duk_dup(ctx, -2); /* -> [ ... key val toJSON val ] */
  22891. duk_dup(ctx, -4); /* -> [ ... key val toJSON val key ] */
  22892. duk_call_method(ctx, 1); /* -> [ ... key val val' ] */
  22893. duk_remove(ctx, -2); /* -> [ ... key val' ] */
  22894. } else {
  22895. duk_pop(ctx);
  22896. }
  22897. }
  22898. /* [ ... key val ] */
  22899. DUK_DDD(DUK_DDDPRINT("value=%!T", (duk_tval *) duk_get_tval(ctx, -1)));
  22900. if (js_ctx->h_replacer) {
  22901. /* XXX: here a "slice copy" would be useful */
  22902. DUK_DDD(DUK_DDDPRINT("replacer is set, call replacer"));
  22903. duk_push_hobject(ctx, js_ctx->h_replacer); /* -> [ ... key val replacer ] */
  22904. duk_dup(ctx, idx_holder); /* -> [ ... key val replacer holder ] */
  22905. duk_dup(ctx, -4); /* -> [ ... key val replacer holder key ] */
  22906. duk_dup(ctx, -4); /* -> [ ... key val replacer holder key val ] */
  22907. duk_call_method(ctx, 2); /* -> [ ... key val val' ] */
  22908. duk_remove(ctx, -2); /* -> [ ... key val' ] */
  22909. }
  22910. /* [ ... key val ] */
  22911. DUK_DDD(DUK_DDDPRINT("value=%!T", (duk_tval *) duk_get_tval(ctx, -1)));
  22912. tv = duk_get_tval(ctx, -1);
  22913. DUK_ASSERT(tv != NULL);
  22914. if (DUK_TVAL_IS_OBJECT(tv)) {
  22915. h = DUK_TVAL_GET_OBJECT(tv);
  22916. DUK_ASSERT(h != NULL);
  22917. c = (duk_small_int_t) DUK_HOBJECT_GET_CLASS_NUMBER(h);
  22918. switch ((int) c) {
  22919. case DUK_HOBJECT_CLASS_NUMBER:
  22920. DUK_DDD(DUK_DDDPRINT("value is a Number object -> coerce with ToNumber()"));
  22921. duk_to_number(ctx, -1);
  22922. break;
  22923. case DUK_HOBJECT_CLASS_STRING:
  22924. DUK_DDD(DUK_DDDPRINT("value is a String object -> coerce with ToString()"));
  22925. duk_to_string(ctx, -1);
  22926. break;
  22927. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  22928. case DUK_HOBJECT_CLASS_BUFFER:
  22929. case DUK_HOBJECT_CLASS_POINTER:
  22930. #endif
  22931. case DUK_HOBJECT_CLASS_BOOLEAN:
  22932. DUK_DDD(DUK_DDDPRINT("value is a Boolean/Buffer/Pointer object -> get internal value"));
  22933. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE);
  22934. duk_remove(ctx, -2);
  22935. break;
  22936. }
  22937. }
  22938. /* [ ... key val ] */
  22939. DUK_DDD(DUK_DDDPRINT("value=%!T", (duk_tval *) duk_get_tval(ctx, -1)));
  22940. if (duk_check_type_mask(ctx, -1, js_ctx->mask_for_undefined)) {
  22941. /* will result in undefined */
  22942. DUK_DDD(DUK_DDDPRINT("-> will result in undefined (type mask check)"));
  22943. goto undef;
  22944. }
  22945. /* functions are detected specially */
  22946. h = duk_get_hobject(ctx, -1);
  22947. if (h != NULL && DUK_HOBJECT_IS_CALLABLE(h)) {
  22948. if (js_ctx->flags & (DUK_JSON_FLAG_EXT_CUSTOM |
  22949. DUK_JSON_FLAG_EXT_COMPATIBLE)) {
  22950. /* function will be serialized to custom format */
  22951. } else {
  22952. /* functions are not serialized, results in undefined */
  22953. DUK_DDD(DUK_DDDPRINT("-> will result in undefined (function)"));
  22954. goto undef;
  22955. }
  22956. }
  22957. DUK_DDD(DUK_DDDPRINT("-> will not result in undefined"));
  22958. return 0;
  22959. undef:
  22960. duk_pop_2(ctx);
  22961. return 1;
  22962. }
  22963. /* The Str(key, holder) operation: encode value, steps 5-10.
  22964. *
  22965. * This must not be called unless duk__enc_value1() returns non-zero.
  22966. * If so, this is guaranteed to produce a non-undefined result.
  22967. * Non-standard encodings (e.g. for undefined) are only used if
  22968. * duk__enc_value1() indicates they are accepted; they're not
  22969. * checked or asserted here again.
  22970. *
  22971. * Stack policy: [ ... key val ] -> [ ... ].
  22972. */
  22973. DUK_LOCAL void duk__enc_value2(duk_json_enc_ctx *js_ctx) {
  22974. duk_context *ctx = (duk_context *) js_ctx->thr;
  22975. duk_hthread *thr = (duk_hthread *) ctx;
  22976. duk_tval *tv;
  22977. DUK_UNREF(thr);
  22978. DUK_DDD(DUK_DDDPRINT("duk__enc_value2: key=%!T, val=%!T",
  22979. (duk_tval *) duk_get_tval(ctx, -2),
  22980. (duk_tval *) duk_get_tval(ctx, -1)));
  22981. /* [ ... key val ] */
  22982. tv = duk_get_tval(ctx, -1);
  22983. DUK_ASSERT(tv != NULL);
  22984. switch (DUK_TVAL_GET_TAG(tv)) {
  22985. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  22986. /* When JX/JC not in use, duk__enc_value1 will block undefined values. */
  22987. case DUK_TAG_UNDEFINED: {
  22988. DUK__EMIT_STRIDX(js_ctx, js_ctx->stridx_custom_undefined);
  22989. break;
  22990. }
  22991. #endif
  22992. case DUK_TAG_NULL: {
  22993. DUK__EMIT_STRIDX(js_ctx, DUK_STRIDX_LC_NULL);
  22994. break;
  22995. }
  22996. case DUK_TAG_BOOLEAN: {
  22997. DUK__EMIT_STRIDX(js_ctx, DUK_TVAL_GET_BOOLEAN(tv) ?
  22998. DUK_STRIDX_TRUE : DUK_STRIDX_FALSE);
  22999. break;
  23000. }
  23001. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23002. /* When JX/JC not in use, duk__enc_value1 will block pointer values. */
  23003. case DUK_TAG_POINTER: {
  23004. char buf[64]; /* XXX: how to figure correct size? */
  23005. const char *fmt;
  23006. void *ptr = DUK_TVAL_GET_POINTER(tv);
  23007. DUK_MEMZERO(buf, sizeof(buf));
  23008. /* The #ifdef clutter here needs to handle the three cases:
  23009. * (1) JX+JC, (2) JX only, (3) JC only.
  23010. */
  23011. #if defined(DUK_USE_JX) && defined(DUK_USE_JC)
  23012. if (js_ctx->flag_ext_custom)
  23013. #endif
  23014. #if defined(DUK_USE_JX)
  23015. {
  23016. fmt = ptr ? "(%p)" : "(null)";
  23017. }
  23018. #endif
  23019. #if defined(DUK_USE_JX) && defined(DUK_USE_JC)
  23020. else
  23021. #endif
  23022. #if defined(DUK_USE_JC)
  23023. {
  23024. fmt = ptr ? "{\"_ptr\":\"%p\"}" : "{\"_ptr\":\"null\"}";
  23025. }
  23026. #endif
  23027. /* When ptr == NULL, the format argument is unused. */
  23028. DUK_SNPRINTF(buf, sizeof(buf) - 1, fmt, ptr); /* must not truncate */
  23029. DUK__EMIT_CSTR(js_ctx, buf);
  23030. break;
  23031. }
  23032. #endif /* DUK_USE_JX || DUK_USE_JC */
  23033. case DUK_TAG_STRING: {
  23034. duk_hstring *h = DUK_TVAL_GET_STRING(tv);
  23035. DUK_ASSERT(h != NULL);
  23036. duk__enc_quote_string(js_ctx, h);
  23037. break;
  23038. }
  23039. case DUK_TAG_OBJECT: {
  23040. duk_hobject *h = DUK_TVAL_GET_OBJECT(tv);
  23041. DUK_ASSERT(h != NULL);
  23042. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23043. if (DUK_HOBJECT_IS_CALLABLE(h)) {
  23044. /* We only get here when doing non-standard JSON encoding */
  23045. DUK_ASSERT(js_ctx->flag_ext_custom || js_ctx->flag_ext_compatible);
  23046. DUK__EMIT_STRIDX(js_ctx, js_ctx->stridx_custom_function);
  23047. } else /* continues below */
  23048. #endif
  23049. if (DUK_HOBJECT_GET_CLASS_NUMBER(h) == DUK_HOBJECT_CLASS_ARRAY) {
  23050. duk__enc_array(js_ctx);
  23051. } else {
  23052. duk__enc_object(js_ctx);
  23053. }
  23054. break;
  23055. }
  23056. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23057. /* When JX/JC not in use, duk__enc_value1 will block buffer values. */
  23058. case DUK_TAG_BUFFER: {
  23059. /* Buffer values are encoded in (lowercase) hex to make the
  23060. * binary data readable. Base64 or similar would be more
  23061. * compact but less readable, and the point of JX/JC
  23062. * variants is to be as useful to a programmer as possible.
  23063. */
  23064. /* The #ifdef clutter here needs to handle the three cases:
  23065. * (1) JX+JC, (2) JX only, (3) JC only.
  23066. */
  23067. #if defined(DUK_USE_JX) && defined(DUK_USE_JC)
  23068. if (js_ctx->flag_ext_custom)
  23069. #endif
  23070. #if defined(DUK_USE_JX)
  23071. {
  23072. duk_uint8_t *p, *p_end;
  23073. duk_small_uint_t x;
  23074. duk_hbuffer *h;
  23075. h = DUK_TVAL_GET_BUFFER(tv);
  23076. DUK_ASSERT(h != NULL);
  23077. p = (duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h);
  23078. p_end = p + DUK_HBUFFER_GET_SIZE(h);
  23079. DUK__EMIT_1(js_ctx, DUK_ASC_PIPE);
  23080. while (p < p_end) {
  23081. x = *p++;
  23082. duk_hbuffer_append_byte(js_ctx->thr, js_ctx->h_buf, duk_lc_digits[(x >> 4) & 0x0f]);
  23083. duk_hbuffer_append_byte(js_ctx->thr, js_ctx->h_buf, duk_lc_digits[x & 0x0f]);
  23084. }
  23085. DUK__EMIT_1(js_ctx, DUK_ASC_PIPE);
  23086. }
  23087. #endif
  23088. #if defined(DUK_USE_JX) && defined(DUK_USE_JC)
  23089. else
  23090. #endif
  23091. #if defined(DUK_USE_JC)
  23092. {
  23093. DUK_ASSERT(js_ctx->flag_ext_compatible);
  23094. duk_hex_encode(ctx, -1);
  23095. DUK__EMIT_CSTR(js_ctx, "{\"_buf\":");
  23096. duk__enc_quote_string(js_ctx, duk_require_hstring(ctx, -1));
  23097. DUK__EMIT_1(js_ctx, DUK_ASC_RCURLY);
  23098. }
  23099. #endif
  23100. break;
  23101. }
  23102. #endif /* DUK_USE_JX || DUK_USE_JC */
  23103. case DUK_TAG_LIGHTFUNC: {
  23104. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23105. /* We only get here when doing non-standard JSON encoding */
  23106. DUK_ASSERT(js_ctx->flag_ext_custom || js_ctx->flag_ext_compatible);
  23107. DUK__EMIT_STRIDX(js_ctx, js_ctx->stridx_custom_function);
  23108. #else
  23109. /* Standard JSON omits functions */
  23110. DUK_UNREACHABLE();
  23111. #endif
  23112. break;
  23113. }
  23114. #if defined(DUK_USE_FASTINT)
  23115. case DUK_TAG_FASTINT:
  23116. #endif
  23117. default: {
  23118. /* number */
  23119. duk_double_t d;
  23120. duk_small_int_t c;
  23121. duk_small_int_t s;
  23122. duk_small_uint_t stridx;
  23123. duk_small_uint_t n2s_flags;
  23124. duk_hstring *h_str;
  23125. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  23126. d = DUK_TVAL_GET_NUMBER(tv);
  23127. c = (duk_small_int_t) DUK_FPCLASSIFY(d);
  23128. s = (duk_small_int_t) DUK_SIGNBIT(d);
  23129. DUK_UNREF(s);
  23130. if (DUK_LIKELY(!(c == DUK_FP_INFINITE || c == DUK_FP_NAN))) {
  23131. DUK_ASSERT(DUK_ISFINITE(d));
  23132. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23133. /* Negative zero needs special handling in JX/JC because
  23134. * it would otherwise serialize to '0', not '-0'.
  23135. */
  23136. if (DUK_UNLIKELY(c == DUK_FP_ZERO && s != 0 &&
  23137. (js_ctx->flag_ext_custom || js_ctx->flag_ext_compatible))) {
  23138. duk_push_hstring_stridx(ctx, DUK_STRIDX_MINUS_ZERO); /* '-0' */
  23139. } else
  23140. #endif /* DUK_USE_JX || DUK_USE_JC */
  23141. {
  23142. n2s_flags = 0;
  23143. /* [ ... number ] -> [ ... string ] */
  23144. duk_numconv_stringify(ctx, 10 /*radix*/, 0 /*digits*/, n2s_flags);
  23145. }
  23146. h_str = duk_to_hstring(ctx, -1);
  23147. DUK_ASSERT(h_str != NULL);
  23148. DUK__EMIT_HSTR(js_ctx, h_str);
  23149. break;
  23150. }
  23151. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23152. if (!(js_ctx->flags & (DUK_JSON_FLAG_EXT_CUSTOM |
  23153. DUK_JSON_FLAG_EXT_COMPATIBLE))) {
  23154. stridx = DUK_STRIDX_LC_NULL;
  23155. } else if (c == DUK_FP_NAN) {
  23156. stridx = js_ctx->stridx_custom_nan;
  23157. } else if (s == 0) {
  23158. stridx = js_ctx->stridx_custom_posinf;
  23159. } else {
  23160. stridx = js_ctx->stridx_custom_neginf;
  23161. }
  23162. #else
  23163. stridx = DUK_STRIDX_LC_NULL;
  23164. #endif
  23165. DUK__EMIT_STRIDX(js_ctx, stridx);
  23166. break;
  23167. }
  23168. }
  23169. /* [ ... key val ] -> [ ... ] */
  23170. duk_pop_2(ctx);
  23171. }
  23172. /* E5 Section 15.12.3, main algorithm, step 4.b.ii steps 1-4. */
  23173. DUK_LOCAL duk_bool_t duk__enc_allow_into_proplist(duk_tval *tv) {
  23174. duk_hobject *h;
  23175. duk_small_int_t c;
  23176. DUK_ASSERT(tv != NULL);
  23177. if (DUK_TVAL_IS_STRING(tv) || DUK_TVAL_IS_NUMBER(tv)) {
  23178. return 1;
  23179. } else if (DUK_TVAL_IS_OBJECT(tv)) {
  23180. h = DUK_TVAL_GET_OBJECT(tv);
  23181. DUK_ASSERT(h != NULL);
  23182. c = (duk_small_int_t) DUK_HOBJECT_GET_CLASS_NUMBER(h);
  23183. if (c == DUK_HOBJECT_CLASS_STRING || c == DUK_HOBJECT_CLASS_NUMBER) {
  23184. return 1;
  23185. }
  23186. }
  23187. return 0;
  23188. }
  23189. /*
  23190. * Top level wrappers
  23191. */
  23192. DUK_INTERNAL
  23193. void duk_bi_json_parse_helper(duk_context *ctx,
  23194. duk_idx_t idx_value,
  23195. duk_idx_t idx_reviver,
  23196. duk_small_uint_t flags) {
  23197. duk_hthread *thr = (duk_hthread *) ctx;
  23198. duk_json_dec_ctx js_ctx_alloc;
  23199. duk_json_dec_ctx *js_ctx = &js_ctx_alloc;
  23200. duk_hstring *h_text;
  23201. #ifdef DUK_USE_ASSERTIONS
  23202. duk_idx_t entry_top = duk_get_top(ctx);
  23203. #endif
  23204. /* negative top-relative indices not allowed now */
  23205. DUK_ASSERT(idx_value == DUK_INVALID_INDEX || idx_value >= 0);
  23206. DUK_ASSERT(idx_reviver == DUK_INVALID_INDEX || idx_reviver >= 0);
  23207. DUK_DDD(DUK_DDDPRINT("JSON parse start: text=%!T, reviver=%!T, flags=0x%08lx, stack_top=%ld",
  23208. (duk_tval *) duk_get_tval(ctx, idx_value),
  23209. (duk_tval *) duk_get_tval(ctx, idx_reviver),
  23210. (unsigned long) flags,
  23211. (long) duk_get_top(ctx)));
  23212. DUK_MEMZERO(&js_ctx_alloc, sizeof(js_ctx_alloc));
  23213. js_ctx->thr = thr;
  23214. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  23215. /* nothing now */
  23216. #endif
  23217. js_ctx->recursion_limit = DUK_JSON_DEC_RECURSION_LIMIT;
  23218. /* Flag handling currently assumes that flags are consistent. This is OK
  23219. * because the call sites are now strictly controlled.
  23220. */
  23221. js_ctx->flags = flags;
  23222. #ifdef DUK_USE_JX
  23223. js_ctx->flag_ext_custom = flags & DUK_JSON_FLAG_EXT_CUSTOM;
  23224. #endif
  23225. #ifdef DUK_USE_JC
  23226. js_ctx->flag_ext_compatible = flags & DUK_JSON_FLAG_EXT_COMPATIBLE;
  23227. #endif
  23228. h_text = duk_to_hstring(ctx, idx_value); /* coerce in-place */
  23229. DUK_ASSERT(h_text != NULL);
  23230. js_ctx->p_start = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h_text);
  23231. js_ctx->p = js_ctx->p_start;
  23232. js_ctx->p_end = ((duk_uint8_t *) DUK_HSTRING_GET_DATA(h_text)) +
  23233. DUK_HSTRING_GET_BYTELEN(h_text);
  23234. duk__dec_value(js_ctx); /* -> [ ... value ] */
  23235. /* Trailing whitespace has been eaten by duk__dec_value(), so if
  23236. * we're not at end of input here, it's a SyntaxError.
  23237. */
  23238. if (js_ctx->p != js_ctx->p_end) {
  23239. duk__dec_syntax_error(js_ctx);
  23240. }
  23241. if (duk_is_callable(ctx, idx_reviver)) {
  23242. DUK_DDD(DUK_DDDPRINT("applying reviver: %!T",
  23243. (duk_tval *) duk_get_tval(ctx, idx_reviver)));
  23244. js_ctx->idx_reviver = idx_reviver;
  23245. duk_push_object(ctx);
  23246. duk_dup(ctx, -2); /* -> [ ... val root val ] */
  23247. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_EMPTY_STRING); /* default attrs ok */
  23248. duk_push_hstring_stridx(ctx, DUK_STRIDX_EMPTY_STRING); /* -> [ ... val root "" ] */
  23249. DUK_DDD(DUK_DDDPRINT("start reviver walk, root=%!T, name=%!T",
  23250. (duk_tval *) duk_get_tval(ctx, -2),
  23251. (duk_tval *) duk_get_tval(ctx, -1)));
  23252. duk__dec_reviver_walk(js_ctx); /* [ ... val root "" ] -> [ ... val val' ] */
  23253. duk_remove(ctx, -2); /* -> [ ... val' ] */
  23254. } else {
  23255. DUK_DDD(DUK_DDDPRINT("reviver does not exist or is not callable: %!T",
  23256. (duk_tval *) duk_get_tval(ctx, idx_reviver)));
  23257. }
  23258. /* Final result is at stack top. */
  23259. DUK_DDD(DUK_DDDPRINT("JSON parse end: text=%!T, reviver=%!T, flags=0x%08lx, result=%!T, stack_top=%ld",
  23260. (duk_tval *) duk_get_tval(ctx, idx_value),
  23261. (duk_tval *) duk_get_tval(ctx, idx_reviver),
  23262. (unsigned long) flags,
  23263. (duk_tval *) duk_get_tval(ctx, -1),
  23264. (long) duk_get_top(ctx)));
  23265. DUK_ASSERT(duk_get_top(ctx) == entry_top + 1);
  23266. }
  23267. DUK_INTERNAL
  23268. void duk_bi_json_stringify_helper(duk_context *ctx,
  23269. duk_idx_t idx_value,
  23270. duk_idx_t idx_replacer,
  23271. duk_idx_t idx_space,
  23272. duk_small_uint_t flags) {
  23273. duk_hthread *thr = (duk_hthread *) ctx;
  23274. duk_json_enc_ctx js_ctx_alloc;
  23275. duk_json_enc_ctx *js_ctx = &js_ctx_alloc;
  23276. duk_hobject *h;
  23277. duk_bool_t undef;
  23278. duk_idx_t idx_holder;
  23279. duk_idx_t entry_top;
  23280. /* negative top-relative indices not allowed now */
  23281. DUK_ASSERT(idx_value == DUK_INVALID_INDEX || idx_value >= 0);
  23282. DUK_ASSERT(idx_replacer == DUK_INVALID_INDEX || idx_replacer >= 0);
  23283. DUK_ASSERT(idx_space == DUK_INVALID_INDEX || idx_space >= 0);
  23284. DUK_DDD(DUK_DDDPRINT("JSON stringify start: value=%!T, replacer=%!T, space=%!T, flags=0x%08lx, stack_top=%ld",
  23285. (duk_tval *) duk_get_tval(ctx, idx_value),
  23286. (duk_tval *) duk_get_tval(ctx, idx_replacer),
  23287. (duk_tval *) duk_get_tval(ctx, idx_space),
  23288. (unsigned long) flags,
  23289. (long) duk_get_top(ctx)));
  23290. entry_top = duk_get_top(ctx);
  23291. /*
  23292. * Context init
  23293. */
  23294. DUK_MEMZERO(&js_ctx_alloc, sizeof(js_ctx_alloc));
  23295. js_ctx->thr = thr;
  23296. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  23297. js_ctx->h_replacer = NULL;
  23298. js_ctx->h_gap = NULL;
  23299. js_ctx->h_indent = NULL;
  23300. #endif
  23301. js_ctx->idx_proplist = -1;
  23302. js_ctx->recursion_limit = DUK_JSON_ENC_RECURSION_LIMIT;
  23303. /* Flag handling currently assumes that flags are consistent. This is OK
  23304. * because the call sites are now strictly controlled.
  23305. */
  23306. js_ctx->flags = flags;
  23307. js_ctx->flag_ascii_only = flags & DUK_JSON_FLAG_ASCII_ONLY;
  23308. js_ctx->flag_avoid_key_quotes = flags & DUK_JSON_FLAG_AVOID_KEY_QUOTES;
  23309. #ifdef DUK_USE_JX
  23310. js_ctx->flag_ext_custom = flags & DUK_JSON_FLAG_EXT_CUSTOM;
  23311. #endif
  23312. #ifdef DUK_USE_JC
  23313. js_ctx->flag_ext_compatible = flags & DUK_JSON_FLAG_EXT_COMPATIBLE;
  23314. #endif
  23315. /* The #ifdef clutter here handles the JX/JC enable/disable
  23316. * combinations properly.
  23317. */
  23318. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23319. #if defined(DUK_USE_JX)
  23320. if (flags & DUK_JSON_FLAG_EXT_CUSTOM) {
  23321. js_ctx->stridx_custom_undefined = DUK_STRIDX_LC_UNDEFINED;
  23322. js_ctx->stridx_custom_nan = DUK_STRIDX_NAN;
  23323. js_ctx->stridx_custom_neginf = DUK_STRIDX_MINUS_INFINITY;
  23324. js_ctx->stridx_custom_posinf = DUK_STRIDX_INFINITY;
  23325. js_ctx->stridx_custom_function =
  23326. (flags & DUK_JSON_FLAG_AVOID_KEY_QUOTES) ?
  23327. DUK_STRIDX_JSON_EXT_FUNCTION2 :
  23328. DUK_STRIDX_JSON_EXT_FUNCTION1;
  23329. }
  23330. #endif /* DUK_USE_JX */
  23331. #if defined(DUK_USE_JX) && defined(DUK_USE_JC)
  23332. else
  23333. #endif /* DUK_USE_JX && DUK_USE_JC */
  23334. #if defined(DUK_USE_JC)
  23335. if (js_ctx->flags & DUK_JSON_FLAG_EXT_COMPATIBLE) {
  23336. js_ctx->stridx_custom_undefined = DUK_STRIDX_JSON_EXT_UNDEFINED;
  23337. js_ctx->stridx_custom_nan = DUK_STRIDX_JSON_EXT_NAN;
  23338. js_ctx->stridx_custom_neginf = DUK_STRIDX_JSON_EXT_NEGINF;
  23339. js_ctx->stridx_custom_posinf = DUK_STRIDX_JSON_EXT_POSINF;
  23340. js_ctx->stridx_custom_function = DUK_STRIDX_JSON_EXT_FUNCTION1;
  23341. }
  23342. #endif /* DUK_USE_JC */
  23343. #endif /* DUK_USE_JX || DUK_USE_JC */
  23344. #if defined(DUK_USE_JX) || defined(DUK_USE_JC)
  23345. if (js_ctx->flags & (DUK_JSON_FLAG_EXT_CUSTOM |
  23346. DUK_JSON_FLAG_EXT_COMPATIBLE)) {
  23347. DUK_ASSERT(js_ctx->mask_for_undefined == 0); /* already zero */
  23348. }
  23349. else
  23350. #endif /* DUK_USE_JX || DUK_USE_JC */
  23351. {
  23352. js_ctx->mask_for_undefined = DUK_TYPE_MASK_UNDEFINED |
  23353. DUK_TYPE_MASK_POINTER |
  23354. DUK_TYPE_MASK_BUFFER |
  23355. DUK_TYPE_MASK_LIGHTFUNC;
  23356. }
  23357. (void) duk_push_dynamic_buffer(ctx, 0);
  23358. js_ctx->h_buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  23359. DUK_ASSERT(js_ctx->h_buf != NULL);
  23360. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(js_ctx->h_buf));
  23361. js_ctx->idx_loop = duk_push_object_internal(ctx);
  23362. DUK_ASSERT(js_ctx->idx_loop >= 0);
  23363. /* [ ... buf loop ] */
  23364. /*
  23365. * Process replacer/proplist (2nd argument to JSON.stringify)
  23366. */
  23367. h = duk_get_hobject(ctx, idx_replacer);
  23368. if (h != NULL) {
  23369. if (DUK_HOBJECT_IS_CALLABLE(h)) {
  23370. js_ctx->h_replacer = h;
  23371. } else if (DUK_HOBJECT_GET_CLASS_NUMBER(h) == DUK_HOBJECT_CLASS_ARRAY) {
  23372. /* Here the specification requires correct array index enumeration
  23373. * which is a bit tricky for sparse arrays (it is handled by the
  23374. * enum setup code). We now enumerate ancestors too, although the
  23375. * specification is not very clear on whether that is required.
  23376. */
  23377. duk_uarridx_t plist_idx = 0;
  23378. duk_small_uint_t enum_flags;
  23379. js_ctx->idx_proplist = duk_push_array(ctx); /* XXX: array internal? */
  23380. enum_flags = DUK_ENUM_ARRAY_INDICES_ONLY |
  23381. DUK_ENUM_SORT_ARRAY_INDICES; /* expensive flag */
  23382. duk_enum(ctx, idx_replacer, enum_flags);
  23383. while (duk_next(ctx, -1 /*enum_index*/, 1 /*get_value*/)) {
  23384. /* [ ... proplist enum_obj key val ] */
  23385. if (duk__enc_allow_into_proplist(duk_get_tval(ctx, -1))) {
  23386. /* XXX: duplicates should be eliminated here */
  23387. DUK_DDD(DUK_DDDPRINT("proplist enum: key=%!T, val=%!T --> accept",
  23388. (duk_tval *) duk_get_tval(ctx, -2),
  23389. (duk_tval *) duk_get_tval(ctx, -1)));
  23390. duk_to_string(ctx, -1); /* extra coercion of strings is OK */
  23391. duk_put_prop_index(ctx, -4, plist_idx); /* -> [ ... proplist enum_obj key ] */
  23392. plist_idx++;
  23393. duk_pop(ctx);
  23394. } else {
  23395. DUK_DDD(DUK_DDDPRINT("proplist enum: key=%!T, val=%!T --> reject",
  23396. (duk_tval *) duk_get_tval(ctx, -2),
  23397. (duk_tval *) duk_get_tval(ctx, -1)));
  23398. duk_pop_2(ctx);
  23399. }
  23400. }
  23401. duk_pop(ctx); /* pop enum */
  23402. /* [ ... proplist ] */
  23403. }
  23404. }
  23405. /* [ ... buf loop (proplist) ] */
  23406. /*
  23407. * Process space (3rd argument to JSON.stringify)
  23408. */
  23409. h = duk_get_hobject(ctx, idx_space);
  23410. if (h != NULL) {
  23411. int c = DUK_HOBJECT_GET_CLASS_NUMBER(h);
  23412. if (c == DUK_HOBJECT_CLASS_NUMBER) {
  23413. duk_to_number(ctx, idx_space);
  23414. } else if (c == DUK_HOBJECT_CLASS_STRING) {
  23415. duk_to_string(ctx, idx_space);
  23416. }
  23417. }
  23418. if (duk_is_number(ctx, idx_space)) {
  23419. duk_small_int_t nspace;
  23420. /* spaces[] must be static to allow initializer with old compilers like BCC */
  23421. static const char spaces[10] = {
  23422. DUK_ASC_SPACE, DUK_ASC_SPACE, DUK_ASC_SPACE, DUK_ASC_SPACE,
  23423. DUK_ASC_SPACE, DUK_ASC_SPACE, DUK_ASC_SPACE, DUK_ASC_SPACE,
  23424. DUK_ASC_SPACE, DUK_ASC_SPACE
  23425. }; /* XXX: helper */
  23426. /* ToInteger() coercion; NaN -> 0, infinities are clamped to 0 and 10 */
  23427. nspace = (duk_small_int_t) duk_to_int_clamped(ctx, idx_space, 0 /*minval*/, 10 /*maxval*/);
  23428. DUK_ASSERT(nspace >= 0 && nspace <= 10);
  23429. duk_push_lstring(ctx, spaces, (duk_size_t) nspace);
  23430. js_ctx->h_gap = duk_get_hstring(ctx, -1);
  23431. DUK_ASSERT(js_ctx->h_gap != NULL);
  23432. } else if (duk_is_string(ctx, idx_space)) {
  23433. /* XXX: substring in-place at idx_place? */
  23434. duk_dup(ctx, idx_space);
  23435. duk_substring(ctx, -1, 0, 10); /* clamp to 10 chars */
  23436. js_ctx->h_gap = duk_get_hstring(ctx, -1);
  23437. DUK_ASSERT(js_ctx->h_gap != NULL);
  23438. } else {
  23439. /* nop */
  23440. }
  23441. if (js_ctx->h_gap != NULL) {
  23442. /* if gap is empty, behave as if not given at all */
  23443. if (DUK_HSTRING_GET_CHARLEN(js_ctx->h_gap) == 0) {
  23444. js_ctx->h_gap = NULL;
  23445. } else {
  23446. /* set 'indent' only if it will actually increase */
  23447. js_ctx->h_indent = DUK_HTHREAD_STRING_EMPTY_STRING(thr);
  23448. }
  23449. }
  23450. DUK_ASSERT((js_ctx->h_gap == NULL && js_ctx->h_indent == NULL) ||
  23451. (js_ctx->h_gap != NULL && js_ctx->h_indent != NULL));
  23452. /* [ ... buf loop (proplist) (gap) ] */
  23453. /*
  23454. * Create wrapper object and serialize
  23455. */
  23456. idx_holder = duk_push_object(ctx);
  23457. duk_dup(ctx, idx_value);
  23458. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_EMPTY_STRING);
  23459. DUK_DDD(DUK_DDDPRINT("before: flags=0x%08lx, buf=%!O, loop=%!T, replacer=%!O, "
  23460. "proplist=%!T, gap=%!O, indent=%!O, holder=%!T",
  23461. (unsigned long) js_ctx->flags,
  23462. (duk_heaphdr *) js_ctx->h_buf,
  23463. (duk_tval *) duk_get_tval(ctx, js_ctx->idx_loop),
  23464. (duk_heaphdr *) js_ctx->h_replacer,
  23465. (duk_tval *) (js_ctx->idx_proplist >= 0 ? duk_get_tval(ctx, js_ctx->idx_proplist) : NULL),
  23466. (duk_heaphdr *) js_ctx->h_gap,
  23467. (duk_heaphdr *) js_ctx->h_indent,
  23468. (duk_tval *) duk_get_tval(ctx, -1)));
  23469. /* serialize the wrapper with empty string key */
  23470. duk_push_hstring_stridx(ctx, DUK_STRIDX_EMPTY_STRING);
  23471. /* [ ... buf loop (proplist) (gap) holder "" ] */
  23472. undef = duk__enc_value1(js_ctx, idx_holder); /* [ ... holder key ] -> [ ... holder key val ] */
  23473. DUK_DDD(DUK_DDDPRINT("after: flags=0x%08lx, buf=%!O, loop=%!T, replacer=%!O, "
  23474. "proplist=%!T, gap=%!O, indent=%!O, holder=%!T",
  23475. (unsigned long) js_ctx->flags,
  23476. (duk_heaphdr *) js_ctx->h_buf,
  23477. (duk_tval *) duk_get_tval(ctx, js_ctx->idx_loop),
  23478. (duk_heaphdr *) js_ctx->h_replacer,
  23479. (duk_tval *) (js_ctx->idx_proplist >= 0 ? duk_get_tval(ctx, js_ctx->idx_proplist) : NULL),
  23480. (duk_heaphdr *) js_ctx->h_gap,
  23481. (duk_heaphdr *) js_ctx->h_indent,
  23482. (duk_tval *) duk_get_tval(ctx, -3)));
  23483. if (undef) {
  23484. /*
  23485. * Result is undefined
  23486. */
  23487. duk_push_undefined(ctx);
  23488. } else {
  23489. /*
  23490. * Finish and convert buffer to result string
  23491. */
  23492. duk__enc_value2(js_ctx); /* [ ... key val ] -> [ ... ] */
  23493. DUK_ASSERT(js_ctx->h_buf != NULL);
  23494. duk_push_hbuffer(ctx, (duk_hbuffer *) js_ctx->h_buf);
  23495. duk_to_string(ctx, -1);
  23496. }
  23497. /* The stack has a variable shape here, so force it to the
  23498. * desired one explicitly.
  23499. */
  23500. duk_replace(ctx, entry_top);
  23501. duk_set_top(ctx, entry_top + 1);
  23502. DUK_DDD(DUK_DDDPRINT("JSON stringify end: value=%!T, replacer=%!T, space=%!T, "
  23503. "flags=0x%08lx, result=%!T, stack_top=%ld",
  23504. (duk_tval *) duk_get_tval(ctx, idx_value),
  23505. (duk_tval *) duk_get_tval(ctx, idx_replacer),
  23506. (duk_tval *) duk_get_tval(ctx, idx_space),
  23507. (unsigned long) flags,
  23508. (duk_tval *) duk_get_tval(ctx, -1),
  23509. (long) duk_get_top(ctx)));
  23510. DUK_ASSERT(duk_get_top(ctx) == entry_top + 1);
  23511. }
  23512. /*
  23513. * Entry points
  23514. */
  23515. DUK_INTERNAL duk_ret_t duk_bi_json_object_parse(duk_context *ctx) {
  23516. duk_bi_json_parse_helper(ctx,
  23517. 0 /*idx_value*/,
  23518. 1 /*idx_replacer*/,
  23519. 0 /*flags*/);
  23520. return 1;
  23521. }
  23522. DUK_INTERNAL duk_ret_t duk_bi_json_object_stringify(duk_context *ctx) {
  23523. duk_bi_json_stringify_helper(ctx,
  23524. 0 /*idx_value*/,
  23525. 1 /*idx_replacer*/,
  23526. 2 /*idx_space*/,
  23527. 0 /*flags*/);
  23528. return 1;
  23529. }
  23530. #line 1 "duk_bi_logger.c"
  23531. /*
  23532. * Logging support
  23533. */
  23534. /* include removed: duk_internal.h */
  23535. /* 3-letter log level strings */
  23536. DUK_LOCAL const duk_uint8_t duk__log_level_strings[] = {
  23537. (duk_uint8_t) DUK_ASC_UC_T, (duk_uint8_t) DUK_ASC_UC_R, (duk_uint8_t) DUK_ASC_UC_C,
  23538. (duk_uint8_t) DUK_ASC_UC_D, (duk_uint8_t) DUK_ASC_UC_B, (duk_uint8_t) DUK_ASC_UC_G,
  23539. (duk_uint8_t) DUK_ASC_UC_I, (duk_uint8_t) DUK_ASC_UC_N, (duk_uint8_t) DUK_ASC_UC_F,
  23540. (duk_uint8_t) DUK_ASC_UC_W, (duk_uint8_t) DUK_ASC_UC_R, (duk_uint8_t) DUK_ASC_UC_N,
  23541. (duk_uint8_t) DUK_ASC_UC_E, (duk_uint8_t) DUK_ASC_UC_R, (duk_uint8_t) DUK_ASC_UC_R,
  23542. (duk_uint8_t) DUK_ASC_UC_F, (duk_uint8_t) DUK_ASC_UC_T, (duk_uint8_t) DUK_ASC_UC_L
  23543. };
  23544. /* Constructor */
  23545. DUK_INTERNAL duk_ret_t duk_bi_logger_constructor(duk_context *ctx) {
  23546. duk_hthread *thr = (duk_hthread *) ctx;
  23547. duk_idx_t nargs;
  23548. /* Calling as a non-constructor is not meaningful. */
  23549. if (!duk_is_constructor_call(ctx)) {
  23550. return DUK_RET_TYPE_ERROR;
  23551. }
  23552. nargs = duk_get_top(ctx);
  23553. duk_set_top(ctx, 1);
  23554. duk_push_this(ctx);
  23555. /* [ name this ] */
  23556. if (nargs == 0) {
  23557. /* Automatic defaulting of logger name from caller. This would
  23558. * work poorly with tail calls, but constructor calls are currently
  23559. * never tail calls, so tail calls are not an issue now.
  23560. */
  23561. if (thr->callstack_top >= 2) {
  23562. duk_activation *act_caller = thr->callstack + thr->callstack_top - 2;
  23563. duk_hobject *func_caller;
  23564. func_caller = DUK_ACT_GET_FUNC(act_caller);
  23565. if (func_caller) {
  23566. /* Stripping the filename might be a good idea
  23567. * ("/foo/bar/quux.js" -> logger name "quux"),
  23568. * but now used verbatim.
  23569. */
  23570. duk_push_hobject(ctx, func_caller);
  23571. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_FILE_NAME);
  23572. duk_replace(ctx, 0);
  23573. }
  23574. }
  23575. }
  23576. /* the stack is unbalanced here on purpose; we only rely on the
  23577. * initial two values: [ name this ].
  23578. */
  23579. if (duk_is_string(ctx, 0)) {
  23580. duk_dup(ctx, 0);
  23581. duk_put_prop_stridx(ctx, 1, DUK_STRIDX_LC_N);
  23582. } else {
  23583. /* don't set 'n' at all, inherited value is used as name */
  23584. }
  23585. duk_compact(ctx, 1);
  23586. return 0; /* keep default instance */
  23587. }
  23588. /* Default function to format objects. Tries to use toLogString() but falls
  23589. * back to toString(). Any errors are propagated out without catching.
  23590. */
  23591. DUK_INTERNAL duk_ret_t duk_bi_logger_prototype_fmt(duk_context *ctx) {
  23592. if (duk_get_prop_stridx(ctx, 0, DUK_STRIDX_TO_LOG_STRING)) {
  23593. /* [ arg toLogString ] */
  23594. duk_dup(ctx, 0);
  23595. duk_call_method(ctx, 0);
  23596. /* [ arg result ] */
  23597. return 1;
  23598. }
  23599. /* [ arg undefined ] */
  23600. duk_pop(ctx);
  23601. duk_to_string(ctx, 0);
  23602. return 1;
  23603. }
  23604. /* Default function to write a formatted log line. Writes to stderr,
  23605. * appending a newline to the log line.
  23606. *
  23607. * The argument is a buffer whose visible size contains the log message.
  23608. * This function should avoid coercing the buffer to a string to avoid
  23609. * string table traffic.
  23610. */
  23611. DUK_INTERNAL duk_ret_t duk_bi_logger_prototype_raw(duk_context *ctx) {
  23612. const char *data;
  23613. duk_size_t data_len;
  23614. DUK_UNREF(ctx);
  23615. DUK_UNREF(data);
  23616. DUK_UNREF(data_len);
  23617. #ifdef DUK_USE_FILE_IO
  23618. data = (const char *) duk_require_buffer(ctx, 0, &data_len);
  23619. DUK_FWRITE((const void *) data, 1, data_len, DUK_STDERR);
  23620. DUK_FPUTC((int) '\n', DUK_STDERR);
  23621. DUK_FFLUSH(DUK_STDERR);
  23622. #else
  23623. /* nop */
  23624. #endif
  23625. return 0;
  23626. }
  23627. /* Log frontend shared helper, magic value indicates log level. Provides
  23628. * frontend functions: trace(), debug(), info(), warn(), error(), fatal().
  23629. * This needs to have small footprint, reasonable performance, minimal
  23630. * memory churn, etc.
  23631. */
  23632. DUK_INTERNAL duk_ret_t duk_bi_logger_prototype_log_shared(duk_context *ctx) {
  23633. duk_hthread *thr = (duk_hthread *) ctx;
  23634. duk_double_t now;
  23635. duk_small_int_t entry_lev = duk_get_current_magic(ctx);
  23636. duk_small_int_t logger_lev;
  23637. duk_int_t nargs;
  23638. duk_int_t i;
  23639. duk_size_t tot_len;
  23640. const duk_uint8_t *arg_str;
  23641. duk_size_t arg_len;
  23642. duk_uint8_t *buf, *p;
  23643. const duk_uint8_t *q;
  23644. duk_uint8_t date_buf[DUK_BI_DATE_ISO8601_BUFSIZE];
  23645. duk_size_t date_len;
  23646. duk_small_int_t rc;
  23647. DUK_ASSERT(entry_lev >= 0 && entry_lev <= 5);
  23648. /* XXX: sanitize to printable (and maybe ASCII) */
  23649. /* XXX: better multiline */
  23650. /*
  23651. * Logger arguments are:
  23652. *
  23653. * magic: log level (0-5)
  23654. * this: logger
  23655. * stack: plain log args
  23656. *
  23657. * We want to minimize memory churn so a two-pass approach
  23658. * is used: first pass formats arguments and computes final
  23659. * string length, second pass copies strings either into a
  23660. * pre-allocated and reused buffer (short messages) or into a
  23661. * newly allocated fixed buffer. If the backend function plays
  23662. * nice, it won't coerce the buffer to a string (and thus
  23663. * intern it).
  23664. */
  23665. nargs = duk_get_top(ctx);
  23666. /* [ arg1 ... argN this ] */
  23667. /*
  23668. * Log level check
  23669. */
  23670. duk_push_this(ctx);
  23671. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_LC_L);
  23672. logger_lev = (duk_small_int_t) duk_get_int(ctx, -1);
  23673. if (entry_lev < logger_lev) {
  23674. return 0;
  23675. }
  23676. /* log level could be popped but that's not necessary */
  23677. now = duk_bi_date_get_now(ctx);
  23678. duk_bi_date_format_timeval(now, date_buf);
  23679. date_len = DUK_STRLEN((const char *) date_buf);
  23680. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_LC_N);
  23681. duk_to_string(ctx, -1);
  23682. DUK_ASSERT(duk_is_string(ctx, -1));
  23683. /* [ arg1 ... argN this loggerLevel loggerName ] */
  23684. /*
  23685. * Pass 1
  23686. */
  23687. /* Line format: <time> <entryLev> <loggerName>: <msg> */
  23688. tot_len = 0;
  23689. tot_len += 3 + /* separators: space, space, colon */
  23690. 3 + /* level string */
  23691. date_len + /* time */
  23692. duk_get_length(ctx, -1); /* loggerName */
  23693. for (i = 0; i < nargs; i++) {
  23694. /* When formatting an argument to a string, errors may happen from multiple
  23695. * causes. In general we want to catch obvious errors like a toLogString()
  23696. * throwing an error, but we don't currently try to catch every possible
  23697. * error. In particular, internal errors (like out of memory or stack) are
  23698. * not caught. Also, we expect Error toString() to not throw an error.
  23699. */
  23700. if (duk_is_object(ctx, i)) {
  23701. /* duk_pcall_prop() may itself throw an error, but we're content
  23702. * in catching the obvious errors (like toLogString() throwing an
  23703. * error).
  23704. */
  23705. duk_push_hstring_stridx(ctx, DUK_STRIDX_FMT);
  23706. duk_dup(ctx, i);
  23707. /* [ arg1 ... argN this loggerLevel loggerName 'fmt' arg ] */
  23708. /* call: this.fmt(arg) */
  23709. rc = duk_pcall_prop(ctx, -5 /*obj_index*/, 1 /*nargs*/);
  23710. if (rc) {
  23711. /* Keep the error as the result (coercing it might fail below,
  23712. * but we don't catch that now).
  23713. */
  23714. ;
  23715. }
  23716. duk_replace(ctx, i);
  23717. }
  23718. (void) duk_to_lstring(ctx, i, &arg_len);
  23719. tot_len++; /* sep (even before first one) */
  23720. tot_len += arg_len;
  23721. }
  23722. /*
  23723. * Pass 2
  23724. */
  23725. if (tot_len <= DUK_BI_LOGGER_SHORT_MSG_LIMIT) {
  23726. duk_hbuffer_dynamic *h_buf;
  23727. DUK_DDD(DUK_DDDPRINT("reuse existing small log message buffer, tot_len %ld", (long) tot_len));
  23728. /* We can assert for all buffer properties because user code
  23729. * never has access to heap->log_buffer.
  23730. */
  23731. DUK_ASSERT(thr != NULL);
  23732. DUK_ASSERT(thr->heap != NULL);
  23733. h_buf = thr->heap->log_buffer;
  23734. DUK_ASSERT(h_buf != NULL);
  23735. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC((duk_hbuffer *) h_buf));
  23736. DUK_ASSERT(DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(h_buf) == DUK_BI_LOGGER_SHORT_MSG_LIMIT);
  23737. /* Set buffer 'visible size' to actual message length and
  23738. * push it to the stack.
  23739. */
  23740. DUK_HBUFFER_SET_SIZE((duk_hbuffer *) h_buf, tot_len);
  23741. duk_push_hbuffer(ctx, (duk_hbuffer *) h_buf);
  23742. buf = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, h_buf);
  23743. } else {
  23744. DUK_DDD(DUK_DDDPRINT("use a one-off large log message buffer, tot_len %ld", (long) tot_len));
  23745. buf = (duk_uint8_t *) duk_push_fixed_buffer(ctx, tot_len);
  23746. }
  23747. DUK_ASSERT(buf != NULL);
  23748. p = buf;
  23749. DUK_MEMCPY((void *) p, (void *) date_buf, date_len);
  23750. p += date_len;
  23751. *p++ = (duk_uint8_t) DUK_ASC_SPACE;
  23752. q = duk__log_level_strings + (entry_lev * 3);
  23753. DUK_MEMCPY((void *) p, (void *) q, (duk_size_t) 3);
  23754. p += 3;
  23755. *p++ = (duk_uint8_t) DUK_ASC_SPACE;
  23756. arg_str = (const duk_uint8_t *) duk_get_lstring(ctx, -2, &arg_len);
  23757. DUK_MEMCPY((void *) p, (const void *) arg_str, arg_len);
  23758. p += arg_len;
  23759. *p++ = (duk_uint8_t) DUK_ASC_COLON;
  23760. for (i = 0; i < nargs; i++) {
  23761. *p++ = (duk_uint8_t) DUK_ASC_SPACE;
  23762. arg_str = (const duk_uint8_t *) duk_get_lstring(ctx, i, &arg_len);
  23763. DUK_ASSERT(arg_str != NULL);
  23764. DUK_MEMCPY((void *) p, (const void *) arg_str, arg_len);
  23765. p += arg_len;
  23766. }
  23767. DUK_ASSERT(buf + tot_len == p);
  23768. /* [ arg1 ... argN this loggerLevel loggerName buffer ] */
  23769. #if defined(DUK_USE_DEBUGGER_SUPPORT) && defined(DUK_USE_DEBUGGER_FWD_LOGGING)
  23770. /* Do debugger forwarding before raw() because the raw() function
  23771. * doesn't get the log level right now.
  23772. */
  23773. if (DUK_HEAP_IS_DEBUGGER_ATTACHED(thr->heap)) {
  23774. const char *log_buf;
  23775. duk_size_t sz_buf;
  23776. log_buf = (const char *) duk_get_buffer(ctx, -1, &sz_buf);
  23777. DUK_ASSERT(log_buf != NULL);
  23778. duk_debug_write_notify(thr, DUK_DBG_CMD_LOG);
  23779. duk_debug_write_int(thr, (duk_int32_t) entry_lev);
  23780. duk_debug_write_string(thr, (const char *) log_buf, sz_buf);
  23781. duk_debug_write_eom(thr);
  23782. }
  23783. #endif
  23784. /* Call this.raw(msg); look up through the instance allows user to override
  23785. * the raw() function in the instance or in the prototype for maximum
  23786. * flexibility.
  23787. */
  23788. duk_push_hstring_stridx(ctx, DUK_STRIDX_RAW);
  23789. duk_dup(ctx, -2);
  23790. /* [ arg1 ... argN this loggerLevel loggerName buffer 'raw' buffer ] */
  23791. duk_call_prop(ctx, -6, 1); /* this.raw(buffer) */
  23792. return 0;
  23793. }
  23794. #line 1 "duk_bi_math.c"
  23795. /*
  23796. * Math built-ins
  23797. */
  23798. /* include removed: duk_internal.h */
  23799. #if defined(DUK_USE_MATH_BUILTIN)
  23800. /*
  23801. * Use static helpers which can work with math.h functions matching
  23802. * the following signatures. This is not portable if any of these math
  23803. * functions is actually a macro.
  23804. *
  23805. * Typing here is intentionally 'double' wherever values interact with
  23806. * the standard library APIs.
  23807. */
  23808. typedef double (*duk__one_arg_func)(double);
  23809. typedef double (*duk__two_arg_func)(double, double);
  23810. DUK_LOCAL duk_ret_t duk__math_minmax(duk_context *ctx, duk_double_t initial, duk__two_arg_func min_max) {
  23811. duk_idx_t n = duk_get_top(ctx);
  23812. duk_idx_t i;
  23813. duk_double_t res = initial;
  23814. duk_double_t t;
  23815. /*
  23816. * Note: fmax() does not match the E5 semantics. E5 requires
  23817. * that if -any- input to Math.max() is a NaN, the result is a
  23818. * NaN. fmax() will return a NaN only if -both- inputs are NaN.
  23819. * Same applies to fmin().
  23820. *
  23821. * Note: every input value must be coerced with ToNumber(), even
  23822. * if we know the result will be a NaN anyway: ToNumber() may have
  23823. * side effects for which even order of evaluation matters.
  23824. */
  23825. for (i = 0; i < n; i++) {
  23826. t = duk_to_number(ctx, i);
  23827. if (DUK_FPCLASSIFY(t) == DUK_FP_NAN || DUK_FPCLASSIFY(res) == DUK_FP_NAN) {
  23828. /* Note: not normalized, but duk_push_number() will normalize */
  23829. res = (duk_double_t) DUK_DOUBLE_NAN;
  23830. } else {
  23831. res = (duk_double_t) min_max(res, (double) t);
  23832. }
  23833. }
  23834. duk_push_number(ctx, res);
  23835. return 1;
  23836. }
  23837. DUK_LOCAL double duk__fmin_fixed(double x, double y) {
  23838. /* fmin() with args -0 and +0 is not guaranteed to return
  23839. * -0 as Ecmascript requires.
  23840. */
  23841. if (x == 0 && y == 0) {
  23842. /* XXX: what's the safest way of creating a negative zero? */
  23843. if (DUK_SIGNBIT(x) != 0 || DUK_SIGNBIT(y) != 0) {
  23844. return -0.0;
  23845. } else {
  23846. return +0.0;
  23847. }
  23848. }
  23849. #ifdef DUK_USE_MATH_FMIN
  23850. return DUK_FMIN(x, y);
  23851. #else
  23852. return (x < y ? x : y);
  23853. #endif
  23854. }
  23855. DUK_LOCAL double duk__fmax_fixed(double x, double y) {
  23856. /* fmax() with args -0 and +0 is not guaranteed to return
  23857. * +0 as Ecmascript requires.
  23858. */
  23859. if (x == 0 && y == 0) {
  23860. if (DUK_SIGNBIT(x) == 0 || DUK_SIGNBIT(y) == 0) {
  23861. return +0.0;
  23862. } else {
  23863. return -0.0;
  23864. }
  23865. }
  23866. #ifdef DUK_USE_MATH_FMAX
  23867. return DUK_FMAX(x, y);
  23868. #else
  23869. return (x > y ? x : y);
  23870. #endif
  23871. }
  23872. DUK_LOCAL double duk__round_fixed(double x) {
  23873. /* Numbers half-way between integers must be rounded towards +Infinity,
  23874. * e.g. -3.5 must be rounded to -3 (not -4). When rounded to zero, zero
  23875. * sign must be set appropriately. E5.1 Section 15.8.2.15.
  23876. *
  23877. * Note that ANSI C round() is "round to nearest integer, away from zero",
  23878. * which is incorrect for negative values. Here we make do with floor().
  23879. */
  23880. duk_small_int_t c = (duk_small_int_t) DUK_FPCLASSIFY(x);
  23881. if (c == DUK_FP_NAN || c == DUK_FP_INFINITE || c == DUK_FP_ZERO) {
  23882. return x;
  23883. }
  23884. /*
  23885. * x is finite and non-zero
  23886. *
  23887. * -1.6 -> floor(-1.1) -> -2
  23888. * -1.5 -> floor(-1.0) -> -1 (towards +Inf)
  23889. * -1.4 -> floor(-0.9) -> -1
  23890. * -0.5 -> -0.0 (special case)
  23891. * -0.1 -> -0.0 (special case)
  23892. * +0.1 -> +0.0 (special case)
  23893. * +0.5 -> floor(+1.0) -> 1 (towards +Inf)
  23894. * +1.4 -> floor(+1.9) -> 1
  23895. * +1.5 -> floor(+2.0) -> 2 (towards +Inf)
  23896. * +1.6 -> floor(+2.1) -> 2
  23897. */
  23898. if (x >= -0.5 && x < 0.5) {
  23899. /* +0.5 is handled by floor, this is on purpose */
  23900. if (x < 0.0) {
  23901. return -0.0;
  23902. } else {
  23903. return +0.0;
  23904. }
  23905. }
  23906. return DUK_FLOOR(x + 0.5);
  23907. }
  23908. DUK_LOCAL double duk__pow_fixed(double x, double y) {
  23909. /* The ANSI C pow() semantics differ from Ecmascript.
  23910. *
  23911. * E.g. when x==1 and y is +/- infinite, the Ecmascript required
  23912. * result is NaN, while at least Linux pow() returns 1.
  23913. */
  23914. duk_small_int_t cx, cy, sx;
  23915. DUK_UNREF(cx);
  23916. DUK_UNREF(sx);
  23917. cy = (duk_small_int_t) DUK_FPCLASSIFY(y);
  23918. if (cy == DUK_FP_NAN) {
  23919. goto ret_nan;
  23920. }
  23921. if (DUK_FABS(x) == 1.0 && cy == DUK_FP_INFINITE) {
  23922. goto ret_nan;
  23923. }
  23924. #if defined(DUK_USE_POW_NETBSD_WORKAROUND)
  23925. /* See test-bug-netbsd-math-pow.js: NetBSD 6.0 on x86 (at least) does not
  23926. * correctly handle some cases where x=+/-0. Specific fixes to these
  23927. * here.
  23928. */
  23929. cx = (duk_small_int_t) DUK_FPCLASSIFY(x);
  23930. if (cx == DUK_FP_ZERO && y < 0.0) {
  23931. sx = (duk_small_int_t) DUK_SIGNBIT(x);
  23932. if (sx == 0) {
  23933. /* Math.pow(+0,y) should be Infinity when y<0. NetBSD pow()
  23934. * returns -Infinity instead when y is <0 and finite. The
  23935. * if-clause also catches y == -Infinity (which works even
  23936. * without the fix).
  23937. */
  23938. return DUK_DOUBLE_INFINITY;
  23939. } else {
  23940. /* Math.pow(-0,y) where y<0 should be:
  23941. * - -Infinity if y<0 and an odd integer
  23942. * - Infinity otherwise
  23943. * NetBSD pow() returns -Infinity for all finite y<0. The
  23944. * if-clause also catches y == -Infinity (which works even
  23945. * without the fix).
  23946. */
  23947. /* fmod() return value has same sign as input (negative) so
  23948. * the result here will be in the range ]-2,0], 1 indicates
  23949. * odd. If x is -Infinity, NaN is returned and the odd check
  23950. * always concludes "not odd" which results in desired outcome.
  23951. */
  23952. double tmp = DUK_FMOD(y, 2);
  23953. if (tmp == -1.0) {
  23954. return -DUK_DOUBLE_INFINITY;
  23955. } else {
  23956. /* Not odd, or y == -Infinity */
  23957. return DUK_DOUBLE_INFINITY;
  23958. }
  23959. }
  23960. }
  23961. #endif
  23962. return DUK_POW(x, y);
  23963. ret_nan:
  23964. return DUK_DOUBLE_NAN;
  23965. }
  23966. /* Wrappers for calling standard math library methods. These may be required
  23967. * on platforms where one or more of the math built-ins are defined as macros
  23968. * or inline functions and are thus not suitable to be used as function pointers.
  23969. */
  23970. #if defined(DUK_USE_AVOID_PLATFORM_FUNCPTRS)
  23971. DUK_LOCAL double duk__fabs(double x) {
  23972. return DUK_FABS(x);
  23973. }
  23974. DUK_LOCAL double duk__acos(double x) {
  23975. return DUK_ACOS(x);
  23976. }
  23977. DUK_LOCAL double duk__asin(double x) {
  23978. return DUK_ASIN(x);
  23979. }
  23980. DUK_LOCAL double duk__atan(double x) {
  23981. return DUK_ATAN(x);
  23982. }
  23983. DUK_LOCAL double duk__ceil(double x) {
  23984. return DUK_CEIL(x);
  23985. }
  23986. DUK_LOCAL double duk__cos(double x) {
  23987. return DUK_COS(x);
  23988. }
  23989. DUK_LOCAL double duk__exp(double x) {
  23990. return DUK_EXP(x);
  23991. }
  23992. DUK_LOCAL double duk__floor(double x) {
  23993. return DUK_FLOOR(x);
  23994. }
  23995. DUK_LOCAL double duk__log(double x) {
  23996. return DUK_LOG(x);
  23997. }
  23998. DUK_LOCAL double duk__sin(double x) {
  23999. return DUK_SIN(x);
  24000. }
  24001. DUK_LOCAL double duk__sqrt(double x) {
  24002. return DUK_SQRT(x);
  24003. }
  24004. DUK_LOCAL double duk__tan(double x) {
  24005. return DUK_TAN(x);
  24006. }
  24007. DUK_LOCAL double duk__atan2(double x, double y) {
  24008. return DUK_ATAN2(x, y);
  24009. }
  24010. #endif /* DUK_USE_AVOID_PLATFORM_FUNCPTRS */
  24011. /* order must match constants in genbuiltins.py */
  24012. DUK_LOCAL const duk__one_arg_func duk__one_arg_funcs[] = {
  24013. #if defined(DUK_USE_AVOID_PLATFORM_FUNCPTRS)
  24014. duk__fabs,
  24015. duk__acos,
  24016. duk__asin,
  24017. duk__atan,
  24018. duk__ceil,
  24019. duk__cos,
  24020. duk__exp,
  24021. duk__floor,
  24022. duk__log,
  24023. duk__round_fixed,
  24024. duk__sin,
  24025. duk__sqrt,
  24026. duk__tan
  24027. #else
  24028. DUK_FABS,
  24029. DUK_ACOS,
  24030. DUK_ASIN,
  24031. DUK_ATAN,
  24032. DUK_CEIL,
  24033. DUK_COS,
  24034. DUK_EXP,
  24035. DUK_FLOOR,
  24036. DUK_LOG,
  24037. duk__round_fixed,
  24038. DUK_SIN,
  24039. DUK_SQRT,
  24040. DUK_TAN
  24041. #endif
  24042. };
  24043. /* order must match constants in genbuiltins.py */
  24044. DUK_LOCAL const duk__two_arg_func duk__two_arg_funcs[] = {
  24045. #if defined(DUK_USE_AVOID_PLATFORM_FUNCPTRS)
  24046. duk__atan2,
  24047. duk__pow_fixed
  24048. #else
  24049. DUK_ATAN2,
  24050. duk__pow_fixed
  24051. #endif
  24052. };
  24053. DUK_INTERNAL duk_ret_t duk_bi_math_object_onearg_shared(duk_context *ctx) {
  24054. duk_small_int_t fun_idx = duk_get_current_magic(ctx);
  24055. duk__one_arg_func fun;
  24056. DUK_ASSERT(fun_idx >= 0);
  24057. DUK_ASSERT(fun_idx < (duk_small_int_t) (sizeof(duk__one_arg_funcs) / sizeof(duk__one_arg_func)));
  24058. fun = duk__one_arg_funcs[fun_idx];
  24059. duk_push_number(ctx, (duk_double_t) fun((double) duk_to_number(ctx, 0)));
  24060. return 1;
  24061. }
  24062. DUK_INTERNAL duk_ret_t duk_bi_math_object_twoarg_shared(duk_context *ctx) {
  24063. duk_small_int_t fun_idx = duk_get_current_magic(ctx);
  24064. duk__two_arg_func fun;
  24065. DUK_ASSERT(fun_idx >= 0);
  24066. DUK_ASSERT(fun_idx < (duk_small_int_t) (sizeof(duk__two_arg_funcs) / sizeof(duk__two_arg_func)));
  24067. fun = duk__two_arg_funcs[fun_idx];
  24068. duk_push_number(ctx, (duk_double_t) fun((double) duk_to_number(ctx, 0), (double) duk_to_number(ctx, 1)));
  24069. return 1;
  24070. }
  24071. DUK_INTERNAL duk_ret_t duk_bi_math_object_max(duk_context *ctx) {
  24072. return duk__math_minmax(ctx, -DUK_DOUBLE_INFINITY, duk__fmax_fixed);
  24073. }
  24074. DUK_INTERNAL duk_ret_t duk_bi_math_object_min(duk_context *ctx) {
  24075. return duk__math_minmax(ctx, DUK_DOUBLE_INFINITY, duk__fmin_fixed);
  24076. }
  24077. DUK_INTERNAL duk_ret_t duk_bi_math_object_random(duk_context *ctx) {
  24078. duk_push_number(ctx, (duk_double_t) duk_util_tinyrandom_get_double((duk_hthread *) ctx));
  24079. return 1;
  24080. }
  24081. #else /* DUK_USE_MATH_BUILTIN */
  24082. /* A stubbed built-in is useful for e.g. compilation torture testing with BCC. */
  24083. DUK_INTERNAL duk_ret_t duk_bi_math_object_onearg_shared(duk_context *ctx) {
  24084. DUK_UNREF(ctx);
  24085. return DUK_RET_UNIMPLEMENTED_ERROR;
  24086. }
  24087. DUK_INTERNAL duk_ret_t duk_bi_math_object_twoarg_shared(duk_context *ctx) {
  24088. DUK_UNREF(ctx);
  24089. return DUK_RET_UNIMPLEMENTED_ERROR;
  24090. }
  24091. DUK_INTERNAL duk_ret_t duk_bi_math_object_max(duk_context *ctx) {
  24092. DUK_UNREF(ctx);
  24093. return DUK_RET_UNIMPLEMENTED_ERROR;
  24094. }
  24095. DUK_INTERNAL duk_ret_t duk_bi_math_object_min(duk_context *ctx) {
  24096. DUK_UNREF(ctx);
  24097. return DUK_RET_UNIMPLEMENTED_ERROR;
  24098. }
  24099. DUK_INTERNAL duk_ret_t duk_bi_math_object_random(duk_context *ctx) {
  24100. DUK_UNREF(ctx);
  24101. return DUK_RET_UNIMPLEMENTED_ERROR;
  24102. }
  24103. #endif /* DUK_USE_MATH_BUILTIN */
  24104. #line 1 "duk_bi_number.c"
  24105. /*
  24106. * Number built-ins
  24107. */
  24108. /* include removed: duk_internal.h */
  24109. DUK_LOCAL duk_double_t duk__push_this_number_plain(duk_context *ctx) {
  24110. duk_hobject *h;
  24111. /* Number built-in accepts a plain number or a Number object (whose
  24112. * internal value is operated on). Other types cause TypeError.
  24113. */
  24114. duk_push_this(ctx);
  24115. if (duk_is_number(ctx, -1)) {
  24116. DUK_DDD(DUK_DDDPRINT("plain number value: %!T", (duk_tval *) duk_get_tval(ctx, -1)));
  24117. goto done;
  24118. }
  24119. h = duk_get_hobject(ctx, -1);
  24120. if (!h ||
  24121. (DUK_HOBJECT_GET_CLASS_NUMBER(h) != DUK_HOBJECT_CLASS_NUMBER)) {
  24122. DUK_DDD(DUK_DDDPRINT("unacceptable this value: %!T", (duk_tval *) duk_get_tval(ctx, -1)));
  24123. DUK_ERROR((duk_hthread *) ctx, DUK_ERR_TYPE_ERROR, "expected a number");
  24124. }
  24125. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE);
  24126. DUK_ASSERT(duk_is_number(ctx, -1));
  24127. DUK_DDD(DUK_DDDPRINT("number object: %!T, internal value: %!T",
  24128. (duk_tval *) duk_get_tval(ctx, -2), (duk_tval *) duk_get_tval(ctx, -1)));
  24129. duk_remove(ctx, -2);
  24130. done:
  24131. return duk_get_number(ctx, -1);
  24132. }
  24133. DUK_INTERNAL duk_ret_t duk_bi_number_constructor(duk_context *ctx) {
  24134. duk_hthread *thr = (duk_hthread *) ctx;
  24135. duk_idx_t nargs;
  24136. duk_hobject *h_this;
  24137. DUK_UNREF(thr);
  24138. /*
  24139. * The Number constructor uses ToNumber(arg) for number coercion
  24140. * (coercing an undefined argument to NaN). However, if the
  24141. * argument is not given at all, +0 must be used instead. To do
  24142. * this, a vararg function is used.
  24143. */
  24144. nargs = duk_get_top(ctx);
  24145. if (nargs == 0) {
  24146. duk_push_int(ctx, 0);
  24147. }
  24148. duk_to_number(ctx, 0);
  24149. duk_set_top(ctx, 1);
  24150. DUK_ASSERT_TOP(ctx, 1);
  24151. if (!duk_is_constructor_call(ctx)) {
  24152. return 1;
  24153. }
  24154. /*
  24155. * E5 Section 15.7.2.1 requires that the constructed object
  24156. * must have the original Number.prototype as its internal
  24157. * prototype. However, since Number.prototype is non-writable
  24158. * and non-configurable, this doesn't have to be enforced here:
  24159. * The default object (bound to 'this') is OK, though we have
  24160. * to change its class.
  24161. *
  24162. * Internal value set to ToNumber(arg) or +0; if no arg given,
  24163. * ToNumber(undefined) = NaN, so special treatment is needed
  24164. * (above). String internal value is immutable.
  24165. */
  24166. /* XXX: helper */
  24167. duk_push_this(ctx);
  24168. h_this = duk_get_hobject(ctx, -1);
  24169. DUK_ASSERT(h_this != NULL);
  24170. DUK_HOBJECT_SET_CLASS_NUMBER(h_this, DUK_HOBJECT_CLASS_NUMBER);
  24171. DUK_ASSERT(DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h_this) == thr->builtins[DUK_BIDX_NUMBER_PROTOTYPE]);
  24172. DUK_ASSERT(DUK_HOBJECT_GET_CLASS_NUMBER(h_this) == DUK_HOBJECT_CLASS_NUMBER);
  24173. DUK_ASSERT(DUK_HOBJECT_HAS_EXTENSIBLE(h_this));
  24174. duk_dup(ctx, 0); /* -> [ val obj val ] */
  24175. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_NONE);
  24176. return 0; /* no return value -> don't replace created value */
  24177. }
  24178. DUK_INTERNAL duk_ret_t duk_bi_number_prototype_value_of(duk_context *ctx) {
  24179. (void) duk__push_this_number_plain(ctx);
  24180. return 1;
  24181. }
  24182. DUK_INTERNAL duk_ret_t duk_bi_number_prototype_to_string(duk_context *ctx) {
  24183. duk_small_int_t radix;
  24184. duk_small_uint_t n2s_flags;
  24185. (void) duk__push_this_number_plain(ctx);
  24186. if (duk_is_undefined(ctx, 0)) {
  24187. radix = 10;
  24188. } else {
  24189. radix = (duk_small_int_t) duk_to_int_check_range(ctx, 0, 2, 36);
  24190. }
  24191. DUK_DDD(DUK_DDDPRINT("radix=%ld", (long) radix));
  24192. n2s_flags = 0;
  24193. duk_numconv_stringify(ctx,
  24194. radix /*radix*/,
  24195. 0 /*digits*/,
  24196. n2s_flags /*flags*/);
  24197. return 1;
  24198. }
  24199. DUK_INTERNAL duk_ret_t duk_bi_number_prototype_to_locale_string(duk_context *ctx) {
  24200. /* XXX: just use toString() for now; permitted although not recommended.
  24201. * nargs==1, so radix is passed to toString().
  24202. */
  24203. return duk_bi_number_prototype_to_string(ctx);
  24204. }
  24205. /*
  24206. * toFixed(), toExponential(), toPrecision()
  24207. */
  24208. /* XXX: shared helper for toFixed(), toExponential(), toPrecision()? */
  24209. DUK_INTERNAL duk_ret_t duk_bi_number_prototype_to_fixed(duk_context *ctx) {
  24210. duk_small_int_t frac_digits;
  24211. duk_double_t d;
  24212. duk_small_int_t c;
  24213. duk_small_uint_t n2s_flags;
  24214. frac_digits = (duk_small_int_t) duk_to_int_check_range(ctx, 0, 0, 20);
  24215. d = duk__push_this_number_plain(ctx);
  24216. c = (duk_small_int_t) DUK_FPCLASSIFY(d);
  24217. if (c == DUK_FP_NAN || c == DUK_FP_INFINITE) {
  24218. goto use_to_string;
  24219. }
  24220. if (d >= 1.0e21 || d <= -1.0e21) {
  24221. goto use_to_string;
  24222. }
  24223. n2s_flags = DUK_N2S_FLAG_FIXED_FORMAT |
  24224. DUK_N2S_FLAG_FRACTION_DIGITS;
  24225. duk_numconv_stringify(ctx,
  24226. 10 /*radix*/,
  24227. frac_digits /*digits*/,
  24228. n2s_flags /*flags*/);
  24229. return 1;
  24230. use_to_string:
  24231. DUK_ASSERT_TOP(ctx, 2);
  24232. duk_to_string(ctx, -1);
  24233. return 1;
  24234. }
  24235. DUK_INTERNAL duk_ret_t duk_bi_number_prototype_to_exponential(duk_context *ctx) {
  24236. duk_bool_t frac_undefined;
  24237. duk_small_int_t frac_digits;
  24238. duk_double_t d;
  24239. duk_small_int_t c;
  24240. duk_small_uint_t n2s_flags;
  24241. d = duk__push_this_number_plain(ctx);
  24242. frac_undefined = duk_is_undefined(ctx, 0);
  24243. duk_to_int(ctx, 0); /* for side effects */
  24244. c = (duk_small_int_t) DUK_FPCLASSIFY(d);
  24245. if (c == DUK_FP_NAN || c == DUK_FP_INFINITE) {
  24246. goto use_to_string;
  24247. }
  24248. frac_digits = (duk_small_int_t) duk_to_int_check_range(ctx, 0, 0, 20);
  24249. n2s_flags = DUK_N2S_FLAG_FORCE_EXP |
  24250. (frac_undefined ? 0 : DUK_N2S_FLAG_FIXED_FORMAT);
  24251. duk_numconv_stringify(ctx,
  24252. 10 /*radix*/,
  24253. frac_digits + 1 /*leading digit + fractions*/,
  24254. n2s_flags /*flags*/);
  24255. return 1;
  24256. use_to_string:
  24257. DUK_ASSERT_TOP(ctx, 2);
  24258. duk_to_string(ctx, -1);
  24259. return 1;
  24260. }
  24261. DUK_INTERNAL duk_ret_t duk_bi_number_prototype_to_precision(duk_context *ctx) {
  24262. /* The specification has quite awkward order of coercion and
  24263. * checks for toPrecision(). The operations below are a bit
  24264. * reordered, within constraints of observable side effects.
  24265. */
  24266. duk_double_t d;
  24267. duk_small_int_t prec;
  24268. duk_small_int_t c;
  24269. duk_small_uint_t n2s_flags;
  24270. DUK_ASSERT_TOP(ctx, 1);
  24271. d = duk__push_this_number_plain(ctx);
  24272. if (duk_is_undefined(ctx, 0)) {
  24273. goto use_to_string;
  24274. }
  24275. DUK_ASSERT_TOP(ctx, 2);
  24276. duk_to_int(ctx, 0); /* for side effects */
  24277. c = (duk_small_int_t) DUK_FPCLASSIFY(d);
  24278. if (c == DUK_FP_NAN || c == DUK_FP_INFINITE) {
  24279. goto use_to_string;
  24280. }
  24281. prec = (duk_small_int_t) duk_to_int_check_range(ctx, 0, 1, 21);
  24282. n2s_flags = DUK_N2S_FLAG_FIXED_FORMAT |
  24283. DUK_N2S_FLAG_NO_ZERO_PAD;
  24284. duk_numconv_stringify(ctx,
  24285. 10 /*radix*/,
  24286. prec /*digits*/,
  24287. n2s_flags /*flags*/);
  24288. return 1;
  24289. use_to_string:
  24290. /* Used when precision is undefined; also used for NaN (-> "NaN"),
  24291. * and +/- infinity (-> "Infinity", "-Infinity").
  24292. */
  24293. DUK_ASSERT_TOP(ctx, 2);
  24294. duk_to_string(ctx, -1);
  24295. return 1;
  24296. }
  24297. #line 1 "duk_bi_object.c"
  24298. /*
  24299. * Object built-ins
  24300. */
  24301. /* include removed: duk_internal.h */
  24302. DUK_INTERNAL duk_ret_t duk_bi_object_constructor(duk_context *ctx) {
  24303. if (!duk_is_constructor_call(ctx) &&
  24304. !duk_is_null_or_undefined(ctx, 0)) {
  24305. duk_to_object(ctx, 0);
  24306. return 1;
  24307. }
  24308. if (duk_is_object(ctx, 0)) {
  24309. return 1;
  24310. }
  24311. /* Pointer and buffer primitive values are treated like other
  24312. * primitives values which have a fully fledged object counterpart:
  24313. * promote to an object value. Lightfuncs are coerced with
  24314. * ToObject() even they could also be returned as is.
  24315. */
  24316. if (duk_check_type_mask(ctx, 0, DUK_TYPE_MASK_STRING |
  24317. DUK_TYPE_MASK_BOOLEAN |
  24318. DUK_TYPE_MASK_NUMBER |
  24319. DUK_TYPE_MASK_POINTER |
  24320. DUK_TYPE_MASK_BUFFER |
  24321. DUK_TYPE_MASK_LIGHTFUNC)) {
  24322. duk_to_object(ctx, 0);
  24323. return 1;
  24324. }
  24325. duk_push_object_helper(ctx,
  24326. DUK_HOBJECT_FLAG_EXTENSIBLE |
  24327. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT),
  24328. DUK_BIDX_OBJECT_PROTOTYPE);
  24329. return 1;
  24330. }
  24331. /* Shared helper to implement Object.getPrototypeOf and the ES6
  24332. * Object.prototype.__proto__ getter.
  24333. *
  24334. * https://people.mozilla.org/~jorendorff/es6-draft.html#sec-get-object.prototype.__proto__
  24335. */
  24336. DUK_INTERNAL duk_ret_t duk_bi_object_getprototype_shared(duk_context *ctx) {
  24337. duk_hthread *thr = (duk_hthread *) ctx;
  24338. duk_hobject *h;
  24339. duk_hobject *proto;
  24340. DUK_UNREF(thr);
  24341. /* magic: 0=getter call, 1=Object.getPrototypeOf */
  24342. if (duk_get_current_magic(ctx) == 0) {
  24343. duk_push_this_coercible_to_object(ctx);
  24344. duk_insert(ctx, 0);
  24345. }
  24346. h = duk_require_hobject_or_lfunc(ctx, 0);
  24347. /* h is NULL for lightfunc */
  24348. /* XXX: should the API call handle this directly, i.e. attempt
  24349. * to duk_push_hobject(ctx, null) would push a null instead?
  24350. * (On the other hand 'undefined' would be just as logical, but
  24351. * not wanted here.)
  24352. */
  24353. if (h == NULL) {
  24354. duk_push_hobject_bidx(ctx, DUK_BIDX_FUNCTION_PROTOTYPE);
  24355. } else {
  24356. proto = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h);
  24357. if (proto) {
  24358. duk_push_hobject(ctx, proto);
  24359. } else {
  24360. duk_push_null(ctx);
  24361. }
  24362. }
  24363. return 1;
  24364. }
  24365. /* Shared helper to implement ES6 Object.setPrototypeOf and
  24366. * Object.prototype.__proto__ setter.
  24367. *
  24368. * https://people.mozilla.org/~jorendorff/es6-draft.html#sec-get-object.prototype.__proto__
  24369. * https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.setprototypeof
  24370. */
  24371. DUK_INTERNAL duk_ret_t duk_bi_object_setprototype_shared(duk_context *ctx) {
  24372. duk_hthread *thr = (duk_hthread *) ctx;
  24373. duk_hobject *h_obj;
  24374. duk_hobject *h_new_proto;
  24375. duk_hobject *h_curr;
  24376. duk_ret_t ret_success = 1; /* retval for success path */
  24377. /* Preliminaries for __proto__ and setPrototypeOf (E6 19.1.2.18 steps 1-4);
  24378. * magic: 0=setter call, 1=Object.setPrototypeOf
  24379. */
  24380. if (duk_get_current_magic(ctx) == 0) {
  24381. duk_push_this_check_object_coercible(ctx);
  24382. duk_insert(ctx, 0);
  24383. if (!duk_check_type_mask(ctx, 1, DUK_TYPE_MASK_NULL | DUK_TYPE_MASK_OBJECT)) {
  24384. return 0;
  24385. }
  24386. /* __proto__ setter returns 'undefined' on success unlike the
  24387. * setPrototypeOf() call which returns the target object.
  24388. */
  24389. ret_success = 0;
  24390. } else {
  24391. duk_require_object_coercible(ctx, 0);
  24392. duk_require_type_mask(ctx, 1, DUK_TYPE_MASK_NULL | DUK_TYPE_MASK_OBJECT);
  24393. }
  24394. h_new_proto = duk_get_hobject(ctx, 1);
  24395. /* h_new_proto may be NULL */
  24396. if (duk_is_lightfunc(ctx, 0)) {
  24397. if (h_new_proto == thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE]) {
  24398. goto skip;
  24399. }
  24400. goto fail_nonextensible;
  24401. }
  24402. h_obj = duk_get_hobject(ctx, 0);
  24403. if (!h_obj) {
  24404. goto skip;
  24405. }
  24406. DUK_ASSERT(h_obj != NULL);
  24407. /* [[SetPrototypeOf]] standard behavior, E6 9.1.2 */
  24408. /* NOTE: steps 7-8 seem to be a cut-paste bug in the E6 draft */
  24409. /* TODO: implement Proxy object support here */
  24410. if (h_new_proto == DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h_obj)) {
  24411. goto skip;
  24412. }
  24413. if (!DUK_HOBJECT_HAS_EXTENSIBLE(h_obj)) {
  24414. goto fail_nonextensible;
  24415. }
  24416. for (h_curr = h_new_proto; h_curr != NULL; h_curr = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h_curr)) {
  24417. /* Loop prevention */
  24418. if (h_curr == h_obj) {
  24419. goto fail_loop;
  24420. }
  24421. }
  24422. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, h_obj, h_new_proto);
  24423. /* fall thru */
  24424. skip:
  24425. duk_set_top(ctx, 1);
  24426. return ret_success;
  24427. fail_nonextensible:
  24428. fail_loop:
  24429. return DUK_RET_TYPE_ERROR;
  24430. }
  24431. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_get_own_property_descriptor(duk_context *ctx) {
  24432. /* XXX: no need for indirect call */
  24433. return duk_hobject_object_get_own_property_descriptor(ctx);
  24434. }
  24435. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_create(duk_context *ctx) {
  24436. duk_tval *tv;
  24437. duk_hobject *proto = NULL;
  24438. DUK_ASSERT_TOP(ctx, 2);
  24439. tv = duk_get_tval(ctx, 0);
  24440. DUK_ASSERT(tv != NULL);
  24441. if (DUK_TVAL_IS_NULL(tv)) {
  24442. ;
  24443. } else if (DUK_TVAL_IS_OBJECT(tv)) {
  24444. proto = DUK_TVAL_GET_OBJECT(tv);
  24445. DUK_ASSERT(proto != NULL);
  24446. } else {
  24447. return DUK_RET_TYPE_ERROR;
  24448. }
  24449. (void) duk_push_object_helper_proto(ctx,
  24450. DUK_HOBJECT_FLAG_EXTENSIBLE |
  24451. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT),
  24452. proto);
  24453. if (!duk_is_undefined(ctx, 1)) {
  24454. /* [ O Properties obj ] */
  24455. duk_replace(ctx, 0);
  24456. /* [ obj Properties ] */
  24457. /* Just call the "original" Object.defineProperties() to
  24458. * finish up.
  24459. */
  24460. return duk_bi_object_constructor_define_properties(ctx);
  24461. }
  24462. /* [ O Properties obj ] */
  24463. return 1;
  24464. }
  24465. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_define_property(duk_context *ctx) {
  24466. duk_hobject *obj;
  24467. duk_hstring *key;
  24468. duk_hobject *get;
  24469. duk_hobject *set;
  24470. duk_idx_t idx_value;
  24471. duk_uint_t defprop_flags;
  24472. DUK_ASSERT(ctx != NULL);
  24473. DUK_DDD(DUK_DDDPRINT("Object.defineProperty(): ctx=%p obj=%!T key=%!T desc=%!T",
  24474. (void *) ctx,
  24475. (duk_tval *) duk_get_tval(ctx, 0),
  24476. (duk_tval *) duk_get_tval(ctx, 1),
  24477. (duk_tval *) duk_get_tval(ctx, 2)));
  24478. /* [ obj key desc ] */
  24479. /* Lightfuncs are currently supported by coercing to a temporary
  24480. * Function object; changes will be allowed (the coerced value is
  24481. * extensible) but will be lost.
  24482. */
  24483. obj = duk_require_hobject_or_lfunc_coerce(ctx, 0);
  24484. (void) duk_to_string(ctx, 1);
  24485. key = duk_require_hstring(ctx, 1);
  24486. (void) duk_require_hobject(ctx, 2);
  24487. DUK_ASSERT(obj != NULL);
  24488. DUK_ASSERT(key != NULL);
  24489. DUK_ASSERT(duk_get_hobject(ctx, 2) != NULL);
  24490. /*
  24491. * Validate and convert argument property descriptor (an Ecmascript
  24492. * object) into a set of defprop_flags and possibly property value,
  24493. * getter, and/or setter values on the value stack.
  24494. *
  24495. * Lightfunc set/get values are coerced to full Functions.
  24496. */
  24497. duk_hobject_prepare_property_descriptor(ctx,
  24498. 2 /*idx_desc*/,
  24499. &defprop_flags,
  24500. &idx_value,
  24501. &get,
  24502. &set);
  24503. /*
  24504. * Use Object.defineProperty() helper for the actual operation.
  24505. */
  24506. duk_hobject_define_property_helper(ctx,
  24507. defprop_flags,
  24508. obj,
  24509. key,
  24510. idx_value,
  24511. get,
  24512. set);
  24513. /* Ignore the normalize/validate helper outputs on the value stack,
  24514. * they're popped automatically.
  24515. */
  24516. /*
  24517. * Return target object.
  24518. */
  24519. duk_push_hobject(ctx, obj);
  24520. return 1;
  24521. }
  24522. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_define_properties(duk_context *ctx) {
  24523. duk_small_uint_t pass;
  24524. duk_uint_t defprop_flags;
  24525. duk_hobject *obj;
  24526. duk_idx_t idx_value;
  24527. duk_hobject *get;
  24528. duk_hobject *set;
  24529. /* Lightfunc handling by ToObject() coercion. */
  24530. obj = duk_require_hobject_or_lfunc_coerce(ctx, 0); /* target */
  24531. DUK_ASSERT(obj != NULL);
  24532. duk_to_object(ctx, 1); /* properties object */
  24533. DUK_DDD(DUK_DDDPRINT("target=%!iT, properties=%!iT",
  24534. (duk_tval *) duk_get_tval(ctx, 0),
  24535. (duk_tval *) duk_get_tval(ctx, 1)));
  24536. /*
  24537. * Two pass approach to processing the property descriptors.
  24538. * On first pass validate and normalize all descriptors before
  24539. * any changes are made to the target object. On second pass
  24540. * make the actual modifications to the target object.
  24541. *
  24542. * Right now we'll just use the same normalize/validate helper
  24543. * on both passes, ignoring its outputs on the first pass.
  24544. */
  24545. for (pass = 0; pass < 2; pass++) {
  24546. duk_set_top(ctx, 2); /* -> [ hobject props ] */
  24547. duk_enum(ctx, 1, DUK_ENUM_OWN_PROPERTIES_ONLY /*enum_flags*/);
  24548. for (;;) {
  24549. duk_hstring *key;
  24550. /* [ hobject props enum(props) ] */
  24551. duk_set_top(ctx, 3);
  24552. if (!duk_next(ctx, 2, 1 /*get_value*/)) {
  24553. break;
  24554. }
  24555. DUK_DDD(DUK_DDDPRINT("-> key=%!iT, desc=%!iT",
  24556. (duk_tval *) duk_get_tval(ctx, -2),
  24557. (duk_tval *) duk_get_tval(ctx, -1)));
  24558. /* [ hobject props enum(props) key desc ] */
  24559. duk_hobject_prepare_property_descriptor(ctx,
  24560. 4 /*idx_desc*/,
  24561. &defprop_flags,
  24562. &idx_value,
  24563. &get,
  24564. &set);
  24565. /* [ hobject props enum(props) key desc value? getter? setter? ] */
  24566. if (pass == 0) {
  24567. continue;
  24568. }
  24569. key = duk_get_hstring(ctx, 3);
  24570. DUK_ASSERT(key != NULL);
  24571. duk_hobject_define_property_helper(ctx,
  24572. defprop_flags,
  24573. obj,
  24574. key,
  24575. idx_value,
  24576. get,
  24577. set);
  24578. }
  24579. }
  24580. /*
  24581. * Return target object
  24582. */
  24583. duk_dup(ctx, 0);
  24584. return 1;
  24585. }
  24586. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_seal_freeze_shared(duk_context *ctx) {
  24587. duk_hthread *thr = (duk_hthread *) ctx;
  24588. duk_hobject *h;
  24589. duk_bool_t is_freeze;
  24590. h = duk_require_hobject_or_lfunc(ctx, 0);
  24591. if (!h) {
  24592. /* Lightfunc, always success. */
  24593. return 1;
  24594. }
  24595. is_freeze = (duk_bool_t) duk_get_current_magic(ctx);
  24596. duk_hobject_object_seal_freeze_helper(thr, h, is_freeze);
  24597. /* Sealed and frozen objects cannot gain any more properties,
  24598. * so this is a good time to compact them.
  24599. */
  24600. duk_hobject_compact_props(thr, h);
  24601. return 1;
  24602. }
  24603. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_prevent_extensions(duk_context *ctx) {
  24604. duk_hthread *thr = (duk_hthread *) ctx;
  24605. duk_hobject *h;
  24606. h = duk_require_hobject_or_lfunc(ctx, 0);
  24607. if (!h) {
  24608. /* Lightfunc, always success. */
  24609. return 1;
  24610. }
  24611. DUK_ASSERT(h != NULL);
  24612. DUK_HOBJECT_CLEAR_EXTENSIBLE(h);
  24613. /* A non-extensible object cannot gain any more properties,
  24614. * so this is a good time to compact.
  24615. */
  24616. duk_hobject_compact_props(thr, h);
  24617. return 1;
  24618. }
  24619. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_is_sealed_frozen_shared(duk_context *ctx) {
  24620. duk_hobject *h;
  24621. duk_bool_t is_frozen;
  24622. duk_bool_t rc;
  24623. h = duk_require_hobject_or_lfunc(ctx, 0);
  24624. if (!h) {
  24625. duk_push_true(ctx); /* frozen and sealed */
  24626. } else {
  24627. is_frozen = duk_get_current_magic(ctx);
  24628. rc = duk_hobject_object_is_sealed_frozen_helper((duk_hthread *) ctx, h, is_frozen /*is_frozen*/);
  24629. duk_push_boolean(ctx, rc);
  24630. }
  24631. return 1;
  24632. }
  24633. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_is_extensible(duk_context *ctx) {
  24634. duk_hobject *h;
  24635. h = duk_require_hobject_or_lfunc(ctx, 0);
  24636. if (!h) {
  24637. duk_push_false(ctx);
  24638. } else {
  24639. duk_push_boolean(ctx, DUK_HOBJECT_HAS_EXTENSIBLE(h));
  24640. }
  24641. return 1;
  24642. }
  24643. /* Shared helper for Object.getOwnPropertyNames() and Object.keys().
  24644. * Magic: 0=getOwnPropertyNames, 1=Object.keys.
  24645. */
  24646. DUK_INTERNAL duk_ret_t duk_bi_object_constructor_keys_shared(duk_context *ctx) {
  24647. duk_hthread *thr = (duk_hthread *) ctx;
  24648. duk_hobject *obj;
  24649. #if defined(DUK_USE_ES6_PROXY)
  24650. duk_hobject *h_proxy_target;
  24651. duk_hobject *h_proxy_handler;
  24652. duk_hobject *h_trap_result;
  24653. duk_uarridx_t i, len, idx;
  24654. #endif
  24655. duk_small_uint_t enum_flags;
  24656. DUK_ASSERT_TOP(ctx, 1);
  24657. DUK_UNREF(thr);
  24658. obj = duk_require_hobject_or_lfunc_coerce(ctx, 0);
  24659. DUK_ASSERT(obj != NULL);
  24660. DUK_UNREF(obj);
  24661. #if defined(DUK_USE_ES6_PROXY)
  24662. if (DUK_LIKELY(!duk_hobject_proxy_check(thr,
  24663. obj,
  24664. &h_proxy_target,
  24665. &h_proxy_handler))) {
  24666. goto skip_proxy;
  24667. }
  24668. duk_push_hobject(ctx, h_proxy_handler);
  24669. if (!duk_get_prop_stridx(ctx, -1, DUK_STRIDX_OWN_KEYS)) {
  24670. /* Careful with reachability here: don't pop 'obj' before pushing
  24671. * proxy target.
  24672. */
  24673. DUK_DDD(DUK_DDDPRINT("no ownKeys trap, get keys of target instead"));
  24674. duk_pop_2(ctx);
  24675. duk_push_hobject(ctx, h_proxy_target);
  24676. duk_replace(ctx, 0);
  24677. DUK_ASSERT_TOP(ctx, 1);
  24678. goto skip_proxy;
  24679. }
  24680. /* [ obj handler trap ] */
  24681. duk_insert(ctx, -2);
  24682. duk_push_hobject(ctx, h_proxy_target); /* -> [ obj trap handler target ] */
  24683. duk_call_method(ctx, 1 /*nargs*/); /* -> [ obj trap_result ] */
  24684. h_trap_result = duk_require_hobject(ctx, -1);
  24685. DUK_UNREF(h_trap_result);
  24686. len = (duk_uarridx_t) duk_get_length(ctx, -1);
  24687. idx = 0;
  24688. duk_push_array(ctx);
  24689. for (i = 0; i < len; i++) {
  24690. /* [ obj trap_result res_arr ] */
  24691. if (duk_get_prop_index(ctx, -2, i) && duk_is_string(ctx, -1)) {
  24692. /* XXX: for Object.keys() we should check enumerability of key */
  24693. /* [ obj trap_result res_arr propname ] */
  24694. duk_put_prop_index(ctx, -2, idx);
  24695. idx++;
  24696. } else {
  24697. duk_pop(ctx);
  24698. }
  24699. }
  24700. /* XXX: for Object.keys() the [[OwnPropertyKeys]] result (trap result)
  24701. * should be filtered so that only enumerable keys remain. Enumerability
  24702. * should be checked with [[GetOwnProperty]] on the original object
  24703. * (i.e., the proxy in this case). If the proxy has a getOwnPropertyDescriptor
  24704. * trap, it should be triggered for every property. If the proxy doesn't have
  24705. * the trap, enumerability should be checked against the target object instead.
  24706. * We don't do any of this now, so Object.keys() and Object.getOwnPropertyNames()
  24707. * return the same result now for proxy traps. We still do clean up the trap
  24708. * result, so that Object.keys() and Object.getOwnPropertyNames() will return a
  24709. * clean array of strings without gaps.
  24710. */
  24711. return 1;
  24712. skip_proxy:
  24713. #endif /* DUK_USE_ES6_PROXY */
  24714. DUK_ASSERT_TOP(ctx, 1);
  24715. if (duk_get_current_magic(ctx)) {
  24716. /* Object.keys */
  24717. enum_flags = DUK_ENUM_OWN_PROPERTIES_ONLY |
  24718. DUK_ENUM_NO_PROXY_BEHAVIOR;
  24719. } else {
  24720. /* Object.getOwnPropertyNames */
  24721. enum_flags = DUK_ENUM_INCLUDE_NONENUMERABLE |
  24722. DUK_ENUM_OWN_PROPERTIES_ONLY |
  24723. DUK_ENUM_NO_PROXY_BEHAVIOR;
  24724. }
  24725. return duk_hobject_get_enumerated_keys(ctx, enum_flags);
  24726. }
  24727. DUK_INTERNAL duk_ret_t duk_bi_object_prototype_to_string(duk_context *ctx) {
  24728. duk_hthread *thr = (duk_hthread *) ctx;
  24729. duk_push_this(ctx);
  24730. duk_push_string(ctx, "[object ");
  24731. if (duk_is_undefined(ctx, -2)) {
  24732. duk_push_hstring_stridx(ctx, DUK_STRIDX_UC_UNDEFINED);
  24733. } else if (duk_is_null(ctx, -2)) {
  24734. duk_push_hstring_stridx(ctx, DUK_STRIDX_UC_NULL);
  24735. } else {
  24736. duk_hobject *h_this;
  24737. duk_hstring *h_classname;
  24738. duk_to_object(ctx, -2);
  24739. h_this = duk_get_hobject(ctx, -2);
  24740. DUK_ASSERT(h_this != NULL);
  24741. h_classname = DUK_HOBJECT_GET_CLASS_STRING(thr->heap, h_this);
  24742. DUK_ASSERT(h_classname != NULL);
  24743. duk_push_hstring(ctx, h_classname);
  24744. }
  24745. duk_push_string(ctx, "]");
  24746. duk_concat(ctx, 3);
  24747. return 1;
  24748. }
  24749. DUK_INTERNAL duk_ret_t duk_bi_object_prototype_to_locale_string(duk_context *ctx) {
  24750. DUK_ASSERT_TOP(ctx, 0);
  24751. (void) duk_push_this_coercible_to_object(ctx);
  24752. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_TO_STRING);
  24753. if (!duk_is_callable(ctx, 1)) {
  24754. return DUK_RET_TYPE_ERROR;
  24755. }
  24756. duk_dup(ctx, 0); /* -> [ O toString O ] */
  24757. duk_call_method(ctx, 0); /* XXX: call method tailcall? */
  24758. return 1;
  24759. }
  24760. DUK_INTERNAL duk_ret_t duk_bi_object_prototype_value_of(duk_context *ctx) {
  24761. (void) duk_push_this_coercible_to_object(ctx);
  24762. return 1;
  24763. }
  24764. DUK_INTERNAL duk_ret_t duk_bi_object_prototype_is_prototype_of(duk_context *ctx) {
  24765. duk_hthread *thr = (duk_hthread *) ctx;
  24766. duk_hobject *h_v;
  24767. duk_hobject *h_obj;
  24768. DUK_ASSERT_TOP(ctx, 1);
  24769. h_v = duk_get_hobject(ctx, 0);
  24770. if (!h_v) {
  24771. duk_push_false(ctx); /* XXX: tail call: return duk_push_false(ctx) */
  24772. return 1;
  24773. }
  24774. h_obj = duk_push_this_coercible_to_object(ctx);
  24775. DUK_ASSERT(h_obj != NULL);
  24776. /* E5.1 Section 15.2.4.6, step 3.a, lookup proto once before compare.
  24777. * Prototype loops should cause an error to be thrown.
  24778. */
  24779. duk_push_boolean(ctx, duk_hobject_prototype_chain_contains(thr, DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h_v), h_obj, 0 /*ignore_loop*/));
  24780. return 1;
  24781. }
  24782. DUK_INTERNAL duk_ret_t duk_bi_object_prototype_has_own_property(duk_context *ctx) {
  24783. return duk_hobject_object_ownprop_helper(ctx, 0 /*required_desc_flags*/);
  24784. }
  24785. DUK_INTERNAL duk_ret_t duk_bi_object_prototype_property_is_enumerable(duk_context *ctx) {
  24786. return duk_hobject_object_ownprop_helper(ctx, DUK_PROPDESC_FLAG_ENUMERABLE /*required_desc_flags*/);
  24787. }
  24788. #line 1 "duk_bi_pointer.c"
  24789. /*
  24790. * Pointer built-ins
  24791. */
  24792. /* include removed: duk_internal.h */
  24793. /*
  24794. * Constructor
  24795. */
  24796. DUK_INTERNAL duk_ret_t duk_bi_pointer_constructor(duk_context *ctx) {
  24797. /* XXX: this behavior is quite useless now; it would be nice to be able
  24798. * to create pointer values from e.g. numbers or strings. Numbers are
  24799. * problematic on 64-bit platforms though. Hex encoded strings?
  24800. */
  24801. if (duk_get_top(ctx) == 0) {
  24802. duk_push_pointer(ctx, NULL);
  24803. } else {
  24804. duk_to_pointer(ctx, 0);
  24805. }
  24806. DUK_ASSERT(duk_is_pointer(ctx, 0));
  24807. duk_set_top(ctx, 1);
  24808. if (duk_is_constructor_call(ctx)) {
  24809. duk_push_object_helper(ctx,
  24810. DUK_HOBJECT_FLAG_EXTENSIBLE |
  24811. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_POINTER),
  24812. DUK_BIDX_POINTER_PROTOTYPE);
  24813. /* Pointer object internal value is immutable */
  24814. duk_dup(ctx, 0);
  24815. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_NONE);
  24816. }
  24817. /* Note: unbalanced stack on purpose */
  24818. return 1;
  24819. }
  24820. /*
  24821. * toString(), valueOf()
  24822. */
  24823. DUK_INTERNAL duk_ret_t duk_bi_pointer_prototype_tostring_shared(duk_context *ctx) {
  24824. duk_tval *tv;
  24825. duk_small_int_t to_string = duk_get_current_magic(ctx);
  24826. duk_push_this(ctx);
  24827. tv = duk_require_tval(ctx, -1);
  24828. DUK_ASSERT(tv != NULL);
  24829. if (DUK_TVAL_IS_POINTER(tv)) {
  24830. /* nop */
  24831. } else if (DUK_TVAL_IS_OBJECT(tv)) {
  24832. duk_hobject *h = DUK_TVAL_GET_OBJECT(tv);
  24833. DUK_ASSERT(h != NULL);
  24834. /* Must be a "pointer object", i.e. class "Pointer" */
  24835. if (DUK_HOBJECT_GET_CLASS_NUMBER(h) != DUK_HOBJECT_CLASS_POINTER) {
  24836. goto type_error;
  24837. }
  24838. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE);
  24839. } else {
  24840. goto type_error;
  24841. }
  24842. if (to_string) {
  24843. duk_to_string(ctx, -1);
  24844. }
  24845. return 1;
  24846. type_error:
  24847. return DUK_RET_TYPE_ERROR;
  24848. }
  24849. #line 1 "duk_bi_proxy.c"
  24850. /*
  24851. * Proxy built-in (ES6 draft)
  24852. */
  24853. /* include removed: duk_internal.h */
  24854. #if defined(DUK_USE_ES6_PROXY)
  24855. DUK_INTERNAL duk_ret_t duk_bi_proxy_constructor(duk_context *ctx) {
  24856. duk_hobject *h_target;
  24857. duk_hobject *h_handler;
  24858. if (!duk_is_constructor_call(ctx)) {
  24859. return DUK_RET_TYPE_ERROR;
  24860. }
  24861. /* Reject a proxy object as the target because it would need
  24862. * special handler in property lookups. (ES6 has no such restriction)
  24863. */
  24864. h_target = duk_require_hobject_or_lfunc_coerce(ctx, 0);
  24865. DUK_ASSERT(h_target != NULL);
  24866. if (DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(h_target)) {
  24867. return DUK_RET_TYPE_ERROR;
  24868. }
  24869. /* Reject a proxy object as the handler because it would cause
  24870. * potentially unbounded recursion. (ES6 has no such restriction)
  24871. */
  24872. h_handler = duk_require_hobject_or_lfunc_coerce(ctx, 1);
  24873. DUK_ASSERT(h_handler != NULL);
  24874. if (DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(h_handler)) {
  24875. return DUK_RET_TYPE_ERROR;
  24876. }
  24877. /* XXX: the returned value is exotic in ES6 (draft), but we use a
  24878. * simple object here with no prototype. Without a prototype,
  24879. * [[DefaultValue]] coercion fails which is abit confusing.
  24880. * No callable check/handling in the current Proxy subset.
  24881. */
  24882. (void) duk_push_object_helper_proto(ctx,
  24883. DUK_HOBJECT_FLAG_EXTENSIBLE |
  24884. DUK_HOBJECT_FLAG_EXOTIC_PROXYOBJ |
  24885. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT),
  24886. NULL);
  24887. DUK_ASSERT_TOP(ctx, 3);
  24888. /* Proxy target */
  24889. duk_dup(ctx, 0);
  24890. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_TARGET, DUK_PROPDESC_FLAGS_WC);
  24891. /* Proxy handler */
  24892. duk_dup(ctx, 1);
  24893. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_HANDLER, DUK_PROPDESC_FLAGS_WC);
  24894. return 1; /* replacement handler */
  24895. }
  24896. #else /* DUK_USE_ES6_PROXY */
  24897. DUK_INTERNAL duk_ret_t duk_bi_proxy_constructor(duk_context *ctx) {
  24898. DUK_UNREF(ctx);
  24899. return DUK_RET_UNSUPPORTED_ERROR;
  24900. }
  24901. #endif /* DUK_USE_ES6_PROXY */
  24902. #line 1 "duk_bi_regexp.c"
  24903. /*
  24904. * RegExp built-ins
  24905. */
  24906. /* include removed: duk_internal.h */
  24907. #ifdef DUK_USE_REGEXP_SUPPORT
  24908. DUK_LOCAL void duk__get_this_regexp(duk_context *ctx) {
  24909. duk_hobject *h;
  24910. duk_push_this(ctx);
  24911. h = duk_require_hobject_with_class(ctx, -1, DUK_HOBJECT_CLASS_REGEXP);
  24912. DUK_ASSERT(h != NULL);
  24913. DUK_UNREF(h);
  24914. duk_insert(ctx, 0); /* prepend regexp to valstack 0 index */
  24915. }
  24916. /* XXX: much to improve (code size) */
  24917. DUK_INTERNAL duk_ret_t duk_bi_regexp_constructor(duk_context *ctx) {
  24918. duk_hthread *thr = (duk_hthread *) ctx;
  24919. duk_hobject *h_pattern;
  24920. DUK_ASSERT_TOP(ctx, 2);
  24921. h_pattern = duk_get_hobject(ctx, 0);
  24922. if (!duk_is_constructor_call(ctx) &&
  24923. h_pattern != NULL &&
  24924. DUK_HOBJECT_GET_CLASS_NUMBER(h_pattern) == DUK_HOBJECT_CLASS_REGEXP &&
  24925. duk_is_undefined(ctx, 1)) {
  24926. /* Called as a function, pattern has [[Class]] "RegExp" and
  24927. * flags is undefined -> return object as is.
  24928. */
  24929. duk_dup(ctx, 0);
  24930. return 1;
  24931. }
  24932. /* Else functionality is identical for function call and constructor
  24933. * call.
  24934. */
  24935. if (h_pattern != NULL &&
  24936. DUK_HOBJECT_GET_CLASS_NUMBER(h_pattern) == DUK_HOBJECT_CLASS_REGEXP) {
  24937. if (duk_is_undefined(ctx, 1)) {
  24938. duk_bool_t flag_g, flag_i, flag_m;
  24939. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_SOURCE);
  24940. flag_g = duk_get_prop_stridx_boolean(ctx, 0, DUK_STRIDX_GLOBAL, NULL);
  24941. flag_i = duk_get_prop_stridx_boolean(ctx, 0, DUK_STRIDX_IGNORE_CASE, NULL);
  24942. flag_m = duk_get_prop_stridx_boolean(ctx, 0, DUK_STRIDX_MULTILINE, NULL);
  24943. duk_push_sprintf(ctx, "%s%s%s",
  24944. (const char *) (flag_g ? "g" : ""),
  24945. (const char *) (flag_i ? "i" : ""),
  24946. (const char *) (flag_m ? "m" : ""));
  24947. /* [ ... pattern flags ] */
  24948. } else {
  24949. return DUK_RET_TYPE_ERROR;
  24950. }
  24951. } else {
  24952. if (duk_is_undefined(ctx, 0)) {
  24953. duk_push_string(ctx, "");
  24954. } else {
  24955. duk_dup(ctx, 0);
  24956. duk_to_string(ctx, -1);
  24957. }
  24958. if (duk_is_undefined(ctx, 1)) {
  24959. duk_push_string(ctx, "");
  24960. } else {
  24961. duk_dup(ctx, 1);
  24962. duk_to_string(ctx, -1);
  24963. }
  24964. /* [ ... pattern flags ] */
  24965. }
  24966. DUK_DDD(DUK_DDDPRINT("RegExp constructor/function call, pattern=%!T, flags=%!T",
  24967. (duk_tval *) duk_get_tval(ctx, -2), (duk_tval *) duk_get_tval(ctx, -1)));
  24968. /* [ ... pattern flags ] */
  24969. duk_regexp_compile(thr);
  24970. /* [ ... bytecode escaped_source ] */
  24971. duk_regexp_create_instance(thr);
  24972. /* [ ... RegExp ] */
  24973. return 1;
  24974. }
  24975. DUK_INTERNAL duk_ret_t duk_bi_regexp_prototype_exec(duk_context *ctx) {
  24976. duk__get_this_regexp(ctx);
  24977. /* [ regexp input ] */
  24978. duk_regexp_match((duk_hthread *) ctx);
  24979. /* [ result ] */
  24980. return 1;
  24981. }
  24982. DUK_INTERNAL duk_ret_t duk_bi_regexp_prototype_test(duk_context *ctx) {
  24983. duk__get_this_regexp(ctx);
  24984. /* [ regexp input ] */
  24985. /* result object is created and discarded; wasteful but saves code space */
  24986. duk_regexp_match((duk_hthread *) ctx);
  24987. /* [ result ] */
  24988. duk_push_boolean(ctx, (duk_is_null(ctx, -1) ? 0 : 1));
  24989. return 1;
  24990. }
  24991. DUK_INTERNAL duk_ret_t duk_bi_regexp_prototype_to_string(duk_context *ctx) {
  24992. duk_hstring *h_bc;
  24993. duk_small_int_t re_flags;
  24994. #if 0
  24995. /* A little tricky string approach to provide the flags string.
  24996. * This depends on the specific flag values in duk_regexp.h,
  24997. * which needs to be asserted for. In practice this doesn't
  24998. * produce more compact code than the easier approach in use.
  24999. */
  25000. const char *flag_strings = "gim\0gi\0gm\0g\0";
  25001. duk_uint8_t flag_offsets[8] = {
  25002. (duk_uint8_t) 3, /* flags: "" */
  25003. (duk_uint8_t) 10, /* flags: "g" */
  25004. (duk_uint8_t) 5, /* flags: "i" */
  25005. (duk_uint8_t) 4, /* flags: "gi" */
  25006. (duk_uint8_t) 2, /* flags: "m" */
  25007. (duk_uint8_t) 7, /* flags: "gm" */
  25008. (duk_uint8_t) 1, /* flags: "im" */
  25009. (duk_uint8_t) 0, /* flags: "gim" */
  25010. };
  25011. DUK_ASSERT(DUK_RE_FLAG_GLOBAL == 1);
  25012. DUK_ASSERT(DUK_RE_FLAG_IGNORE_CASE == 2);
  25013. DUK_ASSERT(DUK_RE_FLAG_MULTILINE == 4);
  25014. #endif
  25015. duk__get_this_regexp(ctx);
  25016. /* [ regexp ] */
  25017. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_SOURCE);
  25018. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_INT_BYTECODE);
  25019. h_bc = duk_get_hstring(ctx, -1);
  25020. DUK_ASSERT(h_bc != NULL);
  25021. DUK_ASSERT(DUK_HSTRING_GET_BYTELEN(h_bc) >= 1);
  25022. DUK_ASSERT(DUK_HSTRING_GET_CHARLEN(h_bc) >= 1);
  25023. DUK_ASSERT(DUK_HSTRING_GET_DATA(h_bc)[0] < 0x80);
  25024. re_flags = (duk_small_int_t) DUK_HSTRING_GET_DATA(h_bc)[0];
  25025. /* [ regexp source bytecode ] */
  25026. #if 1
  25027. /* This is a cleaner approach and also produces smaller code than
  25028. * the other alternative. Use duk_require_string() for format
  25029. * safety (although the source property should always exist).
  25030. */
  25031. duk_push_sprintf(ctx, "/%s/%s%s%s",
  25032. (const char *) duk_require_string(ctx, -2), /* require to be safe */
  25033. (re_flags & DUK_RE_FLAG_GLOBAL) ? "g" : "",
  25034. (re_flags & DUK_RE_FLAG_IGNORE_CASE) ? "i" : "",
  25035. (re_flags & DUK_RE_FLAG_MULTILINE) ? "m" : "");
  25036. #else
  25037. /* This should not be necessary because no-one should tamper with the
  25038. * regexp bytecode, but is prudent to avoid potential segfaults if that
  25039. * were to happen for some reason.
  25040. */
  25041. re_flags &= 0x07;
  25042. DUK_ASSERT(re_flags >= 0 && re_flags <= 7); /* three flags */
  25043. duk_push_sprintf(ctx, "/%s/%s",
  25044. (const char *) duk_require_string(ctx, -2),
  25045. (const char *) (flag_strings + flag_offsets[re_flags]));
  25046. #endif
  25047. return 1;
  25048. }
  25049. #else /* DUK_USE_REGEXP_SUPPORT */
  25050. DUK_INTERNAL duk_ret_t duk_bi_regexp_constructor(duk_context *ctx) {
  25051. DUK_UNREF(ctx);
  25052. return DUK_RET_UNSUPPORTED_ERROR;
  25053. }
  25054. DUK_INTERNAL duk_ret_t duk_bi_regexp_prototype_exec(duk_context *ctx) {
  25055. DUK_UNREF(ctx);
  25056. return DUK_RET_UNSUPPORTED_ERROR;
  25057. }
  25058. DUK_INTERNAL duk_ret_t duk_bi_regexp_prototype_test(duk_context *ctx) {
  25059. DUK_UNREF(ctx);
  25060. return DUK_RET_UNSUPPORTED_ERROR;
  25061. }
  25062. DUK_INTERNAL duk_ret_t duk_bi_regexp_prototype_to_string(duk_context *ctx) {
  25063. DUK_UNREF(ctx);
  25064. return DUK_RET_UNSUPPORTED_ERROR;
  25065. }
  25066. #endif /* DUK_USE_REGEXP_SUPPORT */
  25067. #line 1 "duk_bi_string.c"
  25068. /*
  25069. * String built-ins
  25070. */
  25071. /* XXX: There are several limitations in the current implementation for
  25072. * strings with >= 0x80000000UL characters. In some cases one would need
  25073. * to be able to represent the range [-0xffffffff,0xffffffff] and so on.
  25074. * Generally character and byte length are assumed to fit into signed 32
  25075. * bits (< 0x80000000UL). Places with issues are not marked explicitly
  25076. * below in all cases, look for signed type usage (duk_int_t etc) for
  25077. * offsets/lengths.
  25078. */
  25079. /* include removed: duk_internal.h */
  25080. /*
  25081. * Constructor
  25082. */
  25083. DUK_INTERNAL duk_ret_t duk_bi_string_constructor(duk_context *ctx) {
  25084. /* String constructor needs to distinguish between an argument not given at all
  25085. * vs. given as 'undefined'. We're a vararg function to handle this properly.
  25086. */
  25087. if (duk_get_top(ctx) == 0) {
  25088. duk_push_hstring_stridx(ctx, DUK_STRIDX_EMPTY_STRING);
  25089. } else {
  25090. duk_to_string(ctx, 0);
  25091. }
  25092. DUK_ASSERT(duk_is_string(ctx, 0));
  25093. duk_set_top(ctx, 1);
  25094. if (duk_is_constructor_call(ctx)) {
  25095. duk_push_object_helper(ctx,
  25096. DUK_HOBJECT_FLAG_EXTENSIBLE |
  25097. DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ |
  25098. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_STRING),
  25099. DUK_BIDX_STRING_PROTOTYPE);
  25100. /* String object internal value is immutable */
  25101. duk_dup(ctx, 0);
  25102. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VALUE, DUK_PROPDESC_FLAGS_NONE);
  25103. }
  25104. /* Note: unbalanced stack on purpose */
  25105. return 1;
  25106. }
  25107. DUK_INTERNAL duk_ret_t duk_bi_string_constructor_from_char_code(duk_context *ctx) {
  25108. duk_hthread *thr = (duk_hthread *) ctx;
  25109. duk_hbuffer_dynamic *h;
  25110. duk_idx_t i, n;
  25111. duk_ucodepoint_t cp;
  25112. /* XXX: It would be nice to build the string directly but ToUint16()
  25113. * coercion is needed so a generic helper would not be very
  25114. * helpful (perhaps coerce the value stack first here and then
  25115. * build a string from a duk_tval number sequence in one go?).
  25116. */
  25117. n = duk_get_top(ctx);
  25118. duk_push_dynamic_buffer(ctx, 0); /* XXX: initial spare size estimate from 'n' */
  25119. h = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  25120. for (i = 0; i < n; i++) {
  25121. #if defined(DUK_USE_NONSTD_STRING_FROMCHARCODE_32BIT)
  25122. /* ToUint16() coercion is mandatory in the E5.1 specification, but
  25123. * this non-compliant behavior makes more sense because we support
  25124. * non-BMP codepoints. Don't use CESU-8 because that'd create
  25125. * surrogate pairs.
  25126. */
  25127. cp = (duk_ucodepoint_t) duk_to_uint32(ctx, i);
  25128. duk_hbuffer_append_xutf8(thr, h, cp);
  25129. #else
  25130. cp = (duk_ucodepoint_t) duk_to_uint16(ctx, i);
  25131. duk_hbuffer_append_cesu8(thr, h, cp);
  25132. #endif
  25133. }
  25134. duk_to_string(ctx, -1);
  25135. return 1;
  25136. }
  25137. /*
  25138. * toString(), valueOf()
  25139. */
  25140. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_to_string(duk_context *ctx) {
  25141. duk_tval *tv;
  25142. duk_push_this(ctx);
  25143. tv = duk_require_tval(ctx, -1);
  25144. DUK_ASSERT(tv != NULL);
  25145. if (DUK_TVAL_IS_STRING(tv)) {
  25146. /* return as is */
  25147. return 1;
  25148. } else if (DUK_TVAL_IS_OBJECT(tv)) {
  25149. duk_hobject *h = DUK_TVAL_GET_OBJECT(tv);
  25150. DUK_ASSERT(h != NULL);
  25151. /* Must be a "string object", i.e. class "String" */
  25152. if (DUK_HOBJECT_GET_CLASS_NUMBER(h) != DUK_HOBJECT_CLASS_STRING) {
  25153. goto type_error;
  25154. }
  25155. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VALUE);
  25156. DUK_ASSERT(duk_is_string(ctx, -1));
  25157. return 1;
  25158. } else {
  25159. goto type_error;
  25160. }
  25161. /* never here, but fall through */
  25162. type_error:
  25163. return DUK_RET_TYPE_ERROR;
  25164. }
  25165. /*
  25166. * Character and charcode access
  25167. */
  25168. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_char_at(duk_context *ctx) {
  25169. duk_int_t pos;
  25170. /* XXX: faster implementation */
  25171. (void) duk_push_this_coercible_to_string(ctx);
  25172. pos = duk_to_int(ctx, 0);
  25173. duk_substring(ctx, -1, pos, pos + 1);
  25174. return 1;
  25175. }
  25176. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_char_code_at(duk_context *ctx) {
  25177. duk_hthread *thr = (duk_hthread *) ctx;
  25178. duk_int_t pos;
  25179. duk_hstring *h;
  25180. duk_bool_t clamped;
  25181. /* XXX: faster implementation */
  25182. DUK_DDD(DUK_DDDPRINT("arg=%!T", (duk_tval *) duk_get_tval(ctx, 0)));
  25183. h = duk_push_this_coercible_to_string(ctx);
  25184. DUK_ASSERT(h != NULL);
  25185. pos = duk_to_int_clamped_raw(ctx,
  25186. 0 /*index*/,
  25187. 0 /*min(incl)*/,
  25188. DUK_HSTRING_GET_CHARLEN(h) - 1 /*max(incl)*/,
  25189. &clamped /*out_clamped*/);
  25190. if (clamped) {
  25191. duk_push_number(ctx, DUK_DOUBLE_NAN);
  25192. return 1;
  25193. }
  25194. duk_push_u32(ctx, (duk_uint32_t) duk_hstring_char_code_at_raw(thr, h, pos));
  25195. return 1;
  25196. }
  25197. /*
  25198. * substring(), substr(), slice()
  25199. */
  25200. /* XXX: any chance of merging these three similar but still slightly
  25201. * different algorithms so that footprint would be reduced?
  25202. */
  25203. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_substring(duk_context *ctx) {
  25204. duk_hstring *h;
  25205. duk_int_t start_pos, end_pos;
  25206. duk_int_t len;
  25207. h = duk_push_this_coercible_to_string(ctx);
  25208. DUK_ASSERT(h != NULL);
  25209. len = (duk_int_t) DUK_HSTRING_GET_CHARLEN(h);
  25210. /* [ start end str ] */
  25211. start_pos = duk_to_int_clamped(ctx, 0, 0, len);
  25212. if (duk_is_undefined(ctx, 1)) {
  25213. end_pos = len;
  25214. } else {
  25215. end_pos = duk_to_int_clamped(ctx, 1, 0, len);
  25216. }
  25217. DUK_ASSERT(start_pos >= 0 && start_pos <= len);
  25218. DUK_ASSERT(end_pos >= 0 && end_pos <= len);
  25219. if (start_pos > end_pos) {
  25220. duk_int_t tmp = start_pos;
  25221. start_pos = end_pos;
  25222. end_pos = tmp;
  25223. }
  25224. DUK_ASSERT(end_pos >= start_pos);
  25225. duk_substring(ctx, -1, (duk_size_t) start_pos, (duk_size_t) end_pos);
  25226. return 1;
  25227. }
  25228. #ifdef DUK_USE_SECTION_B
  25229. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_substr(duk_context *ctx) {
  25230. duk_hstring *h;
  25231. duk_int_t start_pos, end_pos;
  25232. duk_int_t len;
  25233. /* Unlike non-obsolete String calls, substr() algorithm in E5.1
  25234. * specification will happily coerce undefined and null to strings
  25235. * ("undefined" and "null").
  25236. */
  25237. duk_push_this(ctx);
  25238. h = duk_to_hstring(ctx, -1);
  25239. DUK_ASSERT(h != NULL);
  25240. len = (duk_int_t) DUK_HSTRING_GET_CHARLEN(h);
  25241. /* [ start length str ] */
  25242. /* The implementation for computing of start_pos and end_pos differs
  25243. * from the standard algorithm, but is intended to result in the exactly
  25244. * same behavior. This is not always obvious.
  25245. */
  25246. /* combines steps 2 and 5; -len ensures max() not needed for step 5 */
  25247. start_pos = duk_to_int_clamped(ctx, 0, -len, len);
  25248. if (start_pos < 0) {
  25249. start_pos = len + start_pos;
  25250. }
  25251. DUK_ASSERT(start_pos >= 0 && start_pos <= len);
  25252. /* combines steps 3, 6; step 7 is not needed */
  25253. if (duk_is_undefined(ctx, 1)) {
  25254. end_pos = len;
  25255. } else {
  25256. DUK_ASSERT(start_pos <= len);
  25257. end_pos = start_pos + duk_to_int_clamped(ctx, 1, 0, len - start_pos);
  25258. }
  25259. DUK_ASSERT(start_pos >= 0 && start_pos <= len);
  25260. DUK_ASSERT(end_pos >= 0 && end_pos <= len);
  25261. DUK_ASSERT(end_pos >= start_pos);
  25262. duk_substring(ctx, -1, (duk_size_t) start_pos, (duk_size_t) end_pos);
  25263. return 1;
  25264. }
  25265. #else /* DUK_USE_SECTION_B */
  25266. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_substr(duk_context *ctx) {
  25267. DUK_UNREF(ctx);
  25268. return DUK_RET_UNSUPPORTED_ERROR;
  25269. }
  25270. #endif /* DUK_USE_SECTION_B */
  25271. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_slice(duk_context *ctx) {
  25272. duk_hstring *h;
  25273. duk_int_t start_pos, end_pos;
  25274. duk_int_t len;
  25275. h = duk_push_this_coercible_to_string(ctx);
  25276. DUK_ASSERT(h != NULL);
  25277. len = (duk_int_t) DUK_HSTRING_GET_CHARLEN(h);
  25278. /* [ start end str ] */
  25279. start_pos = duk_to_int_clamped(ctx, 0, -len, len);
  25280. if (start_pos < 0) {
  25281. start_pos = len + start_pos;
  25282. }
  25283. if (duk_is_undefined(ctx, 1)) {
  25284. end_pos = len;
  25285. } else {
  25286. end_pos = duk_to_int_clamped(ctx, 1, -len, len);
  25287. if (end_pos < 0) {
  25288. end_pos = len + end_pos;
  25289. }
  25290. }
  25291. DUK_ASSERT(start_pos >= 0 && start_pos <= len);
  25292. DUK_ASSERT(end_pos >= 0 && end_pos <= len);
  25293. if (end_pos < start_pos) {
  25294. end_pos = start_pos;
  25295. }
  25296. DUK_ASSERT(end_pos >= start_pos);
  25297. duk_substring(ctx, -1, (duk_size_t) start_pos, (duk_size_t) end_pos);
  25298. return 1;
  25299. }
  25300. /*
  25301. * Case conversion
  25302. */
  25303. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_caseconv_shared(duk_context *ctx) {
  25304. duk_hthread *thr = (duk_hthread *) ctx;
  25305. duk_small_int_t uppercase = duk_get_current_magic(ctx);
  25306. (void) duk_push_this_coercible_to_string(ctx);
  25307. duk_unicode_case_convert_string(thr, (duk_bool_t) uppercase);
  25308. return 1;
  25309. }
  25310. /*
  25311. * indexOf() and lastIndexOf()
  25312. */
  25313. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_indexof_shared(duk_context *ctx) {
  25314. duk_hthread *thr = (duk_hthread *) ctx;
  25315. duk_hstring *h_this;
  25316. duk_hstring *h_search;
  25317. duk_int_t clen_this;
  25318. duk_int_t cpos;
  25319. duk_int_t bpos;
  25320. const duk_uint8_t *p_start, *p_end, *p;
  25321. const duk_uint8_t *q_start;
  25322. duk_int_t q_blen;
  25323. duk_uint8_t firstbyte;
  25324. duk_uint8_t t;
  25325. duk_small_int_t is_lastindexof = duk_get_current_magic(ctx); /* 0=indexOf, 1=lastIndexOf */
  25326. h_this = duk_push_this_coercible_to_string(ctx);
  25327. DUK_ASSERT(h_this != NULL);
  25328. clen_this = (duk_int_t) DUK_HSTRING_GET_CHARLEN(h_this);
  25329. h_search = duk_to_hstring(ctx, 0);
  25330. DUK_ASSERT(h_search != NULL);
  25331. q_start = DUK_HSTRING_GET_DATA(h_search);
  25332. q_blen = (duk_int_t) DUK_HSTRING_GET_BYTELEN(h_search);
  25333. duk_to_number(ctx, 1);
  25334. if (duk_is_nan(ctx, 1) && is_lastindexof) {
  25335. /* indexOf: NaN should cause pos to be zero.
  25336. * lastIndexOf: NaN should cause pos to be +Infinity
  25337. * (and later be clamped to len).
  25338. */
  25339. cpos = clen_this;
  25340. } else {
  25341. cpos = duk_to_int_clamped(ctx, 1, 0, clen_this);
  25342. }
  25343. /* Empty searchstring always matches; cpos must be clamped here.
  25344. * (If q_blen were < 0 due to clamped coercion, it would also be
  25345. * caught here.)
  25346. */
  25347. if (q_blen <= 0) {
  25348. duk_push_int(ctx, cpos);
  25349. return 1;
  25350. }
  25351. DUK_ASSERT(q_blen > 0);
  25352. bpos = (duk_int_t) duk_heap_strcache_offset_char2byte(thr, h_this, (duk_uint32_t) cpos);
  25353. p_start = DUK_HSTRING_GET_DATA(h_this);
  25354. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_this);
  25355. p = p_start + bpos;
  25356. /* This loop is optimized for size. For speed, there should be
  25357. * two separate loops, and we should ensure that memcmp() can be
  25358. * used without an extra "will searchstring fit" check. Doing
  25359. * the preconditioning for 'p' and 'p_end' is easy but cpos
  25360. * must be updated if 'p' is wound back (backward scanning).
  25361. */
  25362. firstbyte = q_start[0]; /* leading byte of match string */
  25363. while (p <= p_end && p >= p_start) {
  25364. t = *p;
  25365. /* For Ecmascript strings, this check can only match for
  25366. * initial UTF-8 bytes (not continuation bytes). For other
  25367. * strings all bets are off.
  25368. */
  25369. if ((t == firstbyte) && ((duk_size_t) (p_end - p) >= (duk_size_t) q_blen)) {
  25370. DUK_ASSERT(q_blen > 0); /* no issues with memcmp() zero size, even if broken */
  25371. if (DUK_MEMCMP(p, q_start, (duk_size_t) q_blen) == 0) {
  25372. duk_push_int(ctx, cpos);
  25373. return 1;
  25374. }
  25375. }
  25376. /* track cpos while scanning */
  25377. if (is_lastindexof) {
  25378. /* when going backwards, we decrement cpos 'early';
  25379. * 'p' may point to a continuation byte of the char
  25380. * at offset 'cpos', but that's OK because we'll
  25381. * backtrack all the way to the initial byte.
  25382. */
  25383. if ((t & 0xc0) != 0x80) {
  25384. cpos--;
  25385. }
  25386. p--;
  25387. } else {
  25388. if ((t & 0xc0) != 0x80) {
  25389. cpos++;
  25390. }
  25391. p++;
  25392. }
  25393. }
  25394. /* Not found. Empty string case is handled specially above. */
  25395. duk_push_int(ctx, -1);
  25396. return 1;
  25397. }
  25398. /*
  25399. * replace()
  25400. */
  25401. /* XXX: the current implementation works but is quite clunky; it compiles
  25402. * to almost 1,4kB of x86 code so it needs to be simplified (better approach,
  25403. * shared helpers, etc). Some ideas for refactoring:
  25404. *
  25405. * - a primitive to convert a string into a regexp matcher (reduces matching
  25406. * code at the cost of making matching much slower)
  25407. * - use replace() as a basic helper for match() and split(), which are both
  25408. * much simpler
  25409. * - API call to get_prop and to_boolean
  25410. */
  25411. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_replace(duk_context *ctx) {
  25412. duk_hthread *thr = (duk_hthread *) ctx;
  25413. duk_hstring *h_input;
  25414. duk_hstring *h_match;
  25415. duk_hstring *h_search;
  25416. duk_hobject *h_re;
  25417. duk_hbuffer_dynamic *h_buf;
  25418. #ifdef DUK_USE_REGEXP_SUPPORT
  25419. duk_bool_t is_regexp;
  25420. duk_bool_t is_global;
  25421. #endif
  25422. duk_bool_t is_repl_func;
  25423. duk_uint32_t match_start_coff, match_start_boff;
  25424. #ifdef DUK_USE_REGEXP_SUPPORT
  25425. duk_int_t match_caps;
  25426. #endif
  25427. duk_uint32_t prev_match_end_boff;
  25428. const duk_uint8_t *r_start, *r_end, *r; /* repl string scan */
  25429. DUK_ASSERT_TOP(ctx, 2);
  25430. h_input = duk_push_this_coercible_to_string(ctx);
  25431. DUK_ASSERT(h_input != NULL);
  25432. duk_push_dynamic_buffer(ctx, 0);
  25433. h_buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  25434. DUK_ASSERT(h_buf != NULL);
  25435. DUK_ASSERT_TOP(ctx, 4);
  25436. /* stack[0] = search value
  25437. * stack[1] = replace value
  25438. * stack[2] = input string
  25439. * stack[3] = result buffer
  25440. */
  25441. h_re = duk_get_hobject_with_class(ctx, 0, DUK_HOBJECT_CLASS_REGEXP);
  25442. if (h_re) {
  25443. #ifdef DUK_USE_REGEXP_SUPPORT
  25444. is_regexp = 1;
  25445. is_global = duk_get_prop_stridx_boolean(ctx, 0, DUK_STRIDX_GLOBAL, NULL);
  25446. if (is_global) {
  25447. /* start match from beginning */
  25448. duk_push_int(ctx, 0);
  25449. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  25450. }
  25451. #else /* DUK_USE_REGEXP_SUPPORT */
  25452. return DUK_RET_UNSUPPORTED_ERROR;
  25453. #endif /* DUK_USE_REGEXP_SUPPORT */
  25454. } else {
  25455. duk_to_string(ctx, 0);
  25456. #ifdef DUK_USE_REGEXP_SUPPORT
  25457. is_regexp = 0;
  25458. is_global = 0;
  25459. #endif
  25460. }
  25461. if (duk_is_function(ctx, 1)) {
  25462. is_repl_func = 1;
  25463. r_start = NULL;
  25464. r_end = NULL;
  25465. } else {
  25466. duk_hstring *h_repl;
  25467. is_repl_func = 0;
  25468. h_repl = duk_to_hstring(ctx, 1);
  25469. DUK_ASSERT(h_repl != NULL);
  25470. r_start = DUK_HSTRING_GET_DATA(h_repl);
  25471. r_end = r_start + DUK_HSTRING_GET_BYTELEN(h_repl);
  25472. }
  25473. prev_match_end_boff = 0;
  25474. for (;;) {
  25475. /*
  25476. * If matching with a regexp:
  25477. * - non-global RegExp: lastIndex not touched on a match, zeroed
  25478. * on a non-match
  25479. * - global RegExp: on match, lastIndex will be updated by regexp
  25480. * executor to point to next char after the matching part (so that
  25481. * characters in the matching part are not matched again)
  25482. *
  25483. * If matching with a string:
  25484. * - always non-global match, find first occurrence
  25485. *
  25486. * We need:
  25487. * - The character offset of start-of-match for the replacer function
  25488. * - The byte offsets for start-of-match and end-of-match to implement
  25489. * the replacement values $&, $`, and $', and to copy non-matching
  25490. * input string portions (including header and trailer) verbatim.
  25491. *
  25492. * NOTE: the E5.1 specification is a bit vague how the RegExp should
  25493. * behave in the replacement process; e.g. is matching done first for
  25494. * all matches (in the global RegExp case) before any replacer calls
  25495. * are made? See: test-bi-string-proto-replace.js for discussion.
  25496. */
  25497. DUK_ASSERT_TOP(ctx, 4);
  25498. #ifdef DUK_USE_REGEXP_SUPPORT
  25499. if (is_regexp) {
  25500. duk_dup(ctx, 0);
  25501. duk_dup(ctx, 2);
  25502. duk_regexp_match(thr); /* [ ... regexp input ] -> [ res_obj ] */
  25503. if (!duk_is_object(ctx, -1)) {
  25504. duk_pop(ctx);
  25505. break;
  25506. }
  25507. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INDEX);
  25508. DUK_ASSERT(duk_is_number(ctx, -1));
  25509. match_start_coff = duk_get_int(ctx, -1);
  25510. duk_pop(ctx);
  25511. duk_get_prop_index(ctx, -1, 0);
  25512. DUK_ASSERT(duk_is_string(ctx, -1));
  25513. h_match = duk_get_hstring(ctx, -1);
  25514. DUK_ASSERT(h_match != NULL);
  25515. duk_pop(ctx); /* h_match is borrowed, remains reachable through match_obj */
  25516. if (DUK_HSTRING_GET_BYTELEN(h_match) == 0) {
  25517. /* This should be equivalent to match() algorithm step 8.f.iii.2:
  25518. * detect an empty match and allow it, but don't allow it twice.
  25519. */
  25520. duk_uint32_t last_index;
  25521. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  25522. last_index = (duk_uint32_t) duk_get_uint(ctx, -1);
  25523. DUK_DDD(DUK_DDDPRINT("empty match, bump lastIndex: %ld -> %ld",
  25524. (long) last_index, (long) (last_index + 1)));
  25525. duk_pop(ctx);
  25526. duk_push_int(ctx, last_index + 1);
  25527. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  25528. }
  25529. DUK_ASSERT(duk_get_length(ctx, -1) <= DUK_INT_MAX); /* string limits */
  25530. match_caps = (duk_int_t) duk_get_length(ctx, -1);
  25531. } else {
  25532. #else /* DUK_USE_REGEXP_SUPPORT */
  25533. { /* unconditionally */
  25534. #endif /* DUK_USE_REGEXP_SUPPORT */
  25535. const duk_uint8_t *p_start, *p_end, *p; /* input string scan */
  25536. const duk_uint8_t *q_start; /* match string */
  25537. duk_size_t q_blen;
  25538. #ifdef DUK_USE_REGEXP_SUPPORT
  25539. DUK_ASSERT(!is_global); /* single match always */
  25540. #endif
  25541. p_start = DUK_HSTRING_GET_DATA(h_input);
  25542. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_input);
  25543. p = p_start;
  25544. h_search = duk_get_hstring(ctx, 0);
  25545. DUK_ASSERT(h_search != NULL);
  25546. q_start = DUK_HSTRING_GET_DATA(h_search);
  25547. q_blen = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h_search);
  25548. p_end -= q_blen; /* ensure full memcmp() fits in while */
  25549. match_start_coff = 0;
  25550. while (p <= p_end) {
  25551. DUK_ASSERT(p + q_blen <= DUK_HSTRING_GET_DATA(h_input) + DUK_HSTRING_GET_BYTELEN(h_input));
  25552. if (DUK_MEMCMP((void *) p, (void *) q_start, (size_t) q_blen) == 0) {
  25553. duk_dup(ctx, 0);
  25554. h_match = duk_get_hstring(ctx, -1);
  25555. DUK_ASSERT(h_match != NULL);
  25556. #ifdef DUK_USE_REGEXP_SUPPORT
  25557. match_caps = 0;
  25558. #endif
  25559. goto found;
  25560. }
  25561. /* track utf-8 non-continuation bytes */
  25562. if ((p[0] & 0xc0) != 0x80) {
  25563. match_start_coff++;
  25564. }
  25565. p++;
  25566. }
  25567. /* not found */
  25568. break;
  25569. }
  25570. found:
  25571. /* stack[0] = search value
  25572. * stack[1] = replace value
  25573. * stack[2] = input string
  25574. * stack[3] = result buffer
  25575. * stack[4] = regexp match OR match string
  25576. */
  25577. match_start_boff = duk_heap_strcache_offset_char2byte(thr, h_input, match_start_coff);
  25578. duk_hbuffer_append_bytes(thr,
  25579. h_buf,
  25580. DUK_HSTRING_GET_DATA(h_input) + prev_match_end_boff,
  25581. (duk_size_t) (match_start_boff - prev_match_end_boff));
  25582. prev_match_end_boff = match_start_boff + DUK_HSTRING_GET_BYTELEN(h_match);
  25583. if (is_repl_func) {
  25584. duk_idx_t idx_args;
  25585. duk_hstring *h_repl;
  25586. /* regexp res_obj is at index 4 */
  25587. duk_dup(ctx, 1);
  25588. idx_args = duk_get_top(ctx);
  25589. #ifdef DUK_USE_REGEXP_SUPPORT
  25590. if (is_regexp) {
  25591. duk_int_t idx;
  25592. duk_require_stack(ctx, match_caps + 2);
  25593. for (idx = 0; idx < match_caps; idx++) {
  25594. /* match followed by capture(s) */
  25595. duk_get_prop_index(ctx, 4, idx);
  25596. }
  25597. } else {
  25598. #else /* DUK_USE_REGEXP_SUPPORT */
  25599. { /* unconditionally */
  25600. #endif /* DUK_USE_REGEXP_SUPPORT */
  25601. /* match == search string, by definition */
  25602. duk_dup(ctx, 0);
  25603. }
  25604. duk_push_int(ctx, match_start_coff);
  25605. duk_dup(ctx, 2);
  25606. /* [ ... replacer match [captures] match_char_offset input ] */
  25607. duk_call(ctx, duk_get_top(ctx) - idx_args);
  25608. h_repl = duk_to_hstring(ctx, -1); /* -> [ ... repl_value ] */
  25609. DUK_ASSERT(h_repl != NULL);
  25610. duk_hbuffer_append_hstring(thr, h_buf, h_repl);
  25611. duk_pop(ctx); /* repl_value */
  25612. } else {
  25613. r = r_start;
  25614. while (r < r_end) {
  25615. duk_int_t ch1;
  25616. duk_int_t ch2;
  25617. #ifdef DUK_USE_REGEXP_SUPPORT
  25618. duk_int_t ch3;
  25619. #endif
  25620. duk_size_t left;
  25621. ch1 = *r++;
  25622. if (ch1 != DUK_ASC_DOLLAR) {
  25623. goto repl_write;
  25624. }
  25625. left = r_end - r;
  25626. if (left <= 0) {
  25627. goto repl_write;
  25628. }
  25629. ch2 = r[0];
  25630. switch ((int) ch2) {
  25631. case DUK_ASC_DOLLAR: {
  25632. ch1 = (1 << 8) + DUK_ASC_DOLLAR;
  25633. goto repl_write;
  25634. }
  25635. case DUK_ASC_AMP: {
  25636. duk_hbuffer_append_hstring(thr, h_buf, h_match);
  25637. r++;
  25638. continue;
  25639. }
  25640. case DUK_ASC_GRAVE: {
  25641. duk_hbuffer_append_bytes(thr,
  25642. h_buf,
  25643. DUK_HSTRING_GET_DATA(h_input),
  25644. match_start_boff);
  25645. r++;
  25646. continue;
  25647. }
  25648. case DUK_ASC_SINGLEQUOTE: {
  25649. duk_uint32_t match_end_boff;
  25650. /* Use match charlen instead of bytelen, just in case the input and
  25651. * match codepoint encodings would have different lengths.
  25652. */
  25653. match_end_boff = duk_heap_strcache_offset_char2byte(thr,
  25654. h_input,
  25655. match_start_coff + DUK_HSTRING_GET_CHARLEN(h_match));
  25656. duk_hbuffer_append_bytes(thr,
  25657. h_buf,
  25658. DUK_HSTRING_GET_DATA(h_input) + match_end_boff,
  25659. DUK_HSTRING_GET_BYTELEN(h_input) - match_end_boff);
  25660. r++;
  25661. continue;
  25662. }
  25663. default: {
  25664. #ifdef DUK_USE_REGEXP_SUPPORT
  25665. duk_int_t capnum, captmp, capadv;
  25666. /* XXX: optional check, match_caps is zero if no regexp,
  25667. * so dollar will be interpreted literally anyway.
  25668. */
  25669. if (!is_regexp) {
  25670. goto repl_write;
  25671. }
  25672. if (!(ch2 >= DUK_ASC_0 && ch2 <= DUK_ASC_9)) {
  25673. goto repl_write;
  25674. }
  25675. capnum = ch2 - DUK_ASC_0;
  25676. capadv = 1;
  25677. if (left >= 2) {
  25678. ch3 = r[1];
  25679. if (ch3 >= DUK_ASC_0 && ch3 <= DUK_ASC_9) {
  25680. captmp = capnum * 10 + (ch3 - DUK_ASC_0);
  25681. if (captmp < match_caps) {
  25682. capnum = captmp;
  25683. capadv = 2;
  25684. }
  25685. }
  25686. }
  25687. if (capnum > 0 && capnum < match_caps) {
  25688. DUK_ASSERT(is_regexp != 0); /* match_caps == 0 without regexps */
  25689. /* regexp res_obj is at offset 4 */
  25690. duk_get_prop_index(ctx, 4, (duk_uarridx_t) capnum);
  25691. if (duk_is_string(ctx, -1)) {
  25692. DUK_ASSERT(duk_get_hstring(ctx, -1) != NULL);
  25693. duk_hbuffer_append_hstring(thr, h_buf, duk_get_hstring(ctx, -1));
  25694. } else {
  25695. /* undefined -> skip (replaced with empty) */
  25696. }
  25697. duk_pop(ctx);
  25698. r += capadv;
  25699. continue;
  25700. } else {
  25701. goto repl_write;
  25702. }
  25703. #else /* DUK_USE_REGEXP_SUPPORT */
  25704. goto repl_write; /* unconditionally */
  25705. #endif /* DUK_USE_REGEXP_SUPPORT */
  25706. } /* default case */
  25707. } /* switch (ch2) */
  25708. repl_write:
  25709. /* ch1 = (r_increment << 8) + byte */
  25710. duk_hbuffer_append_byte(thr, h_buf, (duk_uint8_t) (ch1 & 0xff));
  25711. r += ch1 >> 8;
  25712. } /* while repl */
  25713. } /* if (is_repl_func) */
  25714. duk_pop(ctx); /* pop regexp res_obj or match string */
  25715. #ifdef DUK_USE_REGEXP_SUPPORT
  25716. if (!is_global) {
  25717. #else
  25718. { /* unconditionally; is_global==0 */
  25719. #endif
  25720. break;
  25721. }
  25722. }
  25723. /* trailer */
  25724. duk_hbuffer_append_bytes(thr,
  25725. h_buf,
  25726. DUK_HSTRING_GET_DATA(h_input) + prev_match_end_boff,
  25727. (duk_size_t) (DUK_HSTRING_GET_BYTELEN(h_input) - prev_match_end_boff));
  25728. DUK_ASSERT_TOP(ctx, 4);
  25729. duk_to_string(ctx, -1);
  25730. return 1;
  25731. }
  25732. /*
  25733. * split()
  25734. */
  25735. /* XXX: very messy now, but works; clean up, remove unused variables (nomimally
  25736. * used so compiler doesn't complain).
  25737. */
  25738. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_split(duk_context *ctx) {
  25739. duk_hthread *thr = (duk_hthread *) ctx;
  25740. duk_hstring *h_input;
  25741. duk_hstring *h_sep;
  25742. duk_uint32_t limit;
  25743. duk_uint32_t arr_idx;
  25744. #ifdef DUK_USE_REGEXP_SUPPORT
  25745. duk_bool_t is_regexp;
  25746. #endif
  25747. duk_bool_t matched; /* set to 1 if any match exists (needed for empty input special case) */
  25748. duk_uint32_t prev_match_end_coff, prev_match_end_boff;
  25749. duk_uint32_t match_start_boff, match_start_coff;
  25750. duk_uint32_t match_end_boff, match_end_coff;
  25751. DUK_UNREF(thr);
  25752. h_input = duk_push_this_coercible_to_string(ctx);
  25753. DUK_ASSERT(h_input != NULL);
  25754. duk_push_array(ctx);
  25755. if (duk_is_undefined(ctx, 1)) {
  25756. limit = 0xffffffffUL;
  25757. } else {
  25758. limit = duk_to_uint32(ctx, 1);
  25759. }
  25760. if (limit == 0) {
  25761. return 1;
  25762. }
  25763. /* If the separator is a RegExp, make a "clone" of it. The specification
  25764. * algorithm calls [[Match]] directly for specific indices; we emulate this
  25765. * by tweaking lastIndex and using a "force global" variant of duk_regexp_match()
  25766. * which will use global-style matching even when the RegExp itself is non-global.
  25767. */
  25768. if (duk_is_undefined(ctx, 0)) {
  25769. /* The spec algorithm first does "R = ToString(separator)" before checking
  25770. * whether separator is undefined. Since this is side effect free, we can
  25771. * skip the ToString() here.
  25772. */
  25773. duk_dup(ctx, 2);
  25774. duk_put_prop_index(ctx, 3, 0);
  25775. return 1;
  25776. } else if (duk_get_hobject_with_class(ctx, 0, DUK_HOBJECT_CLASS_REGEXP) != NULL) {
  25777. #ifdef DUK_USE_REGEXP_SUPPORT
  25778. duk_push_hobject_bidx(ctx, DUK_BIDX_REGEXP_CONSTRUCTOR);
  25779. duk_dup(ctx, 0);
  25780. duk_new(ctx, 1); /* [ ... RegExp val ] -> [ ... res ] */
  25781. duk_replace(ctx, 0);
  25782. /* lastIndex is initialized to zero by new RegExp() */
  25783. is_regexp = 1;
  25784. #else
  25785. return DUK_RET_UNSUPPORTED_ERROR;
  25786. #endif
  25787. } else {
  25788. duk_to_string(ctx, 0);
  25789. #ifdef DUK_USE_REGEXP_SUPPORT
  25790. is_regexp = 0;
  25791. #endif
  25792. }
  25793. /* stack[0] = separator (string or regexp)
  25794. * stack[1] = limit
  25795. * stack[2] = input string
  25796. * stack[3] = result array
  25797. */
  25798. prev_match_end_boff = 0;
  25799. prev_match_end_coff = 0;
  25800. arr_idx = 0;
  25801. matched = 0;
  25802. for (;;) {
  25803. /*
  25804. * The specification uses RegExp [[Match]] to attempt match at specific
  25805. * offsets. We don't have such a primitive, so we use an actual RegExp
  25806. * and tweak lastIndex. Since the RegExp may be non-global, we use a
  25807. * special variant which forces global-like behavior for matching.
  25808. */
  25809. DUK_ASSERT_TOP(ctx, 4);
  25810. #ifdef DUK_USE_REGEXP_SUPPORT
  25811. if (is_regexp) {
  25812. duk_dup(ctx, 0);
  25813. duk_dup(ctx, 2);
  25814. duk_regexp_match_force_global(thr); /* [ ... regexp input ] -> [ res_obj ] */
  25815. if (!duk_is_object(ctx, -1)) {
  25816. duk_pop(ctx);
  25817. break;
  25818. }
  25819. matched = 1;
  25820. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INDEX);
  25821. DUK_ASSERT(duk_is_number(ctx, -1));
  25822. match_start_coff = duk_get_int(ctx, -1);
  25823. match_start_boff = duk_heap_strcache_offset_char2byte(thr, h_input, match_start_coff);
  25824. duk_pop(ctx);
  25825. if (match_start_coff == DUK_HSTRING_GET_CHARLEN(h_input)) {
  25826. /* don't allow an empty match at the end of the string */
  25827. duk_pop(ctx);
  25828. break;
  25829. }
  25830. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  25831. DUK_ASSERT(duk_is_number(ctx, -1));
  25832. match_end_coff = duk_get_int(ctx, -1);
  25833. match_end_boff = duk_heap_strcache_offset_char2byte(thr, h_input, match_end_coff);
  25834. duk_pop(ctx);
  25835. /* empty match -> bump and continue */
  25836. if (prev_match_end_boff == match_end_boff) {
  25837. duk_push_int(ctx, match_end_coff + 1);
  25838. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  25839. duk_pop(ctx);
  25840. continue;
  25841. }
  25842. } else {
  25843. #else /* DUK_USE_REGEXP_SUPPORT */
  25844. { /* unconditionally */
  25845. #endif /* DUK_USE_REGEXP_SUPPORT */
  25846. const duk_uint8_t *p_start, *p_end, *p; /* input string scan */
  25847. const duk_uint8_t *q_start; /* match string */
  25848. duk_size_t q_blen, q_clen;
  25849. p_start = DUK_HSTRING_GET_DATA(h_input);
  25850. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h_input);
  25851. p = p_start + prev_match_end_boff;
  25852. h_sep = duk_get_hstring(ctx, 0);
  25853. DUK_ASSERT(h_sep != NULL);
  25854. q_start = DUK_HSTRING_GET_DATA(h_sep);
  25855. q_blen = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h_sep);
  25856. q_clen = (duk_size_t) DUK_HSTRING_GET_CHARLEN(h_sep);
  25857. p_end -= q_blen; /* ensure full memcmp() fits in while */
  25858. match_start_coff = prev_match_end_coff;
  25859. if (q_blen == 0) {
  25860. /* Handle empty separator case: it will always match, and always
  25861. * triggers the check in step 13.c.iii initially. Note that we
  25862. * must skip to either end of string or start of first codepoint,
  25863. * skipping over any continuation bytes!
  25864. *
  25865. * Don't allow an empty string to match at the end of the input.
  25866. */
  25867. matched = 1; /* empty separator can always match */
  25868. match_start_coff++;
  25869. p++;
  25870. while (p < p_end) {
  25871. if ((p[0] & 0xc0) != 0x80) {
  25872. goto found;
  25873. }
  25874. p++;
  25875. }
  25876. goto not_found;
  25877. }
  25878. DUK_ASSERT(q_blen > 0 && q_clen > 0);
  25879. while (p <= p_end) {
  25880. DUK_ASSERT(p + q_blen <= DUK_HSTRING_GET_DATA(h_input) + DUK_HSTRING_GET_BYTELEN(h_input));
  25881. DUK_ASSERT(q_blen > 0); /* no issues with empty memcmp() */
  25882. if (DUK_MEMCMP((void *) p, (void *) q_start, (duk_size_t) q_blen) == 0) {
  25883. /* never an empty match, so step 13.c.iii can't be triggered */
  25884. goto found;
  25885. }
  25886. /* track utf-8 non-continuation bytes */
  25887. if ((p[0] & 0xc0) != 0x80) {
  25888. match_start_coff++;
  25889. }
  25890. p++;
  25891. }
  25892. not_found:
  25893. /* not found */
  25894. break;
  25895. found:
  25896. matched = 1;
  25897. match_start_boff = (duk_uint32_t) (p - p_start);
  25898. match_end_coff = (duk_uint32_t) (match_start_coff + q_clen); /* constrained by string length */
  25899. match_end_boff = (duk_uint32_t) (match_start_boff + q_blen); /* ditto */
  25900. /* empty match (may happen with empty separator) -> bump and continue */
  25901. if (prev_match_end_boff == match_end_boff) {
  25902. prev_match_end_boff++;
  25903. prev_match_end_coff++;
  25904. continue;
  25905. }
  25906. } /* if (is_regexp) */
  25907. /* stack[0] = separator (string or regexp)
  25908. * stack[1] = limit
  25909. * stack[2] = input string
  25910. * stack[3] = result array
  25911. * stack[4] = regexp res_obj (if is_regexp)
  25912. */
  25913. DUK_DDD(DUK_DDDPRINT("split; match_start b=%ld,c=%ld, match_end b=%ld,c=%ld, prev_end b=%ld,c=%ld",
  25914. (long) match_start_boff, (long) match_start_coff,
  25915. (long) match_end_boff, (long) match_end_coff,
  25916. (long) prev_match_end_boff, (long) prev_match_end_coff));
  25917. duk_push_lstring(ctx,
  25918. (const char *) (DUK_HSTRING_GET_DATA(h_input) + prev_match_end_boff),
  25919. (duk_size_t) (match_start_boff - prev_match_end_boff));
  25920. duk_put_prop_index(ctx, 3, arr_idx);
  25921. arr_idx++;
  25922. if (arr_idx >= limit) {
  25923. goto hit_limit;
  25924. }
  25925. #ifdef DUK_USE_REGEXP_SUPPORT
  25926. if (is_regexp) {
  25927. duk_size_t i, len;
  25928. len = duk_get_length(ctx, 4);
  25929. for (i = 1; i < len; i++) {
  25930. DUK_ASSERT(i <= DUK_UARRIDX_MAX); /* cannot have >4G captures */
  25931. duk_get_prop_index(ctx, 4, (duk_uarridx_t) i);
  25932. duk_put_prop_index(ctx, 3, arr_idx);
  25933. arr_idx++;
  25934. if (arr_idx >= limit) {
  25935. goto hit_limit;
  25936. }
  25937. }
  25938. duk_pop(ctx);
  25939. /* lastIndex already set up for next match */
  25940. } else {
  25941. #else /* DUK_USE_REGEXP_SUPPORT */
  25942. { /* unconditionally */
  25943. #endif /* DUK_USE_REGEXP_SUPPORT */
  25944. /* no action */
  25945. }
  25946. prev_match_end_boff = match_end_boff;
  25947. prev_match_end_coff = match_end_coff;
  25948. continue;
  25949. } /* for */
  25950. /* Combined step 11 (empty string special case) and 14-15. */
  25951. DUK_DDD(DUK_DDDPRINT("split trailer; prev_end b=%ld,c=%ld",
  25952. (long) prev_match_end_boff, (long) prev_match_end_coff));
  25953. if (DUK_HSTRING_GET_CHARLEN(h_input) > 0 || !matched) {
  25954. /* Add trailer if:
  25955. * a) non-empty input
  25956. * b) empty input and no (zero size) match found (step 11)
  25957. */
  25958. duk_push_lstring(ctx,
  25959. (const char *) DUK_HSTRING_GET_DATA(h_input) + prev_match_end_boff,
  25960. (duk_size_t) (DUK_HSTRING_GET_BYTELEN(h_input) - prev_match_end_boff));
  25961. duk_put_prop_index(ctx, 3, arr_idx);
  25962. /* No arr_idx update or limit check */
  25963. }
  25964. return 1;
  25965. hit_limit:
  25966. #ifdef DUK_USE_REGEXP_SUPPORT
  25967. if (is_regexp) {
  25968. duk_pop(ctx);
  25969. }
  25970. #endif
  25971. return 1;
  25972. }
  25973. /*
  25974. * Various
  25975. */
  25976. #ifdef DUK_USE_REGEXP_SUPPORT
  25977. DUK_LOCAL void duk__to_regexp_helper(duk_context *ctx, duk_idx_t index, duk_bool_t force_new) {
  25978. duk_hobject *h;
  25979. /* Shared helper for match() steps 3-4, search() steps 3-4. */
  25980. DUK_ASSERT(index >= 0);
  25981. if (force_new) {
  25982. goto do_new;
  25983. }
  25984. h = duk_get_hobject_with_class(ctx, index, DUK_HOBJECT_CLASS_REGEXP);
  25985. if (!h) {
  25986. goto do_new;
  25987. }
  25988. return;
  25989. do_new:
  25990. duk_push_hobject_bidx(ctx, DUK_BIDX_REGEXP_CONSTRUCTOR);
  25991. duk_dup(ctx, index);
  25992. duk_new(ctx, 1); /* [ ... RegExp val ] -> [ ... res ] */
  25993. duk_replace(ctx, index);
  25994. }
  25995. #endif /* DUK_USE_REGEXP_SUPPORT */
  25996. #ifdef DUK_USE_REGEXP_SUPPORT
  25997. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_search(duk_context *ctx) {
  25998. duk_hthread *thr = (duk_hthread *) ctx;
  25999. /* Easiest way to implement the search required by the specification
  26000. * is to do a RegExp test() with lastIndex forced to zero. To avoid
  26001. * side effects on the argument, "clone" the RegExp if a RegExp was
  26002. * given as input.
  26003. *
  26004. * The global flag of the RegExp should be ignored; setting lastIndex
  26005. * to zero (which happens when "cloning" the RegExp) should have an
  26006. * equivalent effect.
  26007. */
  26008. DUK_ASSERT_TOP(ctx, 1);
  26009. (void) duk_push_this_coercible_to_string(ctx); /* at index 1 */
  26010. duk__to_regexp_helper(ctx, 0 /*index*/, 1 /*force_new*/);
  26011. /* stack[0] = regexp
  26012. * stack[1] = string
  26013. */
  26014. /* Avoid using RegExp.prototype methods, as they're writable and
  26015. * configurable and may have been changed.
  26016. */
  26017. duk_dup(ctx, 0);
  26018. duk_dup(ctx, 1); /* [ ... re_obj input ] */
  26019. duk_regexp_match(thr); /* -> [ ... res_obj ] */
  26020. if (!duk_is_object(ctx, -1)) {
  26021. duk_push_int(ctx, -1);
  26022. return 1;
  26023. }
  26024. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INDEX);
  26025. DUK_ASSERT(duk_is_number(ctx, -1));
  26026. return 1;
  26027. }
  26028. #else /* DUK_USE_REGEXP_SUPPORT */
  26029. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_search(duk_context *ctx) {
  26030. DUK_UNREF(ctx);
  26031. return DUK_RET_UNSUPPORTED_ERROR;
  26032. }
  26033. #endif /* DUK_USE_REGEXP_SUPPORT */
  26034. #ifdef DUK_USE_REGEXP_SUPPORT
  26035. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_match(duk_context *ctx) {
  26036. duk_hthread *thr = (duk_hthread *) ctx;
  26037. duk_bool_t global;
  26038. duk_int_t prev_last_index;
  26039. duk_int_t this_index;
  26040. duk_int_t arr_idx;
  26041. DUK_ASSERT_TOP(ctx, 1);
  26042. (void) duk_push_this_coercible_to_string(ctx);
  26043. duk__to_regexp_helper(ctx, 0 /*index*/, 0 /*force_new*/);
  26044. global = duk_get_prop_stridx_boolean(ctx, 0, DUK_STRIDX_GLOBAL, NULL);
  26045. DUK_ASSERT_TOP(ctx, 2);
  26046. /* stack[0] = regexp
  26047. * stack[1] = string
  26048. */
  26049. if (!global) {
  26050. duk_regexp_match(thr); /* -> [ res_obj ] */
  26051. return 1; /* return 'res_obj' */
  26052. }
  26053. /* Global case is more complex. */
  26054. /* [ regexp string ] */
  26055. duk_push_int(ctx, 0);
  26056. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  26057. duk_push_array(ctx);
  26058. /* [ regexp string res_arr ] */
  26059. prev_last_index = 0;
  26060. arr_idx = 0;
  26061. for (;;) {
  26062. DUK_ASSERT_TOP(ctx, 3);
  26063. duk_dup(ctx, 0);
  26064. duk_dup(ctx, 1);
  26065. duk_regexp_match(thr); /* -> [ ... regexp string ] -> [ ... res_obj ] */
  26066. if (!duk_is_object(ctx, -1)) {
  26067. duk_pop(ctx);
  26068. break;
  26069. }
  26070. duk_get_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  26071. DUK_ASSERT(duk_is_number(ctx, -1));
  26072. this_index = duk_get_int(ctx, -1);
  26073. duk_pop(ctx);
  26074. if (this_index == prev_last_index) {
  26075. this_index++;
  26076. duk_push_int(ctx, this_index);
  26077. duk_put_prop_stridx(ctx, 0, DUK_STRIDX_LAST_INDEX);
  26078. }
  26079. prev_last_index = this_index;
  26080. duk_get_prop_index(ctx, -1, 0); /* match string */
  26081. duk_put_prop_index(ctx, 2, arr_idx);
  26082. arr_idx++;
  26083. duk_pop(ctx); /* res_obj */
  26084. }
  26085. if (arr_idx == 0) {
  26086. duk_push_null(ctx);
  26087. }
  26088. return 1; /* return 'res_arr' or 'null' */
  26089. }
  26090. #else /* DUK_USE_REGEXP_SUPPORT */
  26091. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_match(duk_context *ctx) {
  26092. DUK_UNREF(ctx);
  26093. return DUK_RET_UNSUPPORTED_ERROR;
  26094. }
  26095. #endif /* DUK_USE_REGEXP_SUPPORT */
  26096. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_concat(duk_context *ctx) {
  26097. /* duk_concat() coerces arguments with ToString() in correct order */
  26098. (void) duk_push_this_coercible_to_string(ctx);
  26099. duk_insert(ctx, 0); /* this is relatively expensive */
  26100. duk_concat(ctx, duk_get_top(ctx));
  26101. return 1;
  26102. }
  26103. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_trim(duk_context *ctx) {
  26104. DUK_ASSERT_TOP(ctx, 0);
  26105. (void) duk_push_this_coercible_to_string(ctx);
  26106. duk_trim(ctx, 0);
  26107. DUK_ASSERT_TOP(ctx, 1);
  26108. return 1;
  26109. }
  26110. DUK_INTERNAL duk_ret_t duk_bi_string_prototype_locale_compare(duk_context *ctx) {
  26111. duk_hstring *h1;
  26112. duk_hstring *h2;
  26113. duk_size_t h1_len, h2_len, prefix_len;
  26114. duk_small_int_t ret = 0;
  26115. duk_small_int_t rc;
  26116. /* The current implementation of localeCompare() is simply a codepoint
  26117. * by codepoint comparison, implemented with a simple string compare
  26118. * because UTF-8 should preserve codepoint ordering (assuming valid
  26119. * shortest UTF-8 encoding).
  26120. *
  26121. * The specification requires that the return value must be related
  26122. * to the sort order: e.g. negative means that 'this' comes before
  26123. * 'that' in sort order. We assume an ascending sort order.
  26124. */
  26125. /* XXX: could share code with duk_js_ops.c, duk_js_compare_helper */
  26126. h1 = duk_push_this_coercible_to_string(ctx);
  26127. DUK_ASSERT(h1 != NULL);
  26128. h2 = duk_to_hstring(ctx, 0);
  26129. DUK_ASSERT(h2 != NULL);
  26130. h1_len = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h1);
  26131. h2_len = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h2);
  26132. prefix_len = (h1_len <= h2_len ? h1_len : h2_len);
  26133. /* Zero size compare not an issue with DUK_MEMCMP. */
  26134. rc = (duk_small_int_t) DUK_MEMCMP((const char *) DUK_HSTRING_GET_DATA(h1),
  26135. (const char *) DUK_HSTRING_GET_DATA(h2),
  26136. prefix_len);
  26137. if (rc < 0) {
  26138. ret = -1;
  26139. goto done;
  26140. } else if (rc > 0) {
  26141. ret = 1;
  26142. goto done;
  26143. }
  26144. /* prefix matches, lengths matter now */
  26145. if (h1_len > h2_len) {
  26146. ret = 1;
  26147. goto done;
  26148. } else if (h1_len == h2_len) {
  26149. DUK_ASSERT(ret == 0);
  26150. goto done;
  26151. }
  26152. ret = -1;
  26153. goto done;
  26154. done:
  26155. duk_push_int(ctx, (duk_int_t) ret);
  26156. return 1;
  26157. }
  26158. #line 1 "duk_bi_thread.c"
  26159. /*
  26160. * Thread builtins
  26161. */
  26162. /* include removed: duk_internal.h */
  26163. /*
  26164. * Constructor
  26165. */
  26166. DUK_INTERNAL duk_ret_t duk_bi_thread_constructor(duk_context *ctx) {
  26167. duk_hthread *new_thr;
  26168. duk_hobject *func;
  26169. /* XXX: need a duk_require_func_or_lfunc_coerce() */
  26170. if (!duk_is_callable(ctx, 0)) {
  26171. return DUK_RET_TYPE_ERROR;
  26172. }
  26173. func = duk_require_hobject_or_lfunc_coerce(ctx, 0);
  26174. DUK_ASSERT(func != NULL);
  26175. duk_push_thread(ctx);
  26176. new_thr = (duk_hthread *) duk_get_hobject(ctx, -1);
  26177. DUK_ASSERT(new_thr != NULL);
  26178. new_thr->state = DUK_HTHREAD_STATE_INACTIVE;
  26179. /* push initial function call to new thread stack; this is
  26180. * picked up by resume().
  26181. */
  26182. duk_push_hobject((duk_context *) new_thr, func);
  26183. return 1; /* return thread */
  26184. }
  26185. /*
  26186. * Resume a thread.
  26187. *
  26188. * The thread must be in resumable state, either (a) new thread which hasn't
  26189. * yet started, or (b) a thread which has previously yielded. This method
  26190. * must be called from an Ecmascript function.
  26191. *
  26192. * Args:
  26193. * - thread
  26194. * - value
  26195. * - isError (defaults to false)
  26196. *
  26197. * Note: yield and resume handling is currently asymmetric.
  26198. */
  26199. DUK_INTERNAL duk_ret_t duk_bi_thread_resume(duk_context *ctx) {
  26200. duk_hthread *thr = (duk_hthread *) ctx;
  26201. duk_hthread *thr_resume;
  26202. duk_tval tv_tmp;
  26203. duk_tval *tv;
  26204. duk_hobject *func;
  26205. duk_hobject *caller_func;
  26206. duk_small_int_t is_error;
  26207. DUK_DDD(DUK_DDDPRINT("Duktape.Thread.resume(): thread=%!T, value=%!T, is_error=%!T",
  26208. (duk_tval *) duk_get_tval(ctx, 0),
  26209. (duk_tval *) duk_get_tval(ctx, 1),
  26210. (duk_tval *) duk_get_tval(ctx, 2)));
  26211. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_RUNNING);
  26212. DUK_ASSERT(thr->heap->curr_thread == thr);
  26213. thr_resume = duk_require_hthread(ctx, 0);
  26214. is_error = (duk_small_int_t) duk_to_boolean(ctx, 2);
  26215. duk_set_top(ctx, 2);
  26216. /* [ thread value ] */
  26217. /*
  26218. * Thread state and calling context checks
  26219. */
  26220. if (thr->callstack_top < 2) {
  26221. DUK_DD(DUK_DDPRINT("resume state invalid: callstack should contain at least 2 entries (caller and Duktape.Thread.resume)"));
  26222. goto state_error;
  26223. }
  26224. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1) != NULL); /* us */
  26225. DUK_ASSERT(DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1)));
  26226. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2) != NULL); /* caller */
  26227. caller_func = DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2);
  26228. if (!DUK_HOBJECT_IS_COMPILEDFUNCTION(caller_func)) {
  26229. DUK_DD(DUK_DDPRINT("resume state invalid: caller must be Ecmascript code"));
  26230. goto state_error;
  26231. }
  26232. /* Note: there is no requirement that: 'thr->callstack_preventcount == 1'
  26233. * like for yield.
  26234. */
  26235. if (thr_resume->state != DUK_HTHREAD_STATE_INACTIVE &&
  26236. thr_resume->state != DUK_HTHREAD_STATE_YIELDED) {
  26237. DUK_DD(DUK_DDPRINT("resume state invalid: target thread must be INACTIVE or YIELDED"));
  26238. goto state_error;
  26239. }
  26240. DUK_ASSERT(thr_resume->state == DUK_HTHREAD_STATE_INACTIVE ||
  26241. thr_resume->state == DUK_HTHREAD_STATE_YIELDED);
  26242. /* Further state-dependent pre-checks */
  26243. if (thr_resume->state == DUK_HTHREAD_STATE_YIELDED) {
  26244. /* no pre-checks now, assume a previous yield() has left things in
  26245. * tip-top shape (longjmp handler will assert for these).
  26246. */
  26247. } else {
  26248. DUK_ASSERT(thr_resume->state == DUK_HTHREAD_STATE_INACTIVE);
  26249. if ((thr_resume->callstack_top != 0) ||
  26250. (thr_resume->valstack_top - thr_resume->valstack != 1)) {
  26251. goto state_invalid_initial;
  26252. }
  26253. tv = &thr_resume->valstack_top[-1];
  26254. DUK_ASSERT(tv >= thr_resume->valstack && tv < thr_resume->valstack_top);
  26255. if (!DUK_TVAL_IS_OBJECT(tv)) {
  26256. goto state_invalid_initial;
  26257. }
  26258. func = DUK_TVAL_GET_OBJECT(tv);
  26259. DUK_ASSERT(func != NULL);
  26260. if (!DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  26261. /* Note: cannot be a bound function either right now,
  26262. * this would be easy to relax though.
  26263. */
  26264. goto state_invalid_initial;
  26265. }
  26266. }
  26267. /*
  26268. * The error object has been augmented with a traceback and other
  26269. * info from its creation point -- usually another thread. The
  26270. * error handler is called here right before throwing, but it also
  26271. * runs in the resumer's thread. It might be nice to get a traceback
  26272. * from the resumee but this is not the case now.
  26273. */
  26274. #if defined(DUK_USE_AUGMENT_ERROR_THROW)
  26275. if (is_error) {
  26276. DUK_ASSERT_TOP(ctx, 2); /* value (error) is at stack top */
  26277. duk_err_augment_error_throw(thr); /* in resumer's context */
  26278. }
  26279. #endif
  26280. #ifdef DUK_USE_DEBUG
  26281. if (is_error) {
  26282. DUK_DDD(DUK_DDDPRINT("RESUME ERROR: thread=%!T, value=%!T",
  26283. (duk_tval *) duk_get_tval(ctx, 0),
  26284. (duk_tval *) duk_get_tval(ctx, 1)));
  26285. } else if (thr_resume->state == DUK_HTHREAD_STATE_YIELDED) {
  26286. DUK_DDD(DUK_DDDPRINT("RESUME NORMAL: thread=%!T, value=%!T",
  26287. (duk_tval *) duk_get_tval(ctx, 0),
  26288. (duk_tval *) duk_get_tval(ctx, 1)));
  26289. } else {
  26290. DUK_DDD(DUK_DDDPRINT("RESUME INITIAL: thread=%!T, value=%!T",
  26291. (duk_tval *) duk_get_tval(ctx, 0),
  26292. (duk_tval *) duk_get_tval(ctx, 1)));
  26293. }
  26294. #endif
  26295. thr->heap->lj.type = DUK_LJ_TYPE_RESUME;
  26296. /* lj value2: thread */
  26297. DUK_ASSERT(thr->valstack_bottom < thr->valstack_top);
  26298. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value2);
  26299. DUK_TVAL_SET_TVAL(&thr->heap->lj.value2, &thr->valstack_bottom[0]);
  26300. DUK_TVAL_INCREF(thr, &thr->heap->lj.value2);
  26301. DUK_TVAL_DECREF(thr, &tv_tmp);
  26302. /* lj value1: value */
  26303. DUK_ASSERT(thr->valstack_bottom + 1 < thr->valstack_top);
  26304. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value1);
  26305. DUK_TVAL_SET_TVAL(&thr->heap->lj.value1, &thr->valstack_bottom[1]);
  26306. DUK_TVAL_INCREF(thr, &thr->heap->lj.value1);
  26307. DUK_TVAL_DECREF(thr, &tv_tmp);
  26308. thr->heap->lj.iserror = is_error;
  26309. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL); /* call is from executor, so we know we have a jmpbuf */
  26310. duk_err_longjmp(thr); /* execution resumes in bytecode executor */
  26311. return 0; /* never here */
  26312. state_invalid_initial:
  26313. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "invalid initial thread state/stack");
  26314. return 0; /* never here */
  26315. state_error:
  26316. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "invalid state for resume");
  26317. return 0; /* never here */
  26318. }
  26319. /*
  26320. * Yield the current thread.
  26321. *
  26322. * The thread must be in yieldable state: it must have a resumer, and there
  26323. * must not be any yield-preventing calls (native calls and constructor calls,
  26324. * currently) in the thread's call stack (otherwise a resume would not be
  26325. * possible later). This method must be called from an Ecmascript function.
  26326. *
  26327. * Args:
  26328. * - value
  26329. * - isError (defaults to false)
  26330. *
  26331. * Note: yield and resume handling is currently asymmetric.
  26332. */
  26333. DUK_INTERNAL duk_ret_t duk_bi_thread_yield(duk_context *ctx) {
  26334. duk_hthread *thr = (duk_hthread *) ctx;
  26335. duk_tval tv_tmp;
  26336. duk_hobject *caller_func;
  26337. duk_small_int_t is_error;
  26338. DUK_DDD(DUK_DDDPRINT("Duktape.Thread.yield(): value=%!T, is_error=%!T",
  26339. (duk_tval *) duk_get_tval(ctx, 0),
  26340. (duk_tval *) duk_get_tval(ctx, 1)));
  26341. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_RUNNING);
  26342. DUK_ASSERT(thr->heap->curr_thread == thr);
  26343. is_error = (duk_small_int_t) duk_to_boolean(ctx, 1);
  26344. duk_set_top(ctx, 1);
  26345. /* [ value ] */
  26346. /*
  26347. * Thread state and calling context checks
  26348. */
  26349. if (!thr->resumer) {
  26350. DUK_DD(DUK_DDPRINT("yield state invalid: current thread must have a resumer"));
  26351. goto state_error;
  26352. }
  26353. DUK_ASSERT(thr->resumer->state == DUK_HTHREAD_STATE_RESUMED);
  26354. if (thr->callstack_top < 2) {
  26355. DUK_DD(DUK_DDPRINT("yield state invalid: callstack should contain at least 2 entries (caller and Duktape.Thread.yield)"));
  26356. goto state_error;
  26357. }
  26358. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1) != NULL); /* us */
  26359. DUK_ASSERT(DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1)));
  26360. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2) != NULL); /* caller */
  26361. caller_func = DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2);
  26362. if (!DUK_HOBJECT_IS_COMPILEDFUNCTION(caller_func)) {
  26363. DUK_DD(DUK_DDPRINT("yield state invalid: caller must be Ecmascript code"));
  26364. goto state_error;
  26365. }
  26366. DUK_ASSERT(thr->callstack_preventcount >= 1); /* should never be zero, because we (Duktape.Thread.yield) are on the stack */
  26367. if (thr->callstack_preventcount != 1) {
  26368. /* Note: the only yield-preventing call is Duktape.Thread.yield(), hence check for 1, not 0 */
  26369. DUK_DD(DUK_DDPRINT("yield state invalid: there must be no yield-preventing calls in current thread callstack (preventcount is %ld)",
  26370. (long) thr->callstack_preventcount));
  26371. goto state_error;
  26372. }
  26373. /*
  26374. * The error object has been augmented with a traceback and other
  26375. * info from its creation point -- usually the current thread.
  26376. * The error handler, however, is called right before throwing
  26377. * and runs in the yielder's thread.
  26378. */
  26379. #if defined(DUK_USE_AUGMENT_ERROR_THROW)
  26380. if (is_error) {
  26381. DUK_ASSERT_TOP(ctx, 1); /* value (error) is at stack top */
  26382. duk_err_augment_error_throw(thr); /* in yielder's context */
  26383. }
  26384. #endif
  26385. #ifdef DUK_USE_DEBUG
  26386. if (is_error) {
  26387. DUK_DDD(DUK_DDDPRINT("YIELD ERROR: value=%!T",
  26388. (duk_tval *) duk_get_tval(ctx, 0)));
  26389. } else {
  26390. DUK_DDD(DUK_DDDPRINT("YIELD NORMAL: value=%!T",
  26391. (duk_tval *) duk_get_tval(ctx, 0)));
  26392. }
  26393. #endif
  26394. /*
  26395. * Process yield
  26396. *
  26397. * After longjmp(), processing continues in bytecode executor longjmp
  26398. * handler, which will e.g. update thr->resumer to NULL.
  26399. */
  26400. thr->heap->lj.type = DUK_LJ_TYPE_YIELD;
  26401. /* lj value1: value */
  26402. DUK_ASSERT(thr->valstack_bottom < thr->valstack_top);
  26403. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value1);
  26404. DUK_TVAL_SET_TVAL(&thr->heap->lj.value1, &thr->valstack_bottom[0]);
  26405. DUK_TVAL_INCREF(thr, &thr->heap->lj.value1);
  26406. DUK_TVAL_DECREF(thr, &tv_tmp);
  26407. thr->heap->lj.iserror = is_error;
  26408. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL); /* call is from executor, so we know we have a jmpbuf */
  26409. duk_err_longjmp(thr); /* execution resumes in bytecode executor */
  26410. return 0; /* never here */
  26411. state_error:
  26412. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "invalid state for yield");
  26413. return 0; /* never here */
  26414. }
  26415. DUK_INTERNAL duk_ret_t duk_bi_thread_current(duk_context *ctx) {
  26416. duk_push_current_thread(ctx);
  26417. return 1;
  26418. }
  26419. #line 1 "duk_bi_thrower.c"
  26420. /*
  26421. * Type error thrower, E5 Section 13.2.3.
  26422. */
  26423. /* include removed: duk_internal.h */
  26424. DUK_INTERNAL duk_ret_t duk_bi_type_error_thrower(duk_context *ctx) {
  26425. DUK_UNREF(ctx);
  26426. return DUK_RET_TYPE_ERROR;
  26427. }
  26428. #line 1 "duk_debug_fixedbuffer.c"
  26429. /*
  26430. * Fixed buffer helper useful for debugging, requires no allocation
  26431. * which is critical for debugging.
  26432. */
  26433. /* include removed: duk_internal.h */
  26434. #ifdef DUK_USE_DEBUG
  26435. DUK_INTERNAL void duk_fb_put_bytes(duk_fixedbuffer *fb, duk_uint8_t *buffer, duk_size_t length) {
  26436. duk_size_t avail;
  26437. duk_size_t copylen;
  26438. avail = (fb->offset >= fb->length ? (duk_size_t) 0 : (duk_size_t) (fb->length - fb->offset));
  26439. if (length > avail) {
  26440. copylen = avail;
  26441. fb->truncated = 1;
  26442. } else {
  26443. copylen = length;
  26444. }
  26445. DUK_MEMCPY(fb->buffer + fb->offset, buffer, copylen);
  26446. fb->offset += copylen;
  26447. }
  26448. DUK_INTERNAL void duk_fb_put_byte(duk_fixedbuffer *fb, duk_uint8_t x) {
  26449. duk_fb_put_bytes(fb, &x, 1);
  26450. }
  26451. DUK_INTERNAL void duk_fb_put_cstring(duk_fixedbuffer *fb, const char *x) {
  26452. duk_fb_put_bytes(fb, (duk_uint8_t *) x, (duk_size_t) DUK_STRLEN(x));
  26453. }
  26454. DUK_INTERNAL void duk_fb_sprintf(duk_fixedbuffer *fb, const char *fmt, ...) {
  26455. duk_size_t avail;
  26456. va_list ap;
  26457. va_start(ap, fmt);
  26458. avail = (fb->offset >= fb->length ? (duk_size_t) 0 : (duk_size_t) (fb->length - fb->offset));
  26459. if (avail > 0) {
  26460. duk_int_t res = (duk_int_t) DUK_VSNPRINTF((char *) (fb->buffer + fb->offset), avail, fmt, ap);
  26461. if (res < 0) {
  26462. /* error */
  26463. } else if ((duk_size_t) res >= avail) {
  26464. /* (maybe) truncated */
  26465. fb->offset += avail;
  26466. if ((duk_size_t) res > avail) {
  26467. /* actual chars dropped (not just NUL term) */
  26468. fb->truncated = 1;
  26469. }
  26470. } else {
  26471. /* normal */
  26472. fb->offset += res;
  26473. }
  26474. }
  26475. va_end(ap);
  26476. }
  26477. DUK_INTERNAL void duk_fb_put_funcptr(duk_fixedbuffer *fb, duk_uint8_t *fptr, duk_size_t fptr_size) {
  26478. char buf[64+1];
  26479. duk_debug_format_funcptr(buf, sizeof(buf), fptr, fptr_size);
  26480. buf[sizeof(buf) - 1] = (char) 0;
  26481. duk_fb_put_cstring(fb, buf);
  26482. }
  26483. DUK_INTERNAL duk_bool_t duk_fb_is_full(duk_fixedbuffer *fb) {
  26484. return (fb->offset >= fb->length);
  26485. }
  26486. #endif /* DUK_USE_DEBUG */
  26487. #line 1 "duk_debug_heap.c"
  26488. /*
  26489. * Debug dumping of duk_heap.
  26490. */
  26491. /* include removed: duk_internal.h */
  26492. #ifdef DUK_USE_DEBUG
  26493. #if 0 /*unused*/
  26494. DUK_LOCAL void duk__sanitize_snippet(char *buf, duk_size_t buf_size, duk_hstring *str) {
  26495. duk_size_t i;
  26496. duk_size_t nchars;
  26497. duk_size_t maxchars;
  26498. duk_uint8_t *data;
  26499. DUK_MEMZERO(buf, buf_size);
  26500. maxchars = (duk_size_t) (buf_size - 1);
  26501. data = DUK_HSTRING_GET_DATA(str);
  26502. nchars = ((duk_size_t) str->blen < maxchars ? (duk_size_t) str->blen : maxchars);
  26503. for (i = 0; i < nchars; i++) {
  26504. duk_small_int_t c = (duk_small_int_t) data[i];
  26505. if (c < 0x20 || c > 0x7e) {
  26506. c = '.';
  26507. }
  26508. buf[i] = (char) c;
  26509. }
  26510. }
  26511. #endif
  26512. #if 0
  26513. DUK_LOCAL const char *duk__get_heap_type_string(duk_heaphdr *hdr) {
  26514. switch (DUK_HEAPHDR_GET_TYPE(hdr)) {
  26515. case DUK_HTYPE_STRING:
  26516. return "string";
  26517. case DUK_HTYPE_OBJECT:
  26518. return "object";
  26519. case DUK_HTYPE_BUFFER:
  26520. return "buffer";
  26521. default:
  26522. return "???";
  26523. }
  26524. }
  26525. #endif
  26526. #if 0
  26527. DUK_LOCAL void duk__dump_indented(duk_heaphdr *obj, int index) {
  26528. DUK_UNREF(obj);
  26529. DUK_UNREF(index);
  26530. DUK_UNREF(duk__get_heap_type_string);
  26531. #ifdef DUK_USE_REFERENCE_COUNTING
  26532. DUK_D(DUK_DPRINT(" [%ld]: %p %s (flags: 0x%08lx, ref: %ld) -> %!O",
  26533. (long) index,
  26534. (void *) obj,
  26535. (const char *) duk__get_heap_type_string(obj),
  26536. (unsigned long) DUK_HEAPHDR_GET_FLAGS(obj),
  26537. (long) DUK_HEAPHDR_GET_REFCOUNT(obj),
  26538. (duk_heaphdr *) obj));
  26539. #else
  26540. DUK_D(DUK_DPRINT(" [%ld]: %p %s (flags: 0x%08lx) -> %!O",
  26541. (long) index,
  26542. (void *) obj,
  26543. (const char *) duk__get_heap_type_string(obj),
  26544. (unsigned long) DUK_HEAPHDR_GET_FLAGS(obj),
  26545. (duk_heaphdr *) obj));
  26546. #endif
  26547. }
  26548. #endif
  26549. #if 0 /*unused*/
  26550. DUK_LOCAL void duk__dump_heaphdr_list(duk_heap *heap, duk_heaphdr *root, const char *name) {
  26551. duk_int_t count;
  26552. duk_heaphdr *curr;
  26553. DUK_UNREF(heap);
  26554. DUK_UNREF(name);
  26555. count = 0;
  26556. curr = root;
  26557. while (curr) {
  26558. count++;
  26559. curr = DUK_HEAPHDR_GET_NEXT(curr);
  26560. }
  26561. DUK_D(DUK_DPRINT("%s, %ld objects", (const char *) name, (long) count));
  26562. count = 0;
  26563. curr = root;
  26564. while (curr) {
  26565. count++;
  26566. duk__dump_indented(curr, count);
  26567. curr = DUK_HEAPHDR_GET_NEXT(curr);
  26568. }
  26569. }
  26570. #endif
  26571. #if 0 /*unused*/
  26572. DUK_LOCAL void duk__dump_stringtable(duk_heap *heap) {
  26573. duk_uint_fast32_t i;
  26574. char buf[64+1];
  26575. DUK_D(DUK_DPRINT("stringtable %p, used %ld, size %ld, load %ld%%",
  26576. (void *) heap->strtable,
  26577. (long) heap->st_used,
  26578. (long) heap->st_size,
  26579. (long) (((double) heap->st_used) / ((double) heap->st_size) * 100.0)));
  26580. for (i = 0; i < (duk_uint_fast32_t) heap->st_size; i++) {
  26581. duk_hstring *e = heap->strtable[i];
  26582. if (!e) {
  26583. DUK_D(DUK_DPRINT(" [%ld]: NULL", (long) i));
  26584. } else if (e == DUK_STRTAB_DELETED_MARKER(heap)) {
  26585. DUK_D(DUK_DPRINT(" [%ld]: DELETED", (long) i));
  26586. } else {
  26587. duk__sanitize_snippet(buf, sizeof(buf), e);
  26588. #ifdef DUK_USE_REFERENCE_COUNTING
  26589. DUK_D(DUK_DPRINT(" [%ld]: %p (flags: 0x%08lx, ref: %ld) '%s', strhash=0x%08lx, blen=%ld, clen=%ld, "
  26590. "arridx=%ld, internal=%ld, reserved_word=%ld, strict_reserved_word=%ld, eval_or_arguments=%ld",
  26591. (long) i,
  26592. (void *) e,
  26593. (unsigned long) DUK_HEAPHDR_GET_FLAGS((duk_heaphdr *) e),
  26594. (long) DUK_HEAPHDR_GET_REFCOUNT((duk_heaphdr *) e),
  26595. (const char *) buf,
  26596. (unsigned long) e->hash,
  26597. (long) e->blen,
  26598. (long) e->clen,
  26599. (long) (DUK_HSTRING_HAS_ARRIDX(e) ? 1 : 0),
  26600. (long) (DUK_HSTRING_HAS_INTERNAL(e) ? 1 : 0),
  26601. (long) (DUK_HSTRING_HAS_RESERVED_WORD(e) ? 1 : 0),
  26602. (long) (DUK_HSTRING_HAS_STRICT_RESERVED_WORD(e) ? 1 : 0),
  26603. (long) (DUK_HSTRING_HAS_EVAL_OR_ARGUMENTS(e) ? 1 : 0)));
  26604. #else
  26605. DUK_D(DUK_DPRINT(" [%ld]: %p (flags: 0x%08lx) '%s', strhash=0x%08lx, blen=%ld, clen=%ld, "
  26606. "arridx=%ld, internal=%ld, reserved_word=%ld, strict_reserved_word=%ld, eval_or_arguments=%ld",
  26607. (long) i,
  26608. (void *) e,
  26609. (unsigned long) DUK_HEAPHDR_GET_FLAGS((duk_heaphdr *) e),
  26610. (const char *) buf,
  26611. (long) e->hash,
  26612. (long) e->blen,
  26613. (long) e->clen,
  26614. (long) (DUK_HSTRING_HAS_ARRIDX(e) ? 1 : 0),
  26615. (long) (DUK_HSTRING_HAS_INTERNAL(e) ? 1 : 0),
  26616. (long) (DUK_HSTRING_HAS_RESERVED_WORD(e) ? 1 : 0),
  26617. (long) (DUK_HSTRING_HAS_STRICT_RESERVED_WORD(e) ? 1 : 0),
  26618. (long) (DUK_HSTRING_HAS_EVAL_OR_ARGUMENTS(e) ? 1 : 0)));
  26619. #endif
  26620. }
  26621. }
  26622. }
  26623. #endif
  26624. #if 0 /*unused*/
  26625. DUK_LOCAL void duk__dump_strcache(duk_heap *heap) {
  26626. duk_uint_fast32_t i;
  26627. char buf[64+1];
  26628. DUK_D(DUK_DPRINT("stringcache"));
  26629. for (i = 0; i < (duk_uint_fast32_t) DUK_HEAP_STRCACHE_SIZE; i++) {
  26630. duk_strcache *c = &heap->strcache[i];
  26631. if (!c->h) {
  26632. DUK_D(DUK_DPRINT(" [%ld]: bidx=%ld, cidx=%ld, str=NULL",
  26633. (long) i, (long) c->bidx, (long) c->cidx));
  26634. } else {
  26635. duk__sanitize_snippet(buf, sizeof(buf), c->h);
  26636. DUK_D(DUK_DPRINT(" [%ld]: bidx=%ld cidx=%ld str=%s",
  26637. (long) i, (long) c->bidx, (long) c->cidx, (const char *) buf));
  26638. }
  26639. }
  26640. }
  26641. #endif
  26642. #if 0 /*unused*/
  26643. DUK_INTERNAL void duk_debug_dump_heap(duk_heap *heap) {
  26644. char buf[64+1];
  26645. DUK_D(DUK_DPRINT("=== heap %p ===", (void *) heap));
  26646. DUK_D(DUK_DPRINT(" flags: 0x%08lx", (unsigned long) heap->flags));
  26647. /* Note: there is no standard formatter for function pointers */
  26648. #ifdef DUK_USE_GCC_PRAGMAS
  26649. #pragma GCC diagnostic push
  26650. #pragma GCC diagnostic ignored "-pedantic"
  26651. #endif
  26652. duk_debug_format_funcptr(buf, sizeof(buf), (duk_uint8_t *) &heap->alloc_func, sizeof(heap->alloc_func));
  26653. DUK_D(DUK_DPRINT(" alloc_func: %s", (const char *) buf));
  26654. duk_debug_format_funcptr(buf, sizeof(buf), (duk_uint8_t *) &heap->realloc_func, sizeof(heap->realloc_func));
  26655. DUK_D(DUK_DPRINT(" realloc_func: %s", (const char *) buf));
  26656. duk_debug_format_funcptr(buf, sizeof(buf), (duk_uint8_t *) &heap->free_func, sizeof(heap->free_func));
  26657. DUK_D(DUK_DPRINT(" free_func: %s", (const char *) buf));
  26658. duk_debug_format_funcptr(buf, sizeof(buf), (duk_uint8_t *) &heap->fatal_func, sizeof(heap->fatal_func));
  26659. DUK_D(DUK_DPRINT(" fatal_func: %s", (const char *) buf));
  26660. #ifdef DUK_USE_GCC_PRAGMAS
  26661. #pragma GCC diagnostic pop
  26662. #endif
  26663. DUK_D(DUK_DPRINT(" heap_udata: %p", (void *) heap->heap_udata));
  26664. #ifdef DUK_USE_MARK_AND_SWEEP
  26665. #ifdef DUK_USE_VOLUNTARY_GC
  26666. DUK_D(DUK_DPRINT(" mark-and-sweep trig counter: %ld", (long) heap->mark_and_sweep_trigger_counter));
  26667. #endif
  26668. DUK_D(DUK_DPRINT(" mark-and-sweep rec depth: %ld", (long) heap->mark_and_sweep_recursion_depth));
  26669. DUK_D(DUK_DPRINT(" mark-and-sweep base flags: 0x%08lx", (unsigned long) heap->mark_and_sweep_base_flags));
  26670. #endif
  26671. DUK_D(DUK_DPRINT(" lj.jmpbuf_ptr: %p", (void *) heap->lj.jmpbuf_ptr));
  26672. DUK_D(DUK_DPRINT(" lj.type: %ld", (long) heap->lj.type));
  26673. DUK_D(DUK_DPRINT(" lj.value1: %!T", (duk_tval *) &heap->lj.value1));
  26674. DUK_D(DUK_DPRINT(" lj.value2: %!T", (duk_tval *) &heap->lj.value2));
  26675. DUK_D(DUK_DPRINT(" lj.iserror: %ld", (long) heap->lj.iserror));
  26676. DUK_D(DUK_DPRINT(" handling_error: %ld", (long) heap->handling_error));
  26677. DUK_D(DUK_DPRINT(" heap_thread: %!@O", (duk_heaphdr *) heap->heap_thread));
  26678. DUK_D(DUK_DPRINT(" curr_thread: %!@O", (duk_heaphdr *) heap->curr_thread));
  26679. DUK_D(DUK_DPRINT(" heap_object: %!@O", (duk_heaphdr *) heap->heap_object));
  26680. DUK_D(DUK_DPRINT(" call_recursion_depth: %ld", (long) heap->call_recursion_depth));
  26681. DUK_D(DUK_DPRINT(" call_recursion_limit: %ld", (long) heap->call_recursion_limit));
  26682. DUK_D(DUK_DPRINT(" hash_seed: 0x%08lx", (unsigned long) heap->hash_seed));
  26683. DUK_D(DUK_DPRINT(" rnd_state: 0x%08lx", (unsigned long) heap->rnd_state));
  26684. duk__dump_strcache(heap);
  26685. duk__dump_heaphdr_list(heap, heap->heap_allocated, "heap allocated");
  26686. #ifdef DUK_USE_REFERENCE_COUNTING
  26687. duk__dump_heaphdr_list(heap, heap->refzero_list, "refcounting refzero list");
  26688. #endif
  26689. #ifdef DUK_USE_MARK_AND_SWEEP
  26690. duk__dump_heaphdr_list(heap, heap->finalize_list, "mark-and-sweep finalize list");
  26691. #endif
  26692. duk__dump_stringtable(heap);
  26693. /* heap->strs: not worth dumping */
  26694. }
  26695. #endif
  26696. #endif /* DUK_USE_DEBUG */
  26697. #line 1 "duk_debug_vsnprintf.c"
  26698. /*
  26699. * Custom formatter for debug printing, allowing Duktape specific data
  26700. * structures (such as tagged values and heap objects) to be printed with
  26701. * a nice format string. Because debug printing should not affect execution
  26702. * state, formatting here must be independent of execution (see implications
  26703. * below) and must not allocate memory.
  26704. *
  26705. * Custom format tags begin with a '%!' to safely distinguish them from
  26706. * standard format tags. The following conversions are supported:
  26707. *
  26708. * %!T tagged value (duk_tval *)
  26709. * %!O heap object (duk_heaphdr *)
  26710. * %!I decoded bytecode instruction
  26711. * %!C bytecode instruction opcode name (arg is long)
  26712. *
  26713. * Everything is serialized in a JSON-like manner. The default depth is one
  26714. * level, internal prototype is not followed, and internal properties are not
  26715. * serialized. The following modifiers change this behavior:
  26716. *
  26717. * @ print pointers
  26718. * # print binary representations (where applicable)
  26719. * d deep traversal of own properties (not prototype)
  26720. * p follow prototype chain (useless without 'd')
  26721. * i include internal properties (other than prototype)
  26722. * x hexdump buffers
  26723. * h heavy formatting
  26724. *
  26725. * For instance, the following serializes objects recursively, but does not
  26726. * follow the prototype chain nor print internal properties: "%!dO".
  26727. *
  26728. * Notes:
  26729. *
  26730. * * Standard snprintf return value semantics seem to vary. This
  26731. * implementation returns the number of bytes it actually wrote
  26732. * (excluding the null terminator). If retval == buffer size,
  26733. * output was truncated (except for corner cases).
  26734. *
  26735. * * Output format is intentionally different from Ecmascript
  26736. * formatting requirements, as formatting here serves debugging
  26737. * of internals.
  26738. *
  26739. * * Depth checking (and updating) is done in each type printer
  26740. * separately, to allow them to call each other freely.
  26741. *
  26742. * * Some pathological structures might take ages to print (e.g.
  26743. * self recursion with 100 properties pointing to the object
  26744. * itself). To guard against these, each printer also checks
  26745. * whether the output buffer is full; if so, early exit.
  26746. *
  26747. * * Reference loops are detected using a loop stack.
  26748. */
  26749. /* include removed: duk_internal.h */
  26750. #ifdef DUK_USE_DEBUG
  26751. #include <stdio.h>
  26752. #include <stdarg.h>
  26753. #include <string.h>
  26754. /* list of conversion specifiers that terminate a format tag;
  26755. * this is unfortunately guesswork.
  26756. */
  26757. #define DUK__ALLOWED_STANDARD_SPECIFIERS "diouxXeEfFgGaAcsCSpnm"
  26758. /* maximum length of standard format tag that we support */
  26759. #define DUK__MAX_FORMAT_TAG_LENGTH 32
  26760. /* heapobj recursion depth when deep printing is selected */
  26761. #define DUK__DEEP_DEPTH_LIMIT 8
  26762. /* maximum recursion depth for loop detection stacks */
  26763. #define DUK__LOOP_STACK_DEPTH 256
  26764. /* must match bytecode defines now; build autogenerate? */
  26765. DUK_LOCAL const char *duk__bc_optab[64] = {
  26766. "LDREG", "STREG", "LDCONST", "LDINT", "LDINTX", "MPUTOBJ", "MPUTOBJI", "MPUTARR", "MPUTARRI", "NEW",
  26767. "NEWI", "REGEXP", "CSREG", "CSREGI", "GETVAR", "PUTVAR", "DECLVAR", "DELVAR", "CSVAR", "CSVARI",
  26768. "CLOSURE", "GETPROP", "PUTPROP", "DELPROP", "CSPROP", "CSPROPI", "ADD", "SUB", "MUL", "DIV",
  26769. "MOD", "BAND", "BOR", "BXOR", "BASL", "BLSR", "BASR", "EQ", "NEQ", "SEQ",
  26770. "SNEQ", "GT", "GE", "LT", "LE", "IF", "JUMP", "RETURN", "CALL", "CALLI",
  26771. "TRYCATCH", "EXTRA", "PREINCR", "PREDECR", "POSTINCR", "POSTDECR", "PREINCV", "PREDECV", "POSTINCV", "POSTDECV",
  26772. "PREINCP", "PREDECP", "POSTINCP", "POSTDECP"
  26773. };
  26774. DUK_LOCAL const char *duk__bc_extraoptab[256] = {
  26775. "NOP", "INVALID", "LDTHIS", "LDUNDEF", "LDNULL", "LDTRUE", "LDFALSE", "NEWOBJ", "NEWARR", "SETALEN",
  26776. "TYPEOF", "TYPEOFID", "INITENUM", "NEXTENUM", "INITSET", "INITSETI", "INITGET", "INITGETI", "ENDTRY", "ENDCATCH",
  26777. "ENDFIN", "THROW", "INVLHS", "UNM", "UNP", "DEBUGGER", "BREAK", "CONTINUE", "BNOT", "LNOT",
  26778. "INSTOF", "IN", "LABEL", "ENDLABEL", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26779. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26780. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26781. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26782. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26783. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26784. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26785. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26786. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26787. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26788. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26789. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26790. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26791. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26792. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26793. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26794. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26795. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26796. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26797. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26798. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26799. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX", "XXX",
  26800. "XXX", "XXX", "XXX", "XXX", "XXX", "XXX"
  26801. };
  26802. typedef struct duk__dprint_state duk__dprint_state;
  26803. struct duk__dprint_state {
  26804. duk_fixedbuffer *fb;
  26805. /* loop_stack_index could be perhaps be replaced by 'depth', but it's nice
  26806. * to not couple these two mechanisms unnecessarily.
  26807. */
  26808. duk_hobject *loop_stack[DUK__LOOP_STACK_DEPTH];
  26809. duk_int_t loop_stack_index;
  26810. duk_int_t loop_stack_limit;
  26811. duk_int_t depth;
  26812. duk_int_t depth_limit;
  26813. duk_bool_t pointer;
  26814. duk_bool_t heavy;
  26815. duk_bool_t binary;
  26816. duk_bool_t follow_proto;
  26817. duk_bool_t internal;
  26818. duk_bool_t hexdump;
  26819. };
  26820. /* helpers */
  26821. DUK_LOCAL_DECL void duk__print_hstring(duk__dprint_state *st, duk_hstring *k, duk_bool_t quotes);
  26822. DUK_LOCAL_DECL void duk__print_hobject(duk__dprint_state *st, duk_hobject *h);
  26823. DUK_LOCAL_DECL void duk__print_hbuffer(duk__dprint_state *st, duk_hbuffer *h);
  26824. DUK_LOCAL_DECL void duk__print_tval(duk__dprint_state *st, duk_tval *tv);
  26825. DUK_LOCAL_DECL void duk__print_instr(duk__dprint_state *st, duk_instr_t ins);
  26826. DUK_LOCAL_DECL void duk__print_heaphdr(duk__dprint_state *st, duk_heaphdr *h);
  26827. DUK_LOCAL_DECL void duk__print_shared_heaphdr(duk__dprint_state *st, duk_heaphdr *h);
  26828. DUK_LOCAL_DECL void duk__print_shared_heaphdr_string(duk__dprint_state *st, duk_heaphdr_string *h);
  26829. DUK_LOCAL void duk__print_shared_heaphdr(duk__dprint_state *st, duk_heaphdr *h) {
  26830. duk_fixedbuffer *fb = st->fb;
  26831. if (st->heavy) {
  26832. duk_fb_sprintf(fb, "(%p)", (void *) h);
  26833. }
  26834. if (!h) {
  26835. return;
  26836. }
  26837. if (st->binary) {
  26838. duk_size_t i;
  26839. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_LBRACKET);
  26840. for (i = 0; i < (duk_size_t) sizeof(*h); i++) {
  26841. duk_fb_sprintf(fb, "%02lx", (unsigned long) ((duk_uint8_t *)h)[i]);
  26842. }
  26843. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_RBRACKET);
  26844. }
  26845. #ifdef DUK_USE_REFERENCE_COUNTING /* currently implicitly also DUK_USE_DOUBLE_LINKED_HEAP */
  26846. if (st->heavy) {
  26847. duk_fb_sprintf(fb, "[h_next=%p,h_prev=%p,h_refcount=%lu,h_flags=%08lx,type=%ld,"
  26848. "reachable=%ld,temproot=%ld,finalizable=%ld,finalized=%ld]",
  26849. (void *) DUK_HEAPHDR_GET_NEXT(NULL, h),
  26850. (void *) DUK_HEAPHDR_GET_PREV(NULL, h),
  26851. (unsigned long) DUK_HEAPHDR_GET_REFCOUNT(h),
  26852. (unsigned long) DUK_HEAPHDR_GET_FLAGS(h),
  26853. (long) DUK_HEAPHDR_GET_TYPE(h),
  26854. (long) (DUK_HEAPHDR_HAS_REACHABLE(h) ? 1 : 0),
  26855. (long) (DUK_HEAPHDR_HAS_TEMPROOT(h) ? 1 : 0),
  26856. (long) (DUK_HEAPHDR_HAS_FINALIZABLE(h) ? 1 : 0),
  26857. (long) (DUK_HEAPHDR_HAS_FINALIZED(h) ? 1 : 0));
  26858. }
  26859. #else
  26860. if (st->heavy) {
  26861. duk_fb_sprintf(fb, "[h_next=%p,h_flags=%08lx,type=%ld,reachable=%ld,temproot=%ld,finalizable=%ld,finalized=%ld]",
  26862. (void *) DUK_HEAPHDR_GET_NEXT(NULL, h),
  26863. (unsigned long) DUK_HEAPHDR_GET_FLAGS(h),
  26864. (long) DUK_HEAPHDR_GET_TYPE(h),
  26865. (long) (DUK_HEAPHDR_HAS_REACHABLE(h) ? 1 : 0),
  26866. (long) (DUK_HEAPHDR_HAS_TEMPROOT(h) ? 1 : 0),
  26867. (long) (DUK_HEAPHDR_HAS_FINALIZABLE(h) ? 1 : 0),
  26868. (long) (DUK_HEAPHDR_HAS_FINALIZED(h) ? 1 : 0));
  26869. }
  26870. #endif
  26871. }
  26872. DUK_LOCAL void duk__print_shared_heaphdr_string(duk__dprint_state *st, duk_heaphdr_string *h) {
  26873. duk_fixedbuffer *fb = st->fb;
  26874. if (st->heavy) {
  26875. duk_fb_sprintf(fb, "(%p)", (void *) h);
  26876. }
  26877. if (!h) {
  26878. return;
  26879. }
  26880. if (st->binary) {
  26881. duk_size_t i;
  26882. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_LBRACKET);
  26883. for (i = 0; i < (duk_size_t) sizeof(*h); i++) {
  26884. duk_fb_sprintf(fb, "%02lx", (unsigned long) ((duk_uint8_t *)h)[i]);
  26885. }
  26886. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_RBRACKET);
  26887. }
  26888. #ifdef DUK_USE_REFERENCE_COUNTING
  26889. if (st->heavy) {
  26890. duk_fb_sprintf(fb, "[h_refcount=%lu,h_flags=%08lx,type=%ld,reachable=%ld,temproot=%ld,finalizable=%ld,finalized=%ld]",
  26891. (unsigned long) DUK_HEAPHDR_GET_REFCOUNT((duk_heaphdr *) h),
  26892. (unsigned long) DUK_HEAPHDR_GET_FLAGS((duk_heaphdr *) h),
  26893. (long) DUK_HEAPHDR_GET_TYPE((duk_heaphdr *) h),
  26894. (long) (DUK_HEAPHDR_HAS_REACHABLE((duk_heaphdr *) h) ? 1 : 0),
  26895. (long) (DUK_HEAPHDR_HAS_TEMPROOT((duk_heaphdr *) h) ? 1 : 0),
  26896. (long) (DUK_HEAPHDR_HAS_FINALIZABLE((duk_heaphdr *) h) ? 1 : 0),
  26897. (long) (DUK_HEAPHDR_HAS_FINALIZED((duk_heaphdr *) h) ? 1 : 0));
  26898. }
  26899. #else
  26900. if (st->heavy) {
  26901. duk_fb_sprintf(fb, "[h_flags=%08lx,type=%ld,reachable=%ld,temproot=%ld,finalizable=%ld,finalized=%ld]",
  26902. (unsigned long) DUK_HEAPHDR_GET_FLAGS((duk_heaphdr *) h),
  26903. (long) DUK_HEAPHDR_GET_TYPE((duk_heaphdr *) h),
  26904. (long) (DUK_HEAPHDR_HAS_REACHABLE((duk_heaphdr *) h) ? 1 : 0),
  26905. (long) (DUK_HEAPHDR_HAS_TEMPROOT((duk_heaphdr *) h) ? 1 : 0),
  26906. (long) (DUK_HEAPHDR_HAS_FINALIZABLE((duk_heaphdr *) h) ? 1 : 0),
  26907. (long) (DUK_HEAPHDR_HAS_FINALIZED((duk_heaphdr *) h) ? 1 : 0));
  26908. }
  26909. #endif
  26910. }
  26911. DUK_LOCAL void duk__print_hstring(duk__dprint_state *st, duk_hstring *h, duk_bool_t quotes) {
  26912. duk_fixedbuffer *fb = st->fb;
  26913. const duk_uint8_t *p;
  26914. const duk_uint8_t *p_end;
  26915. /* terminal type: no depth check */
  26916. if (duk_fb_is_full(fb)) {
  26917. return;
  26918. }
  26919. duk__print_shared_heaphdr_string(st, &h->hdr);
  26920. if (!h) {
  26921. duk_fb_put_cstring(fb, "NULL");
  26922. return;
  26923. }
  26924. p = DUK_HSTRING_GET_DATA(h);
  26925. p_end = p + DUK_HSTRING_GET_BYTELEN(h);
  26926. if (p_end > p && p[0] == DUK_ASC_UNDERSCORE) {
  26927. /* if property key begins with underscore, encode it with
  26928. * forced quotes (e.g. "_Foo") to distinguish it from encoded
  26929. * internal properties (e.g. \xffBar -> _Bar).
  26930. */
  26931. quotes = 1;
  26932. }
  26933. if (quotes) {
  26934. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_DOUBLEQUOTE);
  26935. }
  26936. while (p < p_end) {
  26937. duk_uint8_t ch = *p++;
  26938. /* two special escapes: '\' and '"', other printables as is */
  26939. if (ch == '\\') {
  26940. duk_fb_sprintf(fb, "\\\\");
  26941. } else if (ch == '"') {
  26942. duk_fb_sprintf(fb, "\\\"");
  26943. } else if (ch >= 0x20 && ch <= 0x7e) {
  26944. duk_fb_put_byte(fb, ch);
  26945. } else if (ch == 0xff && !quotes) {
  26946. /* encode \xffBar as _Bar if no quotes are applied, this is for
  26947. * readable internal keys.
  26948. */
  26949. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_UNDERSCORE);
  26950. } else {
  26951. duk_fb_sprintf(fb, "\\x%02lx", (unsigned long) ch);
  26952. }
  26953. }
  26954. if (quotes) {
  26955. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_DOUBLEQUOTE);
  26956. }
  26957. #ifdef DUK_USE_REFERENCE_COUNTING
  26958. /* XXX: limit to quoted strings only, to save keys from being cluttered? */
  26959. duk_fb_sprintf(fb, "/%lu", (unsigned long) DUK_HEAPHDR_GET_REFCOUNT(&h->hdr));
  26960. #endif
  26961. }
  26962. #ifdef DUK__COMMA
  26963. #undef DUK__COMMA
  26964. #endif
  26965. #define DUK__COMMA() do { \
  26966. if (first) { \
  26967. first = 0; \
  26968. } else { \
  26969. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_COMMA); \
  26970. } \
  26971. } while (0)
  26972. DUK_LOCAL void duk__print_hobject(duk__dprint_state *st, duk_hobject *h) {
  26973. duk_fixedbuffer *fb = st->fb;
  26974. duk_uint_fast32_t i;
  26975. duk_tval *tv;
  26976. duk_hstring *key;
  26977. duk_bool_t first = 1;
  26978. const char *brace1 = "{";
  26979. const char *brace2 = "}";
  26980. duk_bool_t pushed_loopstack = 0;
  26981. if (duk_fb_is_full(fb)) {
  26982. return;
  26983. }
  26984. duk__print_shared_heaphdr(st, &h->hdr);
  26985. if (h && DUK_HOBJECT_HAS_ARRAY_PART(h)) {
  26986. brace1 = "[";
  26987. brace2 = "]";
  26988. }
  26989. if (!h) {
  26990. duk_fb_put_cstring(fb, "NULL");
  26991. goto finished;
  26992. }
  26993. if (st->depth >= st->depth_limit) {
  26994. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
  26995. duk_fb_sprintf(fb, "%sobject/compiledfunction %p%s", (const char *) brace1, (void *) h, (const char *) brace2);
  26996. } else if (DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  26997. duk_fb_sprintf(fb, "%sobject/nativefunction %p%s", (const char *) brace1, (void *) h, (const char *) brace2);
  26998. } else if (DUK_HOBJECT_IS_THREAD(h)) {
  26999. duk_fb_sprintf(fb, "%sobject/thread %p%s", (const char *) brace1, (void *) h, (const char *) brace2);
  27000. } else {
  27001. duk_fb_sprintf(fb, "%sobject %p%s", (const char *) brace1, (void *) h, (const char *) brace2); /* may be NULL */
  27002. }
  27003. return;
  27004. }
  27005. for (i = 0; i < (duk_uint_fast32_t) st->loop_stack_index; i++) {
  27006. if (st->loop_stack[i] == h) {
  27007. duk_fb_sprintf(fb, "%sLOOP:%p%s", (const char *) brace1, (void *) h, (const char *) brace2);
  27008. return;
  27009. }
  27010. }
  27011. /* after this, return paths should 'goto finished' for decrement */
  27012. st->depth++;
  27013. if (st->loop_stack_index >= st->loop_stack_limit) {
  27014. duk_fb_sprintf(fb, "%sOUT-OF-LOOP-STACK%s", (const char *) brace1, (const char *) brace2);
  27015. goto finished;
  27016. }
  27017. st->loop_stack[st->loop_stack_index++] = h;
  27018. pushed_loopstack = 1;
  27019. /*
  27020. * Notation: double underscore used for internal properties which are not
  27021. * stored in the property allocation (e.g. '__valstack').
  27022. */
  27023. duk_fb_put_cstring(fb, brace1);
  27024. if (DUK_HOBJECT_GET_PROPS(NULL, h)) {
  27025. duk_uint32_t a_limit;
  27026. a_limit = DUK_HOBJECT_GET_ASIZE(h);
  27027. if (st->internal) {
  27028. /* dump all allocated entries, unused entries print as 'unused',
  27029. * note that these may extend beyond current 'length' and look
  27030. * a bit funny.
  27031. */
  27032. } else {
  27033. /* leave out trailing 'unused' elements */
  27034. while (a_limit > 0) {
  27035. tv = DUK_HOBJECT_A_GET_VALUE_PTR(NULL, h, a_limit - 1);
  27036. if (!DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  27037. break;
  27038. }
  27039. a_limit--;
  27040. }
  27041. }
  27042. for (i = 0; i < a_limit; i++) {
  27043. tv = DUK_HOBJECT_A_GET_VALUE_PTR(NULL, h, i);
  27044. DUK__COMMA();
  27045. duk__print_tval(st, tv);
  27046. }
  27047. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(h); i++) {
  27048. key = DUK_HOBJECT_E_GET_KEY(NULL, h, i);
  27049. if (!key) {
  27050. continue;
  27051. }
  27052. if (!st->internal &&
  27053. DUK_HSTRING_GET_BYTELEN(key) > 0 &&
  27054. DUK_HSTRING_GET_DATA(key)[0] == 0xff) {
  27055. /* XXX: use DUK_HSTRING_FLAG_INTERNAL? */
  27056. continue;
  27057. }
  27058. DUK__COMMA();
  27059. duk__print_hstring(st, key, 0);
  27060. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_COLON);
  27061. if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(NULL, h, i)) {
  27062. duk_fb_sprintf(fb, "[get:%p,set:%p]",
  27063. (void *) DUK_HOBJECT_E_GET_VALUE(NULL, h, i).a.get,
  27064. (void *) DUK_HOBJECT_E_GET_VALUE(NULL, h, i).a.set);
  27065. } else {
  27066. tv = &DUK_HOBJECT_E_GET_VALUE(NULL, h, i).v;
  27067. duk__print_tval(st, tv);
  27068. }
  27069. if (st->heavy) {
  27070. duk_fb_sprintf(fb, "<%02lx>", (unsigned long) DUK_HOBJECT_E_GET_FLAGS(NULL, h, i));
  27071. }
  27072. }
  27073. }
  27074. if (st->internal) {
  27075. if (DUK_HOBJECT_HAS_EXTENSIBLE(h)) {
  27076. DUK__COMMA(); duk_fb_sprintf(fb, "__extensible:true");
  27077. } else {
  27078. ;
  27079. }
  27080. if (DUK_HOBJECT_HAS_CONSTRUCTABLE(h)) {
  27081. DUK__COMMA(); duk_fb_sprintf(fb, "__constructable:true");
  27082. } else {
  27083. ;
  27084. }
  27085. if (DUK_HOBJECT_HAS_BOUND(h)) {
  27086. DUK__COMMA(); duk_fb_sprintf(fb, "__bound:true");
  27087. } else {
  27088. ;
  27089. }
  27090. if (DUK_HOBJECT_HAS_COMPILEDFUNCTION(h)) {
  27091. DUK__COMMA(); duk_fb_sprintf(fb, "__compiledfunction:true");
  27092. } else {
  27093. ;
  27094. }
  27095. if (DUK_HOBJECT_HAS_NATIVEFUNCTION(h)) {
  27096. DUK__COMMA(); duk_fb_sprintf(fb, "__nativefunction:true");
  27097. } else {
  27098. ;
  27099. }
  27100. if (DUK_HOBJECT_HAS_THREAD(h)) {
  27101. DUK__COMMA(); duk_fb_sprintf(fb, "__thread:true");
  27102. } else {
  27103. ;
  27104. }
  27105. if (DUK_HOBJECT_HAS_ARRAY_PART(h)) {
  27106. DUK__COMMA(); duk_fb_sprintf(fb, "__array_part:true");
  27107. } else {
  27108. ;
  27109. }
  27110. if (DUK_HOBJECT_HAS_STRICT(h)) {
  27111. DUK__COMMA(); duk_fb_sprintf(fb, "__strict:true");
  27112. } else {
  27113. ;
  27114. }
  27115. if (DUK_HOBJECT_HAS_NEWENV(h)) {
  27116. DUK__COMMA(); duk_fb_sprintf(fb, "__newenv:true");
  27117. } else {
  27118. ;
  27119. }
  27120. if (DUK_HOBJECT_HAS_NAMEBINDING(h)) {
  27121. DUK__COMMA(); duk_fb_sprintf(fb, "__namebinding:true");
  27122. } else {
  27123. ;
  27124. }
  27125. if (DUK_HOBJECT_HAS_CREATEARGS(h)) {
  27126. DUK__COMMA(); duk_fb_sprintf(fb, "__createargs:true");
  27127. } else {
  27128. ;
  27129. }
  27130. if (DUK_HOBJECT_HAS_ENVRECCLOSED(h)) {
  27131. DUK__COMMA(); duk_fb_sprintf(fb, "__envrecclosed:true");
  27132. } else {
  27133. ;
  27134. }
  27135. if (DUK_HOBJECT_HAS_EXOTIC_ARRAY(h)) {
  27136. DUK__COMMA(); duk_fb_sprintf(fb, "__special_array:true");
  27137. } else {
  27138. ;
  27139. }
  27140. if (DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(h)) {
  27141. DUK__COMMA(); duk_fb_sprintf(fb, "__special_stringobj:true");
  27142. } else {
  27143. ;
  27144. }
  27145. if (DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(h)) {
  27146. DUK__COMMA(); duk_fb_sprintf(fb, "__special_arguments:true");
  27147. } else {
  27148. ;
  27149. }
  27150. if (DUK_HOBJECT_HAS_EXOTIC_DUKFUNC(h)) {
  27151. DUK__COMMA(); duk_fb_sprintf(fb, "__special_dukfunc:true");
  27152. } else {
  27153. ;
  27154. }
  27155. if (DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(h)) {
  27156. DUK__COMMA(); duk_fb_sprintf(fb, "__special_bufferobj:true");
  27157. } else {
  27158. ;
  27159. }
  27160. if (DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(h)) {
  27161. DUK__COMMA(); duk_fb_sprintf(fb, "__special_proxyobj:true");
  27162. } else {
  27163. ;
  27164. }
  27165. }
  27166. if (st->internal && DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
  27167. duk_hcompiledfunction *f = (duk_hcompiledfunction *) h;
  27168. DUK__COMMA(); duk_fb_put_cstring(fb, "__data:");
  27169. duk__print_hbuffer(st, (duk_hbuffer *) DUK_HCOMPILEDFUNCTION_GET_DATA(NULL, f));
  27170. DUK__COMMA(); duk_fb_sprintf(fb, "__nregs:%ld", (long) f->nregs);
  27171. DUK__COMMA(); duk_fb_sprintf(fb, "__nargs:%ld", (long) f->nargs);
  27172. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  27173. DUK__COMMA(); duk_fb_sprintf(fb, "__start_line:%ld", (long) f->start_line);
  27174. DUK__COMMA(); duk_fb_sprintf(fb, "__end_line:%ld", (long) f->end_line);
  27175. #endif
  27176. DUK__COMMA(); duk_fb_put_cstring(fb, "__data:");
  27177. duk__print_hbuffer(st, (duk_hbuffer *) DUK_HCOMPILEDFUNCTION_GET_DATA(NULL, f));
  27178. } else if (st->internal && DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  27179. duk_hnativefunction *f = (duk_hnativefunction *) h;
  27180. DUK__COMMA(); duk_fb_sprintf(fb, "__func:");
  27181. duk_fb_put_funcptr(fb, (duk_uint8_t *) &f->func, sizeof(f->func));
  27182. DUK__COMMA(); duk_fb_sprintf(fb, "__nargs:%ld", (long) f->nargs);
  27183. } else if (st->internal && DUK_HOBJECT_IS_THREAD(h)) {
  27184. duk_hthread *t = (duk_hthread *) h;
  27185. DUK__COMMA(); duk_fb_sprintf(fb, "__strict:%ld", (long) t->strict);
  27186. DUK__COMMA(); duk_fb_sprintf(fb, "__state:%ld", (long) t->state);
  27187. DUK__COMMA(); duk_fb_sprintf(fb, "__unused1:%ld", (long) t->unused1);
  27188. DUK__COMMA(); duk_fb_sprintf(fb, "__unused2:%ld", (long) t->unused2);
  27189. DUK__COMMA(); duk_fb_sprintf(fb, "__valstack_max:%ld", (long) t->valstack_max);
  27190. DUK__COMMA(); duk_fb_sprintf(fb, "__callstack_max:%ld", (long) t->callstack_max);
  27191. DUK__COMMA(); duk_fb_sprintf(fb, "__catchstack_max:%ld", (long) t->catchstack_max);
  27192. DUK__COMMA(); duk_fb_sprintf(fb, "__valstack:%p", (void *) t->valstack);
  27193. DUK__COMMA(); duk_fb_sprintf(fb, "__valstack_end:%p/%ld", (void *) t->valstack_end, (long) (t->valstack_end - t->valstack));
  27194. DUK__COMMA(); duk_fb_sprintf(fb, "__valstack_bottom:%p/%ld", (void *) t->valstack_bottom, (long) (t->valstack_bottom - t->valstack));
  27195. DUK__COMMA(); duk_fb_sprintf(fb, "__valstack_top:%p/%ld", (void *) t->valstack_top, (long) (t->valstack_top - t->valstack));
  27196. DUK__COMMA(); duk_fb_sprintf(fb, "__catchstack:%p", (void *) t->catchstack);
  27197. DUK__COMMA(); duk_fb_sprintf(fb, "__catchstack_size:%ld", (long) t->catchstack_size);
  27198. DUK__COMMA(); duk_fb_sprintf(fb, "__catchstack_top:%ld", (long) t->catchstack_top);
  27199. DUK__COMMA(); duk_fb_sprintf(fb, "__resumer:"); duk__print_hobject(st, (duk_hobject *) t->resumer);
  27200. /* XXX: print built-ins array? */
  27201. }
  27202. #ifdef DUK_USE_REFERENCE_COUNTING
  27203. if (st->internal) {
  27204. DUK__COMMA(); duk_fb_sprintf(fb, "__refcount:%lu", (unsigned long) DUK_HEAPHDR_GET_REFCOUNT((duk_heaphdr *) h));
  27205. }
  27206. #endif
  27207. if (st->internal) {
  27208. DUK__COMMA(); duk_fb_sprintf(fb, "__class:%ld", (long) DUK_HOBJECT_GET_CLASS_NUMBER(h));
  27209. }
  27210. /* prototype should be last, for readability */
  27211. if (st->follow_proto && DUK_HOBJECT_GET_PROTOTYPE(NULL, h)) {
  27212. DUK__COMMA(); duk_fb_put_cstring(fb, "__prototype:"); duk__print_hobject(st, DUK_HOBJECT_GET_PROTOTYPE(NULL, h));
  27213. }
  27214. duk_fb_put_cstring(fb, brace2);
  27215. #if defined(DUK_USE_HOBJECT_HASH_PART)
  27216. if (st->heavy && DUK_HOBJECT_GET_HSIZE(h) > 0) {
  27217. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_LANGLE);
  27218. for (i = 0; i < DUK_HOBJECT_GET_HSIZE(h); i++) {
  27219. duk_uint_t h_idx = DUK_HOBJECT_H_GET_INDEX(NULL, h, i);
  27220. if (i > 0) {
  27221. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_COMMA);
  27222. }
  27223. if (h_idx == DUK_HOBJECT_HASHIDX_UNUSED) {
  27224. duk_fb_sprintf(fb, "u");
  27225. } else if (h_idx == DUK_HOBJECT_HASHIDX_DELETED) {
  27226. duk_fb_sprintf(fb, "d");
  27227. } else {
  27228. duk_fb_sprintf(fb, "%ld", (long) h_idx);
  27229. }
  27230. }
  27231. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_RANGLE);
  27232. }
  27233. #endif
  27234. finished:
  27235. st->depth--;
  27236. if (pushed_loopstack) {
  27237. st->loop_stack_index--;
  27238. st->loop_stack[st->loop_stack_index] = NULL;
  27239. }
  27240. }
  27241. #undef DUK__COMMA
  27242. DUK_LOCAL void duk__print_hbuffer(duk__dprint_state *st, duk_hbuffer *h) {
  27243. duk_fixedbuffer *fb = st->fb;
  27244. duk_size_t i, n;
  27245. duk_uint8_t *p;
  27246. if (duk_fb_is_full(fb)) {
  27247. return;
  27248. }
  27249. /* terminal type: no depth check */
  27250. if (!h) {
  27251. duk_fb_put_cstring(fb, "NULL");
  27252. return;
  27253. }
  27254. if (DUK_HBUFFER_HAS_DYNAMIC(h)) {
  27255. duk_hbuffer_dynamic *g = (duk_hbuffer_dynamic *) h;
  27256. duk_fb_sprintf(fb, "buffer:dynamic:%p:%ld:%ld",
  27257. (void *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(NULL, g),
  27258. (long) DUK_HBUFFER_DYNAMIC_GET_SIZE(g),
  27259. (long) DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(g));
  27260. } else {
  27261. duk_fb_sprintf(fb, "buffer:fixed:%ld", (long) DUK_HBUFFER_GET_SIZE(h));
  27262. }
  27263. #ifdef DUK_USE_REFERENCE_COUNTING
  27264. duk_fb_sprintf(fb, "/%lu", (unsigned long) DUK_HEAPHDR_GET_REFCOUNT(&h->hdr));
  27265. #endif
  27266. if (st->hexdump) {
  27267. duk_fb_sprintf(fb, "=[");
  27268. n = DUK_HBUFFER_GET_SIZE(h);
  27269. p = (duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(NULL, h);
  27270. for (i = 0; i < n; i++) {
  27271. duk_fb_sprintf(fb, "%02lx", (unsigned long) p[i]);
  27272. }
  27273. duk_fb_sprintf(fb, "]");
  27274. }
  27275. }
  27276. DUK_LOCAL void duk__print_heaphdr(duk__dprint_state *st, duk_heaphdr *h) {
  27277. duk_fixedbuffer *fb = st->fb;
  27278. if (duk_fb_is_full(fb)) {
  27279. return;
  27280. }
  27281. if (!h) {
  27282. duk_fb_put_cstring(fb, "NULL");
  27283. return;
  27284. }
  27285. switch (DUK_HEAPHDR_GET_TYPE(h)) {
  27286. case DUK_HTYPE_STRING:
  27287. duk__print_hstring(st, (duk_hstring *) h, 1);
  27288. break;
  27289. case DUK_HTYPE_OBJECT:
  27290. duk__print_hobject(st, (duk_hobject *) h);
  27291. break;
  27292. case DUK_HTYPE_BUFFER:
  27293. duk__print_hbuffer(st, (duk_hbuffer *) h);
  27294. break;
  27295. default:
  27296. duk_fb_sprintf(fb, "[unknown htype %ld]", (long) DUK_HEAPHDR_GET_TYPE(h));
  27297. break;
  27298. }
  27299. }
  27300. DUK_LOCAL void duk__print_tval(duk__dprint_state *st, duk_tval *tv) {
  27301. duk_fixedbuffer *fb = st->fb;
  27302. if (duk_fb_is_full(fb)) {
  27303. return;
  27304. }
  27305. /* depth check is done when printing an actual type */
  27306. if (st->heavy) {
  27307. duk_fb_sprintf(fb, "(%p)", (void *) tv);
  27308. }
  27309. if (!tv) {
  27310. duk_fb_put_cstring(fb, "NULL");
  27311. return;
  27312. }
  27313. if (st->binary) {
  27314. duk_size_t i;
  27315. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_LBRACKET);
  27316. for (i = 0; i < (duk_size_t) sizeof(*tv); i++) {
  27317. duk_fb_sprintf(fb, "%02lx", (unsigned long) ((duk_uint8_t *)tv)[i]);
  27318. }
  27319. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_RBRACKET);
  27320. }
  27321. if (st->heavy) {
  27322. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_LANGLE);
  27323. }
  27324. switch (DUK_TVAL_GET_TAG(tv)) {
  27325. case DUK_TAG_UNDEFINED: {
  27326. if (DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  27327. duk_fb_put_cstring(fb, "unused");
  27328. } else {
  27329. duk_fb_put_cstring(fb, "undefined");
  27330. }
  27331. break;
  27332. }
  27333. case DUK_TAG_NULL: {
  27334. duk_fb_put_cstring(fb, "null");
  27335. break;
  27336. }
  27337. case DUK_TAG_BOOLEAN: {
  27338. duk_fb_put_cstring(fb, DUK_TVAL_GET_BOOLEAN(tv) ? "true" : "false");
  27339. break;
  27340. }
  27341. case DUK_TAG_STRING: {
  27342. /* Note: string is a terminal heap object, so no depth check here */
  27343. duk__print_hstring(st, DUK_TVAL_GET_STRING(tv), 1);
  27344. break;
  27345. }
  27346. case DUK_TAG_OBJECT: {
  27347. duk__print_hobject(st, DUK_TVAL_GET_OBJECT(tv));
  27348. break;
  27349. }
  27350. case DUK_TAG_BUFFER: {
  27351. duk__print_hbuffer(st, DUK_TVAL_GET_BUFFER(tv));
  27352. break;
  27353. }
  27354. case DUK_TAG_POINTER: {
  27355. duk_fb_sprintf(fb, "pointer:%p", (void *) DUK_TVAL_GET_POINTER(tv));
  27356. break;
  27357. }
  27358. case DUK_TAG_LIGHTFUNC: {
  27359. duk_c_function func;
  27360. duk_small_uint_t lf_flags;
  27361. DUK_TVAL_GET_LIGHTFUNC(tv, func, lf_flags);
  27362. duk_fb_sprintf(fb, "lightfunc:");
  27363. duk_fb_put_funcptr(fb, (duk_uint8_t *) &func, sizeof(func));
  27364. duk_fb_sprintf(fb, ":%04lx", (long) lf_flags);
  27365. break;
  27366. }
  27367. #if defined(DUK_USE_FASTINT)
  27368. case DUK_TAG_FASTINT:
  27369. #endif
  27370. default: {
  27371. /* IEEE double is approximately 16 decimal digits; print a couple extra */
  27372. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  27373. duk_fb_sprintf(fb, "%.18g", (double) DUK_TVAL_GET_NUMBER(tv));
  27374. break;
  27375. }
  27376. }
  27377. if (st->heavy) {
  27378. duk_fb_put_byte(fb, (duk_uint8_t) DUK_ASC_RANGLE);
  27379. }
  27380. }
  27381. DUK_LOCAL void duk__print_instr(duk__dprint_state *st, duk_instr_t ins) {
  27382. duk_fixedbuffer *fb = st->fb;
  27383. duk_small_int_t op;
  27384. const char *op_name;
  27385. const char *extraop_name;
  27386. op = (duk_small_int_t) DUK_DEC_OP(ins);
  27387. op_name = duk__bc_optab[op];
  27388. /* XXX: option to fix opcode length so it lines up nicely */
  27389. if (op == DUK_OP_EXTRA) {
  27390. extraop_name = duk__bc_extraoptab[DUK_DEC_A(ins)];
  27391. duk_fb_sprintf(fb, "%s %ld, %ld",
  27392. (const char *) extraop_name, (long) DUK_DEC_B(ins), (long) DUK_DEC_C(ins));
  27393. } else if (op == DUK_OP_JUMP) {
  27394. duk_int_t diff1 = DUK_DEC_ABC(ins) - DUK_BC_JUMP_BIAS; /* from next pc */
  27395. duk_int_t diff2 = diff1 + 1; /* from curr pc */
  27396. duk_fb_sprintf(fb, "%s %ld (to pc%c%ld)",
  27397. (const char *) op_name, (long) diff1,
  27398. (int) (diff2 >= 0 ? '+' : '-'), /* char format: use int */
  27399. (long) (diff2 >= 0 ? diff2 : -diff2));
  27400. } else {
  27401. duk_fb_sprintf(fb, "%s %ld, %ld, %ld",
  27402. (const char *) op_name, (long) DUK_DEC_A(ins),
  27403. (long) DUK_DEC_B(ins), (long) DUK_DEC_C(ins));
  27404. }
  27405. }
  27406. DUK_LOCAL void duk__print_opcode(duk__dprint_state *st, duk_small_int_t opcode) {
  27407. duk_fixedbuffer *fb = st->fb;
  27408. if (opcode < DUK_BC_OP_MIN || opcode > DUK_BC_OP_MAX) {
  27409. duk_fb_sprintf(fb, "?(%ld)", (long) opcode);
  27410. } else {
  27411. duk_fb_sprintf(fb, "%s", (const char *) duk__bc_optab[opcode]);
  27412. }
  27413. }
  27414. DUK_INTERNAL duk_int_t duk_debug_vsnprintf(char *str, duk_size_t size, const char *format, va_list ap) {
  27415. duk_fixedbuffer fb;
  27416. const char *p = format;
  27417. const char *p_end = p + DUK_STRLEN(format);
  27418. duk_int_t retval;
  27419. DUK_MEMZERO(&fb, sizeof(fb));
  27420. fb.buffer = (duk_uint8_t *) str;
  27421. fb.length = size;
  27422. fb.offset = 0;
  27423. fb.truncated = 0;
  27424. while (p < p_end) {
  27425. char ch = *p++;
  27426. const char *p_begfmt = NULL;
  27427. duk_bool_t got_exclamation = 0;
  27428. duk_bool_t got_long = 0; /* %lf, %ld etc */
  27429. duk__dprint_state st;
  27430. if (ch != DUK_ASC_PERCENT) {
  27431. duk_fb_put_byte(&fb, (duk_uint8_t) ch);
  27432. continue;
  27433. }
  27434. /*
  27435. * Format tag parsing. Since we don't understand all the
  27436. * possible format tags allowed, we just scan for a terminating
  27437. * specifier and keep track of relevant modifiers that we do
  27438. * understand. See man 3 printf.
  27439. */
  27440. DUK_MEMZERO(&st, sizeof(st));
  27441. st.fb = &fb;
  27442. st.depth = 0;
  27443. st.depth_limit = 1;
  27444. st.loop_stack_index = 0;
  27445. st.loop_stack_limit = DUK__LOOP_STACK_DEPTH;
  27446. p_begfmt = p - 1;
  27447. while (p < p_end) {
  27448. ch = *p++;
  27449. if (ch == DUK_ASC_STAR) {
  27450. /* unsupported: would consume multiple args */
  27451. goto error;
  27452. } else if (ch == DUK_ASC_PERCENT) {
  27453. duk_fb_put_byte(&fb, (duk_uint8_t) DUK_ASC_PERCENT);
  27454. break;
  27455. } else if (ch == DUK_ASC_EXCLAMATION) {
  27456. got_exclamation = 1;
  27457. } else if (!got_exclamation && ch == DUK_ASC_LC_L) {
  27458. got_long = 1;
  27459. } else if (got_exclamation && ch == DUK_ASC_LC_D) {
  27460. st.depth_limit = DUK__DEEP_DEPTH_LIMIT;
  27461. } else if (got_exclamation && ch == DUK_ASC_LC_P) {
  27462. st.follow_proto = 1;
  27463. } else if (got_exclamation && ch == DUK_ASC_LC_I) {
  27464. st.internal = 1;
  27465. } else if (got_exclamation && ch == DUK_ASC_LC_X) {
  27466. st.hexdump = 1;
  27467. } else if (got_exclamation && ch == DUK_ASC_LC_H) {
  27468. st.heavy = 1;
  27469. } else if (got_exclamation && ch == DUK_ASC_ATSIGN) {
  27470. st.pointer = 1;
  27471. } else if (got_exclamation && ch == DUK_ASC_HASH) {
  27472. st.binary = 1;
  27473. } else if (got_exclamation && ch == DUK_ASC_UC_T) {
  27474. duk_tval *t = va_arg(ap, duk_tval *);
  27475. if (st.pointer && !st.heavy) {
  27476. duk_fb_sprintf(&fb, "(%p)", (void *) t);
  27477. }
  27478. duk__print_tval(&st, t);
  27479. break;
  27480. } else if (got_exclamation && ch == DUK_ASC_UC_O) {
  27481. duk_heaphdr *t = va_arg(ap, duk_heaphdr *);
  27482. if (st.pointer && !st.heavy) {
  27483. duk_fb_sprintf(&fb, "(%p)", (void *) t);
  27484. }
  27485. duk__print_heaphdr(&st, t);
  27486. break;
  27487. } else if (got_exclamation && ch == DUK_ASC_UC_I) {
  27488. duk_instr_t t = va_arg(ap, duk_instr_t);
  27489. duk__print_instr(&st, t);
  27490. break;
  27491. } else if (got_exclamation && ch == DUK_ASC_UC_C) {
  27492. long t = va_arg(ap, long);
  27493. duk__print_opcode(&st, (duk_small_int_t) t);
  27494. break;
  27495. } else if (!got_exclamation && strchr(DUK__ALLOWED_STANDARD_SPECIFIERS, (int) ch)) {
  27496. char fmtbuf[DUK__MAX_FORMAT_TAG_LENGTH];
  27497. duk_size_t fmtlen;
  27498. DUK_ASSERT(p >= p_begfmt);
  27499. fmtlen = (duk_size_t) (p - p_begfmt);
  27500. if (fmtlen >= sizeof(fmtbuf)) {
  27501. /* format is too large, abort */
  27502. goto error;
  27503. }
  27504. DUK_MEMZERO(fmtbuf, sizeof(fmtbuf));
  27505. DUK_MEMCPY(fmtbuf, p_begfmt, fmtlen);
  27506. /* assume exactly 1 arg, which is why '*' is forbidden; arg size still
  27507. * depends on type though.
  27508. */
  27509. if (ch == DUK_ASC_LC_F || ch == DUK_ASC_LC_G || ch == DUK_ASC_LC_E) {
  27510. /* %f and %lf both consume a 'long' */
  27511. double arg = va_arg(ap, double);
  27512. duk_fb_sprintf(&fb, fmtbuf, arg);
  27513. } else if (ch == DUK_ASC_LC_D && got_long) {
  27514. /* %ld */
  27515. long arg = va_arg(ap, long);
  27516. duk_fb_sprintf(&fb, fmtbuf, arg);
  27517. } else if (ch == DUK_ASC_LC_D) {
  27518. /* %d; only 16 bits are guaranteed */
  27519. int arg = va_arg(ap, int);
  27520. duk_fb_sprintf(&fb, fmtbuf, arg);
  27521. } else if (ch == DUK_ASC_LC_U && got_long) {
  27522. /* %lu */
  27523. unsigned long arg = va_arg(ap, unsigned long);
  27524. duk_fb_sprintf(&fb, fmtbuf, arg);
  27525. } else if (ch == DUK_ASC_LC_U) {
  27526. /* %u; only 16 bits are guaranteed */
  27527. unsigned int arg = va_arg(ap, unsigned int);
  27528. duk_fb_sprintf(&fb, fmtbuf, arg);
  27529. } else if (ch == DUK_ASC_LC_X && got_long) {
  27530. /* %lx */
  27531. unsigned long arg = va_arg(ap, unsigned long);
  27532. duk_fb_sprintf(&fb, fmtbuf, arg);
  27533. } else if (ch == DUK_ASC_LC_X) {
  27534. /* %x; only 16 bits are guaranteed */
  27535. unsigned int arg = va_arg(ap, unsigned int);
  27536. duk_fb_sprintf(&fb, fmtbuf, arg);
  27537. } else if (ch == DUK_ASC_LC_S) {
  27538. /* %s */
  27539. const char *arg = va_arg(ap, const char *);
  27540. if (arg == NULL) {
  27541. /* '%s' and NULL is not portable, so special case
  27542. * it for debug printing.
  27543. */
  27544. duk_fb_sprintf(&fb, "NULL");
  27545. } else {
  27546. duk_fb_sprintf(&fb, fmtbuf, arg);
  27547. }
  27548. } else if (ch == DUK_ASC_LC_P) {
  27549. /* %p */
  27550. void *arg = va_arg(ap, void *);
  27551. if (arg == NULL) {
  27552. /* '%p' and NULL is portable, but special case it
  27553. * anyway to get a standard NULL marker in logs.
  27554. */
  27555. duk_fb_sprintf(&fb, "NULL");
  27556. } else {
  27557. duk_fb_sprintf(&fb, fmtbuf, arg);
  27558. }
  27559. } else if (ch == DUK_ASC_LC_C) {
  27560. /* '%c', passed concretely as int */
  27561. int arg = va_arg(ap, int);
  27562. duk_fb_sprintf(&fb, fmtbuf, arg);
  27563. } else {
  27564. /* Should not happen. */
  27565. duk_fb_sprintf(&fb, "INVALID-FORMAT(%s)", (const char *) fmtbuf);
  27566. }
  27567. break;
  27568. } else {
  27569. /* ignore */
  27570. }
  27571. }
  27572. }
  27573. goto done;
  27574. error:
  27575. duk_fb_put_cstring(&fb, "FMTERR");
  27576. /* fall through */
  27577. done:
  27578. retval = (duk_int_t) fb.offset;
  27579. duk_fb_put_byte(&fb, (duk_uint8_t) 0);
  27580. /* return total chars written excluding terminator */
  27581. return retval;
  27582. }
  27583. #if 0 /*unused*/
  27584. DUK_INTERNAL duk_int_t duk_debug_snprintf(char *str, duk_size_t size, const char *format, ...) {
  27585. duk_int_t retval;
  27586. va_list ap;
  27587. va_start(ap, format);
  27588. retval = duk_debug_vsnprintf(str, size, format, ap);
  27589. va_end(ap);
  27590. return retval;
  27591. }
  27592. #endif
  27593. /* Formatting function pointers is tricky: there is no standard pointer for
  27594. * function pointers and the size of a function pointer may depend on the
  27595. * specific pointer type. This helper formats a function pointer based on
  27596. * its memory layout to get something useful on most platforms.
  27597. */
  27598. DUK_INTERNAL void duk_debug_format_funcptr(char *buf, duk_size_t buf_size, duk_uint8_t *fptr, duk_size_t fptr_size) {
  27599. duk_size_t i;
  27600. duk_uint8_t *p = (duk_uint8_t *) buf;
  27601. duk_uint8_t *p_end = (duk_uint8_t *) (buf + buf_size - 1);
  27602. DUK_MEMZERO(buf, buf_size);
  27603. for (i = 0; i < fptr_size; i++) {
  27604. duk_int_t left = (duk_int_t) (p_end - p);
  27605. duk_uint8_t ch;
  27606. if (left <= 0) {
  27607. break;
  27608. }
  27609. /* Quite approximate but should be useful for little and big endian. */
  27610. #ifdef DUK_USE_INTEGER_BE
  27611. ch = fptr[i];
  27612. #else
  27613. ch = fptr[fptr_size - 1 - i];
  27614. #endif
  27615. p += DUK_SNPRINTF((char *) p, left, "%02lx", (unsigned long) ch);
  27616. }
  27617. }
  27618. #endif /* DUK_USE_DEBUG */
  27619. #line 1 "duk_debugger.c"
  27620. /*
  27621. * Duktape debugger
  27622. */
  27623. /* include removed: duk_internal.h */
  27624. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  27625. /*
  27626. * Helper structs
  27627. */
  27628. typedef union {
  27629. void *p;
  27630. duk_uint_t b[1];
  27631. /* Use b[] to access the size of the union, which is strictly not
  27632. * correct. Can't use fixed size unless there's feature detection
  27633. * for pointer byte size.
  27634. */
  27635. } duk__ptr_union;
  27636. /*
  27637. * Detach handling
  27638. */
  27639. #define DUK__SET_CONN_BROKEN(thr) do { \
  27640. /* For now shared handler is fine. */ \
  27641. duk_debug_do_detach((thr)->heap); \
  27642. } while (0)
  27643. DUK_INTERNAL void duk_debug_do_detach(duk_heap *heap) {
  27644. /* Can be called muliple times with no harm. */
  27645. heap->dbg_read_cb = NULL;
  27646. heap->dbg_write_cb = NULL;
  27647. heap->dbg_peek_cb = NULL;
  27648. heap->dbg_read_flush_cb = NULL;
  27649. heap->dbg_write_flush_cb = NULL;
  27650. if (heap->dbg_detached_cb) {
  27651. heap->dbg_detached_cb(heap->dbg_udata);
  27652. }
  27653. heap->dbg_detached_cb = NULL;
  27654. heap->dbg_udata = NULL;
  27655. heap->dbg_processing = 0;
  27656. heap->dbg_paused = 0;
  27657. heap->dbg_state_dirty = 0;
  27658. heap->dbg_step_type = 0;
  27659. heap->dbg_step_thread = NULL;
  27660. heap->dbg_step_csindex = 0;
  27661. heap->dbg_step_startline = 0;
  27662. /* Ensure there are no stale active breakpoint pointers.
  27663. * Breakpoint list is currently kept - we could empty it
  27664. * here but we'd need to handle refcounts correctly, and
  27665. * we'd need a 'thr' reference for that.
  27666. *
  27667. * XXX: clear breakpoint on either attach or detach?
  27668. */
  27669. heap->dbg_breakpoints_active[0] = (duk_breakpoint *) NULL;
  27670. }
  27671. /*
  27672. * Debug connection peek and flush primitives
  27673. */
  27674. DUK_INTERNAL duk_bool_t duk_debug_read_peek(duk_hthread *thr) {
  27675. duk_heap *heap;
  27676. DUK_ASSERT(thr != NULL);
  27677. heap = thr->heap;
  27678. DUK_ASSERT(heap != NULL);
  27679. if (heap->dbg_read_cb == NULL) {
  27680. DUK_D(DUK_DPRINT("attempt to peek in detached state, return zero (= no data)"));
  27681. return 0;
  27682. }
  27683. if (heap->dbg_peek_cb == NULL) {
  27684. DUK_DD(DUK_DDPRINT("no peek callback, return zero (= no data)"));
  27685. return 0;
  27686. }
  27687. return (duk_bool_t) (heap->dbg_peek_cb(heap->dbg_udata) > 0);
  27688. }
  27689. DUK_INTERNAL void duk_debug_read_flush(duk_hthread *thr) {
  27690. duk_heap *heap;
  27691. DUK_ASSERT(thr != NULL);
  27692. heap = thr->heap;
  27693. DUK_ASSERT(heap != NULL);
  27694. if (heap->dbg_read_cb == NULL) {
  27695. DUK_D(DUK_DPRINT("attempt to read flush in detached state, ignore"));
  27696. return;
  27697. }
  27698. if (heap->dbg_read_flush_cb == NULL) {
  27699. DUK_DD(DUK_DDPRINT("no read flush callback, ignore"));
  27700. return;
  27701. }
  27702. heap->dbg_read_flush_cb(heap->dbg_udata);
  27703. }
  27704. DUK_INTERNAL void duk_debug_write_flush(duk_hthread *thr) {
  27705. duk_heap *heap;
  27706. DUK_ASSERT(thr != NULL);
  27707. heap = thr->heap;
  27708. DUK_ASSERT(heap != NULL);
  27709. if (heap->dbg_read_cb == NULL) {
  27710. DUK_D(DUK_DPRINT("attempt to write flush in detached state, ignore"));
  27711. return;
  27712. }
  27713. if (heap->dbg_write_flush_cb == NULL) {
  27714. DUK_DD(DUK_DDPRINT("no write flush callback, ignore"));
  27715. return;
  27716. }
  27717. heap->dbg_write_flush_cb(heap->dbg_udata);
  27718. }
  27719. /*
  27720. * Debug connection skip primitives
  27721. */
  27722. /* Skip fully. */
  27723. DUK_INTERNAL void duk_debug_skip_bytes(duk_hthread *thr, duk_size_t length) {
  27724. duk_uint8_t dummy[64];
  27725. duk_size_t now;
  27726. DUK_ASSERT(thr != NULL);
  27727. while (length > 0) {
  27728. now = (length > sizeof(dummy) ? sizeof(dummy) : length);
  27729. duk_debug_read_bytes(thr, dummy, now);
  27730. length -= now;
  27731. }
  27732. }
  27733. DUK_INTERNAL void duk_debug_skip_byte(duk_hthread *thr) {
  27734. DUK_ASSERT(thr != NULL);
  27735. (void) duk_debug_read_byte(thr);
  27736. }
  27737. /*
  27738. * Debug connection read primitives
  27739. */
  27740. /* Read fully. */
  27741. DUK_INTERNAL void duk_debug_read_bytes(duk_hthread *thr, duk_uint8_t *data, duk_size_t length) {
  27742. duk_heap *heap;
  27743. duk_uint8_t *p;
  27744. duk_size_t left;
  27745. duk_size_t got;
  27746. DUK_ASSERT(thr != NULL);
  27747. heap = thr->heap;
  27748. DUK_ASSERT(heap != NULL);
  27749. if (heap->dbg_read_cb == NULL) {
  27750. DUK_D(DUK_DPRINT("attempt to read %ld bytes in detached state, return zero data", (long) length));
  27751. goto fail;
  27752. }
  27753. p = data;
  27754. for (;;) {
  27755. left = (duk_size_t) ((data + length) - p);
  27756. if (left == 0) {
  27757. break;
  27758. }
  27759. DUK_ASSERT(heap->dbg_read_cb != NULL);
  27760. DUK_ASSERT(left >= 1);
  27761. #if defined(DUK_USE_DEBUGGER_TRANSPORT_TORTURE)
  27762. left = 1;
  27763. #endif
  27764. got = heap->dbg_read_cb(heap->dbg_udata, (char *) p, left);
  27765. if (got == 0 || got > left) {
  27766. DUK_D(DUK_DPRINT("connection error during read, return zero data"));
  27767. DUK__SET_CONN_BROKEN(thr);
  27768. goto fail;
  27769. }
  27770. p += got;
  27771. }
  27772. return;
  27773. fail:
  27774. DUK_MEMZERO((void *) data, (size_t) length);
  27775. }
  27776. DUK_INTERNAL duk_uint8_t duk_debug_read_byte(duk_hthread *thr) {
  27777. duk_heap *heap;
  27778. duk_size_t got;
  27779. duk_uint8_t x;
  27780. DUK_ASSERT(thr != NULL);
  27781. heap = thr->heap;
  27782. DUK_ASSERT(heap != NULL);
  27783. if (heap->dbg_read_cb == NULL) {
  27784. DUK_D(DUK_DPRINT("attempt to read 1 bytes in detached state, return zero data"));
  27785. return 0;
  27786. }
  27787. x = 0; /* just in case callback is broken and won't write 'x' */
  27788. DUK_ASSERT(heap->dbg_read_cb != NULL);
  27789. got = heap->dbg_read_cb(heap->dbg_udata, (char *) (&x), 1);
  27790. if (got != 1) {
  27791. DUK_D(DUK_DPRINT("connection error during read, return zero data"));
  27792. DUK__SET_CONN_BROKEN(thr);
  27793. return 0;
  27794. }
  27795. return x;
  27796. }
  27797. DUK_LOCAL duk_uint32_t duk__debug_read_uint32_raw(duk_hthread *thr) {
  27798. duk_uint8_t buf[4];
  27799. DUK_ASSERT(thr != NULL);
  27800. duk_debug_read_bytes(thr, buf, 4);
  27801. return ((duk_uint32_t) buf[0] << 24) |
  27802. ((duk_uint32_t) buf[1] << 16) |
  27803. ((duk_uint32_t) buf[2] << 8) |
  27804. (duk_uint32_t) buf[3];
  27805. }
  27806. DUK_LOCAL duk_uint32_t duk__debug_read_int32_raw(duk_hthread *thr) {
  27807. return (duk_int32_t) duk__debug_read_uint32_raw(thr);
  27808. }
  27809. DUK_LOCAL duk_uint16_t duk__debug_read_uint16_raw(duk_hthread *thr) {
  27810. duk_uint8_t buf[2];
  27811. DUK_ASSERT(thr != NULL);
  27812. duk_debug_read_bytes(thr, buf, 2);
  27813. return ((duk_uint16_t) buf[0] << 8) |
  27814. (duk_uint16_t) buf[1];
  27815. }
  27816. DUK_INTERNAL duk_int32_t duk_debug_read_int(duk_hthread *thr) {
  27817. duk_small_uint_t x;
  27818. duk_small_uint_t t;
  27819. DUK_ASSERT(thr != NULL);
  27820. x = duk_debug_read_byte(thr);
  27821. if (x >= 0xc0) {
  27822. t = duk_debug_read_byte(thr);
  27823. return (duk_int32_t) (((x - 0xc0) << 8) + t);
  27824. } else if (x >= 0x80) {
  27825. return (duk_int32_t) (x - 0x80);
  27826. } else if (x == 0x10) {
  27827. return (duk_int32_t) duk__debug_read_uint32_raw(thr);
  27828. }
  27829. DUK_D(DUK_DPRINT("debug connection error: failed to decode int"));
  27830. DUK__SET_CONN_BROKEN(thr);
  27831. return 0;
  27832. }
  27833. DUK_LOCAL duk_hstring *duk__debug_read_hstring_raw(duk_hthread *thr, duk_uint32_t len) {
  27834. duk_context *ctx = (duk_context *) thr;
  27835. duk_uint8_t buf[31];
  27836. duk_uint8_t *p;
  27837. if (len <= sizeof(buf)) {
  27838. duk_debug_read_bytes(thr, buf, (duk_size_t) len);
  27839. duk_push_lstring(ctx, (const char *) buf, (duk_size_t) len);
  27840. } else {
  27841. p = (duk_uint8_t *) duk_push_fixed_buffer(ctx, (duk_size_t) len);
  27842. DUK_ASSERT(p != NULL);
  27843. duk_debug_read_bytes(thr, p, (duk_size_t) len);
  27844. duk_to_string(ctx, -1);
  27845. }
  27846. return duk_require_hstring(ctx, -1);
  27847. }
  27848. DUK_INTERNAL duk_hstring *duk_debug_read_hstring(duk_hthread *thr) {
  27849. duk_context *ctx = (duk_context *) thr;
  27850. duk_small_uint_t x;
  27851. duk_uint32_t len;
  27852. DUK_ASSERT(thr != NULL);
  27853. x = duk_debug_read_byte(thr);
  27854. if (x >= 0x60 && x <= 0x7f) {
  27855. /* For short strings, use a fixed temp buffer. */
  27856. len = (duk_uint32_t) (x - 0x60);
  27857. } else if (x == 0x12) {
  27858. len = (duk_uint32_t) duk__debug_read_uint16_raw(thr);
  27859. } else if (x == 0x11) {
  27860. len = (duk_uint32_t) duk__debug_read_uint32_raw(thr);
  27861. } else {
  27862. goto fail;
  27863. }
  27864. return duk__debug_read_hstring_raw(thr, len);
  27865. fail:
  27866. DUK_D(DUK_DPRINT("debug connection error: failed to decode int"));
  27867. DUK__SET_CONN_BROKEN(thr);
  27868. duk_push_hstring_stridx(thr, DUK_STRIDX_EMPTY_STRING); /* always push some string */
  27869. return duk_require_hstring(ctx, -1);
  27870. }
  27871. DUK_LOCAL duk_hbuffer *duk__debug_read_hbuffer_raw(duk_hthread *thr, duk_uint32_t len) {
  27872. duk_context *ctx = (duk_context *) thr;
  27873. duk_uint8_t *p;
  27874. p = (duk_uint8_t *) duk_push_fixed_buffer(ctx, (duk_size_t) len);
  27875. DUK_ASSERT(p != NULL);
  27876. duk_debug_read_bytes(thr, p, (duk_size_t) len);
  27877. return duk_require_hbuffer(ctx, -1);
  27878. }
  27879. DUK_LOCAL const void *duk__debug_read_pointer_raw(duk_hthread *thr) {
  27880. duk_small_uint_t x;
  27881. volatile duk__ptr_union pu;
  27882. DUK_ASSERT(thr != NULL);
  27883. x = duk_debug_read_byte(thr);
  27884. if (x != sizeof(pu)) {
  27885. goto fail;
  27886. }
  27887. duk_debug_read_bytes(thr, (duk_uint8_t *) &pu.p, sizeof(pu));
  27888. #if defined(DUK_USE_INTEGER_LE)
  27889. duk_byteswap_bytes((duk_uint8_t *) pu.b, sizeof(pu));
  27890. #endif
  27891. return (const void *) pu.p;
  27892. fail:
  27893. DUK_D(DUK_DPRINT("debug connection error: failed to decode pointer"));
  27894. DUK__SET_CONN_BROKEN(thr);
  27895. return (const void *) NULL;
  27896. }
  27897. DUK_LOCAL duk_double_t duk__debug_read_double_raw(duk_hthread *thr) {
  27898. duk_double_union du;
  27899. DUK_ASSERT(sizeof(du.uc) == 8);
  27900. duk_debug_read_bytes(thr, (duk_uint8_t *) du.uc, sizeof(du.uc));
  27901. DUK_DBLUNION_BSWAP(&du);
  27902. return du.d;
  27903. }
  27904. DUK_INTERNAL void duk_debug_read_tval(duk_hthread *thr) {
  27905. duk_context *ctx = (duk_context *) thr;
  27906. duk_uint8_t x;
  27907. duk_uint_t t;
  27908. duk_uint32_t len;
  27909. DUK_ASSERT(thr != NULL);
  27910. x = duk_debug_read_byte(thr);
  27911. if (x >= 0xc0) {
  27912. t = (duk_uint_t) (x - 0xc0);
  27913. t = (t << 8) + duk_debug_read_byte(thr);
  27914. duk_push_uint(ctx, (duk_uint_t) t);
  27915. return;
  27916. }
  27917. if (x >= 0x80) {
  27918. duk_push_uint(ctx, (duk_uint_t) (x - 0x80));
  27919. return;
  27920. }
  27921. if (x >= 0x60) {
  27922. len = (duk_uint32_t) (x - 0x60);
  27923. duk__debug_read_hstring_raw(thr, len);
  27924. return;
  27925. }
  27926. switch (x) {
  27927. case 0x10: {
  27928. duk_int32_t i = duk__debug_read_int32_raw(thr);
  27929. duk_push_i32(ctx, i);
  27930. break;
  27931. }
  27932. case 0x11:
  27933. len = duk__debug_read_uint32_raw(thr);
  27934. duk__debug_read_hstring_raw(thr, len);
  27935. break;
  27936. case 0x12:
  27937. len = duk__debug_read_uint16_raw(thr);
  27938. duk__debug_read_hstring_raw(thr, len);
  27939. break;
  27940. case 0x13:
  27941. len = duk__debug_read_uint32_raw(thr);
  27942. duk__debug_read_hbuffer_raw(thr, len);
  27943. break;
  27944. case 0x14:
  27945. len = duk__debug_read_uint16_raw(thr);
  27946. duk__debug_read_hbuffer_raw(thr, len);
  27947. break;
  27948. case 0x15:
  27949. duk_push_unused(ctx);
  27950. break;
  27951. case 0x16:
  27952. duk_push_undefined(ctx);
  27953. break;
  27954. case 0x17:
  27955. duk_push_null(ctx);
  27956. break;
  27957. case 0x18:
  27958. duk_push_true(ctx);
  27959. break;
  27960. case 0x19:
  27961. duk_push_false(ctx);
  27962. break;
  27963. case 0x1a: {
  27964. duk_double_t d;
  27965. d = duk__debug_read_double_raw(thr);
  27966. duk_push_number(ctx, d);
  27967. break;
  27968. }
  27969. case 0x1b:
  27970. /* XXX: not needed for now, so not implemented */
  27971. DUK_D(DUK_DPRINT("reading object values unimplemented"));
  27972. goto fail;
  27973. case 0x1c: {
  27974. const void *ptr;
  27975. ptr = duk__debug_read_pointer_raw(thr);
  27976. duk_push_pointer(thr, (void *) ptr);
  27977. break;
  27978. }
  27979. case 0x1d:
  27980. /* XXX: not needed for now, so not implemented */
  27981. DUK_D(DUK_DPRINT("reading lightfunc values unimplemented"));
  27982. goto fail;
  27983. case 0x1e: {
  27984. duk_heaphdr *h;
  27985. h = (duk_heaphdr *) duk__debug_read_pointer_raw(thr);
  27986. duk_push_heapptr(thr, (void *) h);
  27987. break;
  27988. }
  27989. default:
  27990. goto fail;
  27991. }
  27992. return;
  27993. fail:
  27994. DUK_D(DUK_DPRINT("debug connection error: failed to decode tval"));
  27995. DUK__SET_CONN_BROKEN(thr);
  27996. }
  27997. /*
  27998. * Debug connection write primitives
  27999. */
  28000. /* Write fully. */
  28001. DUK_INTERNAL void duk_debug_write_bytes(duk_hthread *thr, const duk_uint8_t *data, duk_size_t length) {
  28002. duk_heap *heap;
  28003. const duk_uint8_t *p;
  28004. duk_size_t left;
  28005. duk_size_t got;
  28006. DUK_ASSERT(thr != NULL);
  28007. DUK_ASSERT(length == 0 || data != NULL);
  28008. heap = thr->heap;
  28009. DUK_ASSERT(heap != NULL);
  28010. if (heap->dbg_write_cb == NULL) {
  28011. DUK_D(DUK_DPRINT("attempt to write %ld bytes in detached state, ignore", (long) length));
  28012. return;
  28013. }
  28014. if (length == 0) {
  28015. /* Avoid doing an actual write callback with length == 0,
  28016. * because that's reserved for a write flush.
  28017. */
  28018. return;
  28019. }
  28020. DUK_ASSERT(data != NULL);
  28021. p = data;
  28022. for (;;) {
  28023. left = (duk_size_t) ((data + length) - p);
  28024. if (left == 0) {
  28025. break;
  28026. }
  28027. DUK_ASSERT(heap->dbg_write_cb != NULL);
  28028. DUK_ASSERT(left >= 1);
  28029. #if defined(DUK_USE_DEBUGGER_TRANSPORT_TORTURE)
  28030. left = 1;
  28031. #endif
  28032. got = heap->dbg_write_cb(heap->dbg_udata, (const char *) p, left);
  28033. if (got == 0 || got > left) {
  28034. DUK_D(DUK_DPRINT("connection error during write"));
  28035. DUK__SET_CONN_BROKEN(thr);
  28036. return;
  28037. }
  28038. p += got;
  28039. }
  28040. }
  28041. DUK_INTERNAL void duk_debug_write_byte(duk_hthread *thr, duk_uint8_t x) {
  28042. duk_heap *heap;
  28043. duk_size_t got;
  28044. DUK_ASSERT(thr != NULL);
  28045. heap = thr->heap;
  28046. DUK_ASSERT(heap != NULL);
  28047. if (heap->dbg_write_cb == NULL) {
  28048. DUK_D(DUK_DPRINT("attempt to write 1 bytes in detached state, ignore"));
  28049. return;
  28050. }
  28051. DUK_ASSERT(heap->dbg_write_cb != NULL);
  28052. got = heap->dbg_write_cb(heap->dbg_udata, (const char *) (&x), 1);
  28053. if (got != 1) {
  28054. DUK_D(DUK_DPRINT("connection error during write"));
  28055. DUK__SET_CONN_BROKEN(thr);
  28056. }
  28057. }
  28058. DUK_INTERNAL void duk_debug_write_unused(duk_hthread *thr) {
  28059. duk_debug_write_byte(thr, 0x15);
  28060. }
  28061. DUK_INTERNAL void duk_debug_write_undefined(duk_hthread *thr) {
  28062. duk_debug_write_byte(thr, 0x16);
  28063. }
  28064. /* Write signed 32-bit integer. */
  28065. DUK_INTERNAL void duk_debug_write_int(duk_hthread *thr, duk_int32_t x) {
  28066. duk_uint8_t buf[5];
  28067. duk_size_t len;
  28068. DUK_ASSERT(thr != NULL);
  28069. if (x >= 0 && x <= 0x3fL) {
  28070. buf[0] = (duk_uint8_t) (0x80 + x);
  28071. len = 1;
  28072. } else if (x >= 0 && x <= 0x3fffL) {
  28073. buf[0] = (duk_uint8_t) (0xc0 + (x >> 8));
  28074. buf[1] = (duk_uint8_t) (x & 0xff);
  28075. len = 2;
  28076. } else {
  28077. /* Signed integers always map to 4 bytes now. */
  28078. buf[0] = (duk_uint8_t) 0x10;
  28079. buf[1] = (duk_uint8_t) ((x >> 24) & 0xff);
  28080. buf[2] = (duk_uint8_t) ((x >> 16) & 0xff);
  28081. buf[3] = (duk_uint8_t) ((x >> 8) & 0xff);
  28082. buf[4] = (duk_uint8_t) (x & 0xff);
  28083. len = 5;
  28084. }
  28085. duk_debug_write_bytes(thr, buf, len);
  28086. }
  28087. /* Write unsigned 32-bit integer. */
  28088. DUK_INTERNAL void duk_debug_write_uint(duk_hthread *thr, duk_uint32_t x) {
  28089. /* XXX: there's currently no need to support full 32-bit unsigned
  28090. * integer range in practice. If that becomes necessary, add a new
  28091. * dvalue type or encode as an IEEE double.
  28092. */
  28093. duk_debug_write_int(thr, (duk_int32_t) x);
  28094. }
  28095. DUK_INTERNAL void duk_debug_write_strbuf(duk_hthread *thr, const char *data, duk_size_t length, duk_uint8_t marker_base) {
  28096. duk_uint8_t buf[5];
  28097. duk_size_t buflen;
  28098. DUK_ASSERT(thr != NULL);
  28099. DUK_ASSERT(length == 0 || data != NULL);
  28100. if (length <= 0x1fUL && marker_base == 0x11) {
  28101. /* For strings, special form for short lengths. */
  28102. buf[0] = (duk_uint8_t) (0x60 + length);
  28103. buflen = 1;
  28104. } else if (length <= 0xffffUL) {
  28105. buf[0] = (duk_uint8_t) (marker_base + 1);
  28106. buf[1] = (duk_uint8_t) (length >> 8);
  28107. buf[2] = (duk_uint8_t) (length & 0xff);
  28108. buflen = 3;
  28109. } else {
  28110. buf[0] = (duk_uint8_t) marker_base;
  28111. buf[1] = (duk_uint8_t) (length >> 24);
  28112. buf[2] = (duk_uint8_t) ((length >> 16) & 0xff);
  28113. buf[3] = (duk_uint8_t) ((length >> 8) & 0xff);
  28114. buf[4] = (duk_uint8_t) (length & 0xff);
  28115. buflen = 5;
  28116. }
  28117. duk_debug_write_bytes(thr, (const duk_uint8_t *) buf, buflen);
  28118. duk_debug_write_bytes(thr, (const duk_uint8_t *) data, length);
  28119. }
  28120. DUK_INTERNAL void duk_debug_write_string(duk_hthread *thr, const char *data, duk_size_t length) {
  28121. duk_debug_write_strbuf(thr, data, length, 0x11);
  28122. }
  28123. DUK_INTERNAL void duk_debug_write_cstring(duk_hthread *thr, const char *data) {
  28124. DUK_ASSERT(thr != NULL);
  28125. duk_debug_write_string(thr,
  28126. data,
  28127. data ? DUK_STRLEN(data) : 0);
  28128. }
  28129. DUK_INTERNAL void duk_debug_write_hstring(duk_hthread *thr, duk_hstring *h) {
  28130. DUK_ASSERT(thr != NULL);
  28131. /* XXX: differentiate null pointer from empty string? */
  28132. duk_debug_write_string(thr,
  28133. (h != NULL ? (const char *) DUK_HSTRING_GET_DATA(h) : NULL),
  28134. (h != NULL ? (duk_size_t) DUK_HSTRING_GET_BYTELEN(h) : 0));
  28135. }
  28136. DUK_INTERNAL void duk_debug_write_buffer(duk_hthread *thr, const char *data, duk_size_t length) {
  28137. duk_debug_write_strbuf(thr, data, length, 0x13);
  28138. }
  28139. DUK_INTERNAL void duk_debug_write_hbuffer(duk_hthread *thr, duk_hbuffer *h) {
  28140. DUK_ASSERT(thr != NULL);
  28141. duk_debug_write_buffer(thr,
  28142. (h != NULL ? (const char *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h) : NULL),
  28143. (h != NULL ? (duk_size_t) DUK_HBUFFER_GET_SIZE(h) : 0));
  28144. }
  28145. DUK_LOCAL void duk__debug_write_pointer_raw(duk_hthread *thr, const void *ptr, duk_uint8_t ibyte) {
  28146. duk_uint8_t buf[2];
  28147. volatile duk__ptr_union pu;
  28148. DUK_ASSERT(thr != NULL);
  28149. DUK_ASSERT(sizeof(ptr) >= 1 && sizeof(ptr) <= 16);
  28150. /* ptr may be NULL */
  28151. buf[0] = ibyte;
  28152. buf[1] = sizeof(pu);
  28153. duk_debug_write_bytes(thr, buf, 2);
  28154. pu.p = (void *) ptr;
  28155. #if defined(DUK_USE_INTEGER_LE)
  28156. duk_byteswap_bytes((duk_uint8_t *) pu.b, sizeof(pu));
  28157. #endif
  28158. duk_debug_write_bytes(thr, (const duk_uint8_t *) &pu.p, (duk_size_t) sizeof(pu));
  28159. }
  28160. DUK_INTERNAL void duk_debug_write_pointer(duk_hthread *thr, const void *ptr) {
  28161. duk__debug_write_pointer_raw(thr, ptr, 0x1c);
  28162. }
  28163. #if defined(DUK_USE_DEBUGGER_DUMPHEAP)
  28164. DUK_INTERNAL void duk_debug_write_heapptr(duk_hthread *thr, duk_heaphdr *h) {
  28165. duk__debug_write_pointer_raw(thr, (const void *) h, 0x1e);
  28166. }
  28167. #endif /* DUK_USE_DEBUGGER_DUMPHEAP */
  28168. DUK_INTERNAL void duk_debug_write_hobject(duk_hthread *thr, duk_hobject *obj) {
  28169. duk_uint8_t buf[3];
  28170. volatile duk__ptr_union pu;
  28171. DUK_ASSERT(thr != NULL);
  28172. DUK_ASSERT(sizeof(obj) >= 1 && sizeof(obj) <= 16);
  28173. DUK_ASSERT(obj != NULL);
  28174. buf[0] = 0x1b;
  28175. buf[1] = (duk_uint8_t) DUK_HOBJECT_GET_CLASS_NUMBER(obj);
  28176. buf[2] = sizeof(pu);
  28177. duk_debug_write_bytes(thr, buf, 3);
  28178. pu.p = (void *) obj;
  28179. #if defined(DUK_USE_INTEGER_LE)
  28180. duk_byteswap_bytes((duk_uint8_t *) pu.b, sizeof(pu));
  28181. #endif
  28182. duk_debug_write_bytes(thr, (const duk_uint8_t *) &pu.p, (duk_size_t) sizeof(pu));
  28183. }
  28184. DUK_INTERNAL void duk_debug_write_tval(duk_hthread *thr, duk_tval *tv) {
  28185. duk_c_function lf_func;
  28186. duk_small_uint_t lf_flags;
  28187. duk_uint8_t buf[4];
  28188. duk_double_union du;
  28189. DUK_ASSERT(thr != NULL);
  28190. DUK_ASSERT(tv != NULL);
  28191. switch (DUK_TVAL_GET_TAG(tv)) {
  28192. case DUK_TAG_UNDEFINED:
  28193. duk_debug_write_byte(thr,
  28194. DUK_TVAL_IS_UNDEFINED_UNUSED(tv) ? 0x15 : 0x16);
  28195. break;
  28196. case DUK_TAG_NULL:
  28197. duk_debug_write_byte(thr, 0x17);
  28198. break;
  28199. case DUK_TAG_BOOLEAN:
  28200. DUK_ASSERT(DUK_TVAL_GET_BOOLEAN(tv) == 0 ||
  28201. DUK_TVAL_GET_BOOLEAN(tv) == 1);
  28202. duk_debug_write_byte(thr, DUK_TVAL_GET_BOOLEAN(tv) ? 0x18 : 0x19);
  28203. break;
  28204. case DUK_TAG_POINTER:
  28205. duk_debug_write_pointer(thr, (const void *) DUK_TVAL_GET_POINTER(tv));
  28206. break;
  28207. case DUK_TAG_LIGHTFUNC:
  28208. DUK_TVAL_GET_LIGHTFUNC(tv, lf_func, lf_flags);
  28209. buf[0] = 0x1d;
  28210. buf[1] = (duk_uint8_t) (lf_flags >> 8);
  28211. buf[2] = (duk_uint8_t) (lf_flags & 0xff);
  28212. buf[3] = sizeof(lf_func);
  28213. duk_debug_write_bytes(thr, buf, 4);
  28214. duk_debug_write_bytes(thr, (const duk_uint8_t *) &lf_func, sizeof(lf_func));
  28215. break;
  28216. case DUK_TAG_STRING:
  28217. duk_debug_write_hstring(thr, DUK_TVAL_GET_STRING(tv));
  28218. break;
  28219. case DUK_TAG_OBJECT:
  28220. duk_debug_write_hobject(thr, DUK_TVAL_GET_OBJECT(tv));
  28221. break;
  28222. case DUK_TAG_BUFFER:
  28223. duk_debug_write_hbuffer(thr, DUK_TVAL_GET_BUFFER(tv));
  28224. break;
  28225. #if defined(DUK_USE_FASTINT)
  28226. case DUK_TAG_FASTINT:
  28227. #endif
  28228. default:
  28229. /* Numbers are normalized to big (network) endian. */
  28230. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  28231. du.d = DUK_TVAL_GET_NUMBER(tv);
  28232. DUK_DBLUNION_BSWAP(&du);
  28233. duk_debug_write_byte(thr, 0x1a);
  28234. duk_debug_write_bytes(thr, (const duk_uint8_t *) du.uc, sizeof(du.uc));
  28235. }
  28236. }
  28237. #if defined(DUK_USE_DEBUGGER_DUMPHEAP)
  28238. /* Variant for writing duk_tvals so that any heap allocated values are
  28239. * written out as tagged heap pointers.
  28240. */
  28241. DUK_LOCAL void duk__debug_write_tval_heapptr(duk_hthread *thr, duk_tval *tv) {
  28242. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  28243. duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
  28244. duk_debug_write_heapptr(thr, h);
  28245. } else {
  28246. duk_debug_write_tval(thr, tv);
  28247. }
  28248. }
  28249. #endif /* DUK_USE_DEBUGGER_DUMPHEAP */
  28250. /*
  28251. * Debug connection message write helpers
  28252. */
  28253. #if 0 /* unused */
  28254. DUK_INTERNAL void duk_debug_write_request(duk_hthread *thr, duk_small_uint_t command) {
  28255. duk_debug_write_byte(thr, DUK_DBG_MARKER_REQUEST);
  28256. duk_debug_write_int(thr, command);
  28257. }
  28258. #endif
  28259. DUK_INTERNAL void duk_debug_write_reply(duk_hthread *thr) {
  28260. duk_debug_write_byte(thr, DUK_DBG_MARKER_REPLY);
  28261. }
  28262. DUK_INTERNAL void duk_debug_write_error_eom(duk_hthread *thr, duk_small_uint_t err_code, const char *msg) {
  28263. /* Allow NULL 'msg' */
  28264. duk_debug_write_byte(thr, DUK_DBG_MARKER_ERROR);
  28265. duk_debug_write_int(thr, (duk_int32_t) err_code);
  28266. duk_debug_write_cstring(thr, msg);
  28267. duk_debug_write_eom(thr);
  28268. }
  28269. DUK_INTERNAL void duk_debug_write_notify(duk_hthread *thr, duk_small_uint_t command) {
  28270. duk_debug_write_byte(thr, DUK_DBG_MARKER_NOTIFY);
  28271. duk_debug_write_int(thr, command);
  28272. }
  28273. DUK_INTERNAL void duk_debug_write_eom(duk_hthread *thr) {
  28274. duk_debug_write_byte(thr, DUK_DBG_MARKER_EOM);
  28275. /* As an initial implementation, write flush after every EOM (and the
  28276. * version identifier). A better implementation would flush only when
  28277. * Duktape is finished processing messages so that a flush only happens
  28278. * after all outbound messages are finished on that occasion.
  28279. */
  28280. duk_debug_write_flush(thr);
  28281. }
  28282. /*
  28283. * Status message and helpers
  28284. */
  28285. DUK_INTERNAL duk_uint_fast32_t duk_debug_curr_line(duk_hthread *thr) {
  28286. duk_context *ctx = (duk_context *) thr;
  28287. duk_activation *act;
  28288. duk_uint_fast32_t line;
  28289. duk_uint_fast32_t pc;
  28290. if (thr->callstack_top == 0) {
  28291. return 0;
  28292. }
  28293. act = thr->callstack + thr->callstack_top - 1;
  28294. /* act->pc indicates the next instruction about to be executed. This
  28295. * is usually correct, but for the 'debugger' statement it will be the
  28296. * instruction after that.
  28297. */
  28298. pc = (duk_uint_fast32_t) act->pc;
  28299. /* XXX: this should be optimized to be a raw query and avoid valstack
  28300. * operations if possible.
  28301. */
  28302. duk_push_hobject(ctx, act->func);
  28303. line = duk_hobject_pc2line_query(ctx, -1, pc);
  28304. duk_pop(ctx);
  28305. return line;
  28306. }
  28307. DUK_INTERNAL void duk_debug_send_status(duk_hthread *thr) {
  28308. duk_context *ctx = (duk_context *) thr;
  28309. duk_activation *act;
  28310. duk_debug_write_notify(thr, DUK_DBG_CMD_STATUS);
  28311. duk_debug_write_int(thr, thr->heap->dbg_paused);
  28312. DUK_ASSERT_DISABLE(thr->callstack_top >= 0); /* unsigned */
  28313. if (thr->callstack_top == 0) {
  28314. duk_debug_write_undefined(thr);
  28315. duk_debug_write_undefined(thr);
  28316. duk_debug_write_int(thr, 0);
  28317. duk_debug_write_int(thr, 0);
  28318. } else {
  28319. act = thr->callstack + thr->callstack_top - 1;
  28320. duk_push_hobject(ctx, act->func);
  28321. duk_get_prop_string(ctx, -1, "fileName");
  28322. duk_safe_to_string(ctx, -1);
  28323. duk_debug_write_hstring(thr, duk_require_hstring(ctx, -1));
  28324. duk_get_prop_string(ctx, -2, "name");
  28325. duk_safe_to_string(ctx, -1);
  28326. duk_debug_write_hstring(thr, duk_require_hstring(ctx, -1));
  28327. duk_pop_3(ctx);
  28328. duk_debug_write_uint(thr, (duk_uint32_t) duk_debug_curr_line(thr));
  28329. duk_debug_write_uint(thr, (duk_uint32_t) act->pc);
  28330. }
  28331. duk_debug_write_eom(thr);
  28332. }
  28333. /*
  28334. * Debug message processing
  28335. */
  28336. /* Skip dvalue. */
  28337. DUK_LOCAL duk_bool_t duk__debug_skip_dvalue(duk_hthread *thr) {
  28338. duk_uint8_t x;
  28339. duk_uint32_t len;
  28340. x = duk_debug_read_byte(thr);
  28341. if (x >= 0xc0) {
  28342. duk_debug_skip_byte(thr);
  28343. return 0;
  28344. }
  28345. if (x >= 0x80) {
  28346. return 0;
  28347. }
  28348. if (x >= 0x60) {
  28349. duk_debug_skip_bytes(thr, x - 0x60);
  28350. return 0;
  28351. }
  28352. switch(x) {
  28353. case 0x00:
  28354. return 1; /* Return 1: got EOM */
  28355. case 0x01:
  28356. case 0x02:
  28357. case 0x03:
  28358. case 0x04:
  28359. break;
  28360. case 0x10:
  28361. (void) duk__debug_read_uint32_raw(thr);
  28362. break;
  28363. case 0x11:
  28364. case 0x13:
  28365. len = duk__debug_read_uint32_raw(thr);
  28366. duk_debug_skip_bytes(thr, len);
  28367. break;
  28368. case 0x12:
  28369. case 0x14:
  28370. len = duk__debug_read_uint16_raw(thr);
  28371. duk_debug_skip_bytes(thr, len);
  28372. break;
  28373. case 0x15:
  28374. case 0x16:
  28375. case 0x17:
  28376. case 0x18:
  28377. case 0x19:
  28378. break;
  28379. case 0x1a:
  28380. duk_debug_skip_bytes(thr, 8);
  28381. break;
  28382. case 0x1b:
  28383. duk_debug_skip_byte(thr);
  28384. len = duk_debug_read_byte(thr);
  28385. duk_debug_skip_bytes(thr, len);
  28386. break;
  28387. case 0x1c:
  28388. len = duk_debug_read_byte(thr);
  28389. duk_debug_skip_bytes(thr, len);
  28390. break;
  28391. case 0x1d:
  28392. duk_debug_skip_bytes(thr, 2);
  28393. len = duk_debug_read_byte(thr);
  28394. duk_debug_skip_bytes(thr, len);
  28395. break;
  28396. default:
  28397. goto fail;
  28398. }
  28399. return 0;
  28400. fail:
  28401. DUK__SET_CONN_BROKEN(thr);
  28402. return 1; /* Pretend like we got EOM */
  28403. }
  28404. /* Skip dvalues to EOM. */
  28405. DUK_LOCAL void duk__debug_skip_to_eom(duk_hthread *thr) {
  28406. for (;;) {
  28407. if (duk__debug_skip_dvalue(thr)) {
  28408. break;
  28409. }
  28410. }
  28411. }
  28412. /*
  28413. * Process incoming debug requests
  28414. */
  28415. DUK_LOCAL void duk__debug_handle_basic_info(duk_hthread *thr, duk_heap *heap) {
  28416. DUK_UNREF(heap);
  28417. DUK_D(DUK_DPRINT("debug command version"));
  28418. duk_debug_write_reply(thr);
  28419. duk_debug_write_int(thr, DUK_VERSION);
  28420. duk_debug_write_cstring(thr, DUK_GIT_DESCRIBE);
  28421. duk_debug_write_cstring(thr, DUK_USE_TARGET_INFO);
  28422. #if defined(DUK_USE_DOUBLE_LE)
  28423. duk_debug_write_int(thr, 1);
  28424. #elif defined(DUK_USE_DOUBLE_ME)
  28425. duk_debug_write_int(thr, 2);
  28426. #elif defined(DUK_USE_DOUBLE_BE)
  28427. duk_debug_write_int(thr, 3);
  28428. #else
  28429. duk_debug_write_int(thr, 0);
  28430. #endif
  28431. duk_debug_write_eom(thr);
  28432. }
  28433. DUK_LOCAL void duk__debug_handle_trigger_status(duk_hthread *thr, duk_heap *heap) {
  28434. DUK_UNREF(heap);
  28435. DUK_D(DUK_DPRINT("debug command triggerstatus"));
  28436. duk_debug_write_reply(thr);
  28437. duk_debug_write_eom(thr);
  28438. heap->dbg_state_dirty = 1;
  28439. }
  28440. DUK_LOCAL void duk__debug_handle_pause(duk_hthread *thr, duk_heap *heap) {
  28441. DUK_D(DUK_DPRINT("debug command pause"));
  28442. DUK_HEAP_SET_PAUSED(heap);
  28443. duk_debug_write_reply(thr);
  28444. duk_debug_write_eom(thr);
  28445. }
  28446. DUK_LOCAL void duk__debug_handle_resume(duk_hthread *thr, duk_heap *heap) {
  28447. DUK_D(DUK_DPRINT("debug command resume"));
  28448. DUK_HEAP_CLEAR_PAUSED(heap);
  28449. duk_debug_write_reply(thr);
  28450. duk_debug_write_eom(thr);
  28451. }
  28452. DUK_LOCAL void duk__debug_handle_step(duk_hthread *thr, duk_heap *heap, duk_int32_t cmd) {
  28453. duk_small_uint_t step_type;
  28454. duk_uint_fast32_t line;
  28455. if (cmd == DUK_DBG_CMD_STEPINTO) {
  28456. step_type = DUK_STEP_TYPE_INTO;
  28457. } else if (cmd == DUK_DBG_CMD_STEPOVER) {
  28458. step_type = DUK_STEP_TYPE_OVER;
  28459. } else {
  28460. DUK_ASSERT(cmd == DUK_DBG_CMD_STEPOUT);
  28461. step_type = DUK_STEP_TYPE_OUT;
  28462. }
  28463. DUK_D(DUK_DPRINT("debug command stepinto/stepover/stepout: %d", (int) cmd));
  28464. line = duk_debug_curr_line(thr);
  28465. if (line > 0) {
  28466. heap->dbg_paused = 0;
  28467. heap->dbg_step_type = step_type;
  28468. heap->dbg_step_thread = thr;
  28469. heap->dbg_step_csindex = thr->callstack_top - 1;
  28470. heap->dbg_step_startline = line;
  28471. heap->dbg_state_dirty = 1;
  28472. } else {
  28473. DUK_D(DUK_DPRINT("cannot determine current line, stepinto/stepover/stepout ignored"));
  28474. }
  28475. duk_debug_write_reply(thr);
  28476. duk_debug_write_eom(thr);
  28477. }
  28478. DUK_LOCAL void duk__debug_handle_list_break(duk_hthread *thr, duk_heap *heap) {
  28479. duk_small_int_t i;
  28480. DUK_D(DUK_DPRINT("debug command listbreak"));
  28481. duk_debug_write_reply(thr);
  28482. for (i = 0; i < (duk_small_int_t) heap->dbg_breakpoint_count; i++) {
  28483. duk_debug_write_hstring(thr, heap->dbg_breakpoints[i].filename);
  28484. duk_debug_write_uint(thr, (duk_uint32_t) heap->dbg_breakpoints[i].line);
  28485. }
  28486. duk_debug_write_eom(thr);
  28487. }
  28488. DUK_LOCAL void duk__debug_handle_add_break(duk_hthread *thr, duk_heap *heap) {
  28489. duk_context *ctx = (duk_context *) thr;
  28490. duk_hstring *filename;
  28491. duk_uint32_t linenumber;
  28492. duk_small_int_t idx;
  28493. DUK_UNREF(heap);
  28494. filename = duk_debug_read_hstring(thr);
  28495. linenumber = (duk_uint32_t) duk_debug_read_int(thr);
  28496. DUK_D(DUK_DPRINT("debug command addbreak: %!O:%ld", (duk_hobject *) filename, (long) linenumber));
  28497. idx = duk_debug_add_breakpoint(thr, filename, linenumber);
  28498. if (idx >= 0) {
  28499. duk_debug_write_reply(thr);
  28500. duk_debug_write_int(thr, (duk_int32_t) idx);
  28501. duk_debug_write_eom(thr);
  28502. } else {
  28503. duk_debug_write_error_eom(thr, DUK_DBG_ERR_TOOMANY, "no space for breakpoint");
  28504. }
  28505. duk_pop(ctx);
  28506. }
  28507. DUK_LOCAL void duk__debug_handle_del_break(duk_hthread *thr, duk_heap *heap) {
  28508. duk_small_uint_t idx;
  28509. DUK_UNREF(heap);
  28510. DUK_D(DUK_DPRINT("debug command delbreak"));
  28511. idx = (duk_small_uint_t) duk_debug_read_int(thr);
  28512. if (duk_debug_remove_breakpoint(thr, idx)) {
  28513. duk_debug_write_reply(thr);
  28514. duk_debug_write_eom(thr);
  28515. } else {
  28516. duk_debug_write_error_eom(thr, DUK_DBG_ERR_NOTFOUND, "invalid breakpoint index");
  28517. }
  28518. }
  28519. DUK_LOCAL void duk__debug_handle_get_var(duk_hthread *thr, duk_heap *heap) {
  28520. duk_context *ctx = (duk_context *) thr;
  28521. duk_hstring *str;
  28522. duk_bool_t rc;
  28523. DUK_UNREF(heap);
  28524. DUK_D(DUK_DPRINT("debug command getvar"));
  28525. str = duk_debug_read_hstring(thr); /* push to stack */
  28526. DUK_ASSERT(str != NULL);
  28527. if (thr->callstack_top > 0) {
  28528. rc = duk_js_getvar_activation(thr,
  28529. thr->callstack + thr->callstack_top - 1,
  28530. str,
  28531. 0);
  28532. } else {
  28533. /* No activation, no variable access. Could also pretend
  28534. * we're in the global program context and read stuff off
  28535. * the global object.
  28536. */
  28537. DUK_D(DUK_DPRINT("callstack empty, no activation -> ignore getvar"));
  28538. rc = 0;
  28539. }
  28540. duk_debug_write_reply(thr);
  28541. if (rc) {
  28542. duk_debug_write_int(thr, 1);
  28543. duk_debug_write_tval(thr, duk_require_tval(ctx, -2));
  28544. duk_pop_2(ctx);
  28545. } else {
  28546. duk_debug_write_int(thr, 0);
  28547. duk_debug_write_unused(thr);
  28548. }
  28549. duk_pop(ctx);
  28550. duk_debug_write_eom(thr);
  28551. }
  28552. DUK_LOCAL void duk__debug_handle_put_var(duk_hthread *thr, duk_heap *heap) {
  28553. duk_context *ctx = (duk_context *) thr;
  28554. duk_hstring *str;
  28555. duk_tval *tv;
  28556. DUK_UNREF(heap);
  28557. DUK_D(DUK_DPRINT("debug command putvar"));
  28558. str = duk_debug_read_hstring(thr); /* push to stack */
  28559. DUK_ASSERT(str != NULL);
  28560. duk_debug_read_tval(thr); /* push to stack */
  28561. tv = duk_require_tval(ctx, -1);
  28562. if (thr->callstack_top > 0) {
  28563. duk_js_putvar_activation(thr,
  28564. thr->callstack + thr->callstack_top - 1,
  28565. str,
  28566. tv,
  28567. 0);
  28568. } else {
  28569. DUK_D(DUK_DPRINT("callstack empty, no activation -> ignore putvar"));
  28570. }
  28571. duk_pop_2(ctx);
  28572. /* XXX: Current putvar implementation doesn't have a success flag,
  28573. * add one and send to debug client?
  28574. */
  28575. duk_debug_write_reply(thr);
  28576. duk_debug_write_eom(thr);
  28577. }
  28578. DUK_LOCAL void duk__debug_handle_get_call_stack(duk_hthread *thr, duk_heap *heap) {
  28579. duk_context *ctx = (duk_context *) thr;
  28580. duk_hthread *curr_thr = thr;
  28581. duk_activation *curr_act;
  28582. duk_uint_fast32_t line;
  28583. duk_size_t i;
  28584. DUK_UNREF(heap);
  28585. duk_debug_write_reply(thr);
  28586. while (curr_thr != NULL) {
  28587. i = curr_thr->callstack_top;
  28588. while (i > 0) {
  28589. i--;
  28590. curr_act = curr_thr->callstack + i;
  28591. /* XXX: optimize to use direct reads,
  28592. * i.e. avoid value stack operations.
  28593. */
  28594. duk_push_tval(ctx, &curr_act->tv_func);
  28595. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_FILE_NAME);
  28596. duk_safe_to_string(ctx, -1);
  28597. duk_debug_write_hstring(thr, duk_get_hstring(ctx, -1));
  28598. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_NAME);
  28599. duk_safe_to_string(ctx, -1);
  28600. duk_debug_write_hstring(thr, duk_get_hstring(ctx, -1));
  28601. line = duk_hobject_pc2line_query(ctx, -3, curr_act->pc);
  28602. duk_debug_write_uint(thr, (duk_uint32_t) line);
  28603. duk_debug_write_uint(thr, (duk_uint32_t) curr_act->pc);
  28604. duk_pop_3(ctx);
  28605. }
  28606. curr_thr = curr_thr->resumer;
  28607. }
  28608. duk_debug_write_eom(thr);
  28609. }
  28610. DUK_LOCAL void duk__debug_handle_get_locals(duk_hthread *thr, duk_heap *heap) {
  28611. duk_context *ctx = (duk_context *) thr;
  28612. duk_activation *curr_act;
  28613. duk_hstring *varname;
  28614. DUK_UNREF(heap);
  28615. duk_debug_write_reply(thr);
  28616. if (thr->callstack_top == 0) {
  28617. goto callstack_empty;
  28618. }
  28619. curr_act = thr->callstack + thr->callstack_top - 1;
  28620. /* XXX: several nice-to-have improvements here:
  28621. * - Use direct reads avoiding value stack operations
  28622. * - Avoid triggering getters, indicate getter values to debug client
  28623. * - If side effects are possible, add error catching
  28624. */
  28625. duk_push_tval(ctx, &curr_act->tv_func);
  28626. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VARMAP);
  28627. if (duk_is_object(ctx, -1)) {
  28628. duk_enum(ctx, -1, 0 /*enum_flags*/);
  28629. while (duk_next(ctx, -1 /*enum_index*/, 0 /*get_value*/)) {
  28630. varname = duk_get_hstring(ctx, -1);
  28631. DUK_ASSERT(varname != NULL);
  28632. duk_js_getvar_activation(thr, curr_act, varname, 0 /*throw_flag*/);
  28633. /* [ ... func varmap enum key value this ] */
  28634. duk_debug_write_hstring(thr, duk_get_hstring(ctx, -3));
  28635. duk_debug_write_tval(thr, duk_get_tval(ctx, -2));
  28636. duk_pop_3(ctx); /* -> [ ... func varmap enum ] */
  28637. }
  28638. duk_pop(ctx);
  28639. } else {
  28640. DUK_D(DUK_DPRINT("varmap is not an object in GetLocals, ignore"));
  28641. }
  28642. duk_pop_2(ctx);
  28643. callstack_empty:
  28644. duk_debug_write_eom(thr);
  28645. }
  28646. DUK_LOCAL void duk__debug_handle_eval(duk_hthread *thr, duk_heap *heap) {
  28647. duk_context *ctx = (duk_context *) thr;
  28648. duk_small_uint_t call_flags;
  28649. duk_int_t call_ret;
  28650. duk_small_int_t eval_err;
  28651. #if defined(DUK_USE_ASSERTIONS)
  28652. duk_idx_t entry_top;
  28653. #endif
  28654. DUK_UNREF(heap);
  28655. DUK_D(DUK_DPRINT("debug command eval"));
  28656. /* The eval code must be executed within the current (topmost)
  28657. * activation. For now, use global object eval() function, with
  28658. * the eval considered a 'direct call to eval'.
  28659. */
  28660. #if defined(DUK_USE_ASSERTIONS)
  28661. entry_top = duk_get_top(ctx);
  28662. #endif
  28663. duk_push_c_function(ctx, duk_bi_global_object_eval, 1 /*nargs*/);
  28664. duk_push_undefined(ctx); /* 'this' binding shouldn't matter here */
  28665. (void) duk_debug_read_hstring(thr);
  28666. /* [ ... eval "eval" eval_input ] */
  28667. call_flags = DUK_CALL_FLAG_PROTECTED;
  28668. if (thr->callstack_top >= 1) {
  28669. duk_activation *act;
  28670. duk_hobject *fun;
  28671. act = thr->callstack + thr->callstack_top - 1;
  28672. fun = DUK_ACT_GET_FUNC(act);
  28673. if (fun && DUK_HOBJECT_IS_COMPILEDFUNCTION(fun)) {
  28674. /* Direct eval requires that there's a current
  28675. * activation and it is an Ecmascript function.
  28676. * When Eval is executed from e.g. cooperate API
  28677. * call we'll need to an indirect eval instead.
  28678. */
  28679. call_flags |= DUK_CALL_FLAG_DIRECT_EVAL;
  28680. }
  28681. }
  28682. call_ret = duk_handle_call(thr, 1 /*num_stack_args*/, call_flags);
  28683. if (call_ret == DUK_EXEC_SUCCESS) {
  28684. eval_err = 0;
  28685. /* Use result value as is. */
  28686. } else {
  28687. /* For errors a string coerced result is most informative
  28688. * right now, as the debug client doesn't have the capability
  28689. * to traverse the error object.
  28690. */
  28691. eval_err = 1;
  28692. duk_safe_to_string(ctx, -1);
  28693. }
  28694. /* [ ... result ] */
  28695. duk_debug_write_reply(thr);
  28696. duk_debug_write_int(thr, (duk_int32_t) eval_err);
  28697. duk_debug_write_tval(thr, duk_require_tval(ctx, -1));
  28698. duk_debug_write_eom(thr);
  28699. duk_pop(ctx);
  28700. DUK_ASSERT(duk_get_top(ctx) == entry_top);
  28701. }
  28702. DUK_LOCAL void duk__debug_handle_detach(duk_hthread *thr, duk_heap *heap) {
  28703. DUK_UNREF(heap);
  28704. DUK_D(DUK_DPRINT("debug command detach"));
  28705. duk_debug_write_reply(thr);
  28706. duk_debug_write_eom(thr);
  28707. DUK_D(DUK_DPRINT("debug connection detached, mark broken"));
  28708. DUK__SET_CONN_BROKEN(thr);
  28709. }
  28710. #if defined(DUK_USE_DEBUGGER_DUMPHEAP)
  28711. DUK_LOCAL void duk__debug_dump_heaphdr(duk_hthread *thr, duk_heap *heap, duk_heaphdr *hdr) {
  28712. DUK_UNREF(heap);
  28713. duk_debug_write_heapptr(thr, hdr);
  28714. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HEAPHDR_GET_TYPE(hdr));
  28715. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HEAPHDR_GET_FLAGS_RAW(hdr));
  28716. #if defined(DUK_USE_REFERENCE_COUNTING)
  28717. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HEAPHDR_GET_REFCOUNT(hdr));
  28718. #else
  28719. duk_debug_write_int(thr, (duk_int32_t) -1);
  28720. #endif
  28721. switch (DUK_HEAPHDR_GET_TYPE(hdr)) {
  28722. case DUK_HTYPE_STRING: {
  28723. duk_hstring *h = (duk_hstring *) hdr;
  28724. duk_debug_write_uint(thr, (duk_int32_t) DUK_HSTRING_GET_BYTELEN(h));
  28725. duk_debug_write_uint(thr, (duk_int32_t) DUK_HSTRING_GET_CHARLEN(h));
  28726. duk_debug_write_uint(thr, (duk_int32_t) DUK_HSTRING_GET_HASH(h));
  28727. duk_debug_write_hstring(thr, h);
  28728. break;
  28729. }
  28730. case DUK_HTYPE_OBJECT: {
  28731. duk_hobject *h = (duk_hobject *) hdr;
  28732. duk_hstring *k;
  28733. duk_uint_fast32_t i;
  28734. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_CLASS_NUMBER(h));
  28735. duk_debug_write_heapptr(thr, (duk_heaphdr *) DUK_HOBJECT_GET_PROTOTYPE(heap, h));
  28736. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_ESIZE(h));
  28737. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_ENEXT(h));
  28738. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_ASIZE(h));
  28739. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_HSIZE(h));
  28740. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(h); i++) {
  28741. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_E_GET_FLAGS(heap, h, i));
  28742. k = DUK_HOBJECT_E_GET_KEY(heap, h, i);
  28743. duk_debug_write_heapptr(thr, (duk_heaphdr *) k);
  28744. if (k == NULL) {
  28745. duk_debug_write_int(thr, 0); /* isAccessor */
  28746. duk_debug_write_unused(thr);
  28747. continue;
  28748. }
  28749. if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(heap, h, i)) {
  28750. duk_debug_write_int(thr, 1); /* isAccessor */
  28751. duk_debug_write_heapptr(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->a.get);
  28752. duk_debug_write_heapptr(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->a.set);
  28753. } else {
  28754. duk_debug_write_int(thr, 0); /* isAccessor */
  28755. duk__debug_write_tval_heapptr(thr, &DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->v);
  28756. }
  28757. }
  28758. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ASIZE(h); i++) {
  28759. /* Note: array dump will include elements beyond
  28760. * 'length'.
  28761. */
  28762. duk__debug_write_tval_heapptr(thr, DUK_HOBJECT_A_GET_VALUE_PTR(heap, h, i));
  28763. }
  28764. break;
  28765. }
  28766. case DUK_HTYPE_BUFFER: {
  28767. duk_hbuffer *h = (duk_hbuffer *) hdr;
  28768. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HBUFFER_GET_SIZE(h));
  28769. if (DUK_HBUFFER_HAS_DYNAMIC(h)) {
  28770. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE((duk_hbuffer_dynamic *) h));
  28771. } else {
  28772. duk_debug_write_uint(thr, (duk_uint32_t) DUK_HBUFFER_GET_SIZE(h));
  28773. }
  28774. duk_debug_write_buffer(thr, (const char *) DUK_HBUFFER_GET_DATA_PTR(heap, h), (duk_size_t) DUK_HBUFFER_GET_SIZE(h));
  28775. break;
  28776. }
  28777. default: {
  28778. DUK_D(DUK_DPRINT("invalid htype: %d", (int) DUK_HEAPHDR_GET_TYPE(hdr)));
  28779. }
  28780. }
  28781. }
  28782. DUK_LOCAL void duk__debug_dump_heap_allocated(duk_hthread *thr, duk_heap *heap) {
  28783. duk_heaphdr *hdr;
  28784. hdr = heap->heap_allocated;
  28785. while (hdr != NULL) {
  28786. duk__debug_dump_heaphdr(thr, heap, hdr);
  28787. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  28788. }
  28789. }
  28790. #if defined(DUK_USE_STRTAB_CHAIN)
  28791. DUK_LOCAL void duk__debug_dump_strtab_chain(duk_hthread *thr, duk_heap *heap) {
  28792. duk_uint_fast32_t i, j;
  28793. duk_strtab_entry *e;
  28794. #if defined(DUK_USE_HEAPPTR16)
  28795. duk_uint16_t *lst;
  28796. #else
  28797. duk_hstring **lst;
  28798. #endif
  28799. duk_hstring *h;
  28800. for (i = 0; i < DUK_STRTAB_CHAIN_SIZE; i++) {
  28801. e = heap->strtable + i;
  28802. if (e->listlen > 0) {
  28803. #if defined(DUK_USE_HEAPPTR16)
  28804. lst = (duk_uint16_t *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.strlist16);
  28805. #else
  28806. lst = e->u.strlist;
  28807. #endif
  28808. DUK_ASSERT(lst != NULL);
  28809. for (j = 0; j < e->listlen; j++) {
  28810. #if defined(DUK_USE_HEAPPTR16)
  28811. h = DUK_USE_HEAPPTR_DEC16(heap->heap_udata, lst[j]);
  28812. #else
  28813. h = lst[j];
  28814. #endif
  28815. if (h != NULL) {
  28816. duk__debug_dump_heaphdr(thr, heap, (duk_heaphdr *) h);
  28817. }
  28818. }
  28819. } else {
  28820. #if defined(DUK_USE_HEAPPTR16)
  28821. h = DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.str16);
  28822. #else
  28823. h = e->u.str;
  28824. #endif
  28825. if (h != NULL) {
  28826. duk__debug_dump_heaphdr(thr, heap, (duk_heaphdr *) h);
  28827. }
  28828. }
  28829. }
  28830. }
  28831. #endif /* DUK_USE_STRTAB_CHAIN */
  28832. #if defined(DUK_USE_STRTAB_PROBE)
  28833. DUK_LOCAL void duk__debug_dump_strtab_probe(duk_hthread *thr, duk_heap *heap) {
  28834. duk_uint32_t i;
  28835. duk_hstring *h;
  28836. for (i = 0; i < heap->st_size; i++) {
  28837. #if defined(DUK_USE_HEAPPTR16)
  28838. h = DUK_USE_HEAPPTR_DEC16(heap->strtable16[i]);
  28839. #else
  28840. h = heap->strtable[i];
  28841. #endif
  28842. if (h == NULL || h == DUK_STRTAB_DELETED_MARKER(heap)) {
  28843. continue;
  28844. }
  28845. duk__debug_dump_heaphdr(thr, heap, (duk_heaphdr *) h);
  28846. }
  28847. }
  28848. #endif /* DUK_USE_STRTAB_PROBE */
  28849. DUK_LOCAL void duk__debug_handle_dump_heap(duk_hthread *thr, duk_heap *heap) {
  28850. DUK_D(DUK_DPRINT("debug command dumpheap"));
  28851. duk_debug_write_reply(thr);
  28852. duk__debug_dump_heap_allocated(thr, heap);
  28853. #if defined(DUK_USE_STRTAB_CHAIN)
  28854. duk__debug_dump_strtab_chain(thr, heap);
  28855. #endif
  28856. #if defined(DUK_USE_STRTAB_PROBE)
  28857. duk__debug_dump_strtab_probe(thr, heap);
  28858. #endif
  28859. duk_debug_write_eom(thr);
  28860. }
  28861. #endif /* DUK_USE_DEBUGGER_DUMPHEAP */
  28862. DUK_LOCAL void duk__debug_handle_get_bytecode(duk_hthread *thr, duk_heap *heap) {
  28863. duk_activation *act;
  28864. duk_hcompiledfunction *fun;
  28865. duk_size_t i, n;
  28866. duk_tval *tv;
  28867. duk_hobject **fn;
  28868. DUK_UNREF(heap);
  28869. DUK_D(DUK_DPRINT("debug command getbytecode"));
  28870. duk_debug_write_reply(thr);
  28871. if (thr->callstack_top == 0) {
  28872. fun = NULL;
  28873. } else {
  28874. act = thr->callstack + thr->callstack_top - 1;
  28875. fun = (duk_hcompiledfunction *) DUK_ACT_GET_FUNC(act);
  28876. if (!DUK_HOBJECT_IS_COMPILEDFUNCTION((duk_hobject *) fun)) {
  28877. fun = NULL;
  28878. }
  28879. }
  28880. DUK_ASSERT(fun == NULL || DUK_HOBJECT_IS_COMPILEDFUNCTION((duk_hobject *) fun));
  28881. if (fun) {
  28882. n = DUK_HCOMPILEDFUNCTION_GET_CONSTS_COUNT(heap, fun);
  28883. duk_debug_write_int(thr, (int) n);
  28884. tv = DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(heap, fun);
  28885. for (i = 0; i < n; i++) {
  28886. duk_debug_write_tval(thr, tv);
  28887. tv++;
  28888. }
  28889. n = DUK_HCOMPILEDFUNCTION_GET_FUNCS_COUNT(heap, fun);
  28890. duk_debug_write_int(thr, (int) n);
  28891. fn = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(heap, fun);
  28892. for (i = 0; i < n; i++) {
  28893. duk_debug_write_hobject(thr, *fn);
  28894. fn++;
  28895. }
  28896. duk_debug_write_string(thr,
  28897. (const char *) DUK_HCOMPILEDFUNCTION_GET_CODE_BASE(heap, fun),
  28898. (duk_size_t) DUK_HCOMPILEDFUNCTION_GET_CODE_SIZE(heap, fun));
  28899. } else {
  28900. duk_debug_write_int(thr, 0);
  28901. duk_debug_write_int(thr, 0);
  28902. duk_debug_write_cstring(thr, "");
  28903. }
  28904. duk_debug_write_eom(thr);
  28905. }
  28906. DUK_LOCAL void duk__debug_process_message(duk_hthread *thr) {
  28907. duk_context *ctx = (duk_context *) thr;
  28908. duk_heap *heap;
  28909. duk_uint8_t x;
  28910. duk_int32_t cmd;
  28911. DUK_ASSERT(thr != NULL);
  28912. heap = thr->heap;
  28913. DUK_ASSERT(heap != NULL);
  28914. DUK_UNREF(ctx);
  28915. x = duk_debug_read_byte(thr);
  28916. switch (x) {
  28917. case DUK_DBG_MARKER_REQUEST: {
  28918. cmd = duk_debug_read_int(thr);
  28919. switch (cmd) {
  28920. case DUK_DBG_CMD_BASICINFO: {
  28921. duk__debug_handle_basic_info(thr, heap);
  28922. break;
  28923. }
  28924. case DUK_DBG_CMD_TRIGGERSTATUS: {
  28925. duk__debug_handle_trigger_status(thr, heap);
  28926. break;
  28927. }
  28928. case DUK_DBG_CMD_PAUSE: {
  28929. duk__debug_handle_pause(thr, heap);
  28930. break;
  28931. }
  28932. case DUK_DBG_CMD_RESUME: {
  28933. duk__debug_handle_resume(thr, heap);
  28934. break;
  28935. }
  28936. case DUK_DBG_CMD_STEPINTO:
  28937. case DUK_DBG_CMD_STEPOVER:
  28938. case DUK_DBG_CMD_STEPOUT: {
  28939. duk__debug_handle_step(thr, heap, cmd);
  28940. break;
  28941. }
  28942. case DUK_DBG_CMD_LISTBREAK: {
  28943. duk__debug_handle_list_break(thr, heap);
  28944. break;
  28945. }
  28946. case DUK_DBG_CMD_ADDBREAK: {
  28947. duk__debug_handle_add_break(thr, heap);
  28948. break;
  28949. }
  28950. case DUK_DBG_CMD_DELBREAK: {
  28951. duk__debug_handle_del_break(thr, heap);
  28952. break;
  28953. }
  28954. case DUK_DBG_CMD_GETVAR: {
  28955. duk__debug_handle_get_var(thr, heap);
  28956. break;
  28957. }
  28958. case DUK_DBG_CMD_PUTVAR: {
  28959. duk__debug_handle_put_var(thr, heap);
  28960. break;
  28961. }
  28962. case DUK_DBG_CMD_GETCALLSTACK: {
  28963. duk__debug_handle_get_call_stack(thr, heap);
  28964. break;
  28965. }
  28966. case DUK_DBG_CMD_GETLOCALS: {
  28967. duk__debug_handle_get_locals(thr, heap);
  28968. break;
  28969. }
  28970. case DUK_DBG_CMD_EVAL: {
  28971. duk__debug_handle_eval(thr, heap);
  28972. break;
  28973. }
  28974. case DUK_DBG_CMD_DETACH: {
  28975. duk__debug_handle_detach(thr, heap);
  28976. break;
  28977. }
  28978. #if defined(DUK_USE_DEBUGGER_DUMPHEAP)
  28979. case DUK_DBG_CMD_DUMPHEAP: {
  28980. duk__debug_handle_dump_heap(thr, heap);
  28981. break;
  28982. }
  28983. #endif /* DUK_USE_DEBUGGER_DUMPHEAP */
  28984. case DUK_DBG_CMD_GETBYTECODE: {
  28985. duk__debug_handle_get_bytecode(thr, heap);
  28986. break;
  28987. }
  28988. default: {
  28989. DUK_D(DUK_DPRINT("debug command unsupported: %d", (int) cmd));
  28990. duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNSUPPORTED, "unsupported command");
  28991. }
  28992. } /* switch cmd */
  28993. break;
  28994. }
  28995. case DUK_DBG_MARKER_REPLY: {
  28996. DUK_D(DUK_DPRINT("debug reply, skipping"));
  28997. break;
  28998. }
  28999. case DUK_DBG_MARKER_ERROR: {
  29000. DUK_D(DUK_DPRINT("debug error, skipping"));
  29001. break;
  29002. }
  29003. case DUK_DBG_MARKER_NOTIFY: {
  29004. DUK_D(DUK_DPRINT("debug notify, skipping"));
  29005. break;
  29006. }
  29007. default: {
  29008. DUK_D(DUK_DPRINT("invalid initial byte, drop connection: %d", (int) x));
  29009. goto fail;
  29010. }
  29011. } /* switch initial byte */
  29012. duk__debug_skip_to_eom(thr);
  29013. return;
  29014. fail:
  29015. DUK__SET_CONN_BROKEN(thr);
  29016. return;
  29017. }
  29018. DUK_INTERNAL duk_bool_t duk_debug_process_messages(duk_hthread *thr, duk_bool_t no_block) {
  29019. duk_context *ctx = (duk_context *) thr;
  29020. #if defined(DUK_USE_ASSERTIONS)
  29021. duk_idx_t entry_top;
  29022. #endif
  29023. duk_bool_t retval = 0;
  29024. DUK_ASSERT(thr != NULL);
  29025. DUK_UNREF(ctx);
  29026. #if defined(DUK_USE_ASSERTIONS)
  29027. entry_top = duk_get_top(ctx);
  29028. #endif
  29029. DUK_DD(DUK_DDPRINT("top at entry: %ld", (long) duk_get_top(ctx)));
  29030. for (;;) {
  29031. /* Process messages until we're no longer paused or we peek
  29032. * and see there's nothing to read right now.
  29033. */
  29034. DUK_DD(DUK_DDPRINT("top at loop top: %ld", (long) duk_get_top(ctx)));
  29035. if (thr->heap->dbg_read_cb == NULL) {
  29036. DUK_D(DUK_DPRINT("debug connection broken, stop processing messages"));
  29037. break;
  29038. } else if (!thr->heap->dbg_paused || no_block) {
  29039. if (!duk_debug_read_peek(thr)) {
  29040. DUK_D(DUK_DPRINT("processing debug message, peek indicated no data, stop processing"));
  29041. break;
  29042. }
  29043. DUK_D(DUK_DPRINT("processing debug message, peek indicated there is data, handle it"));
  29044. } else {
  29045. DUK_D(DUK_DPRINT("paused, process debug message, blocking if necessary"));
  29046. }
  29047. duk__debug_process_message(thr);
  29048. if (thr->heap->dbg_state_dirty) {
  29049. /* Executed something that may have affected status,
  29050. * resend.
  29051. */
  29052. duk_debug_send_status(thr);
  29053. thr->heap->dbg_state_dirty = 0;
  29054. }
  29055. retval = 1; /* processed one or more messages */
  29056. }
  29057. /* As an initial implementation, read flush after exiting the message
  29058. * loop.
  29059. */
  29060. duk_debug_read_flush(thr);
  29061. DUK_DD(DUK_DDPRINT("top at exit: %ld", (long) duk_get_top(ctx)));
  29062. #if defined(DUK_USE_ASSERTIONS)
  29063. /* Easy to get wrong, so assert for it. */
  29064. DUK_ASSERT(entry_top == duk_get_top(ctx));
  29065. #endif
  29066. return retval;
  29067. }
  29068. /*
  29069. * Breakpoint management
  29070. */
  29071. DUK_INTERNAL duk_small_int_t duk_debug_add_breakpoint(duk_hthread *thr, duk_hstring *filename, duk_uint32_t line) {
  29072. duk_heap *heap;
  29073. duk_breakpoint *b;
  29074. /* Caller must trigger recomputation of active breakpoint list. To
  29075. * ensure stale values are not used if that doesn't happen, clear the
  29076. * active breakpoint list here.
  29077. */
  29078. DUK_ASSERT(thr != NULL);
  29079. DUK_ASSERT(filename != NULL);
  29080. heap = thr->heap;
  29081. DUK_ASSERT(heap != NULL);
  29082. if (heap->dbg_breakpoint_count >= DUK_HEAP_MAX_BREAKPOINTS) {
  29083. DUK_D(DUK_DPRINT("failed to add breakpoint for %O:%ld, all breakpoint slots used",
  29084. (duk_heaphdr *) filename, (long) line));
  29085. return -1;
  29086. }
  29087. heap->dbg_breakpoints_active[0] = (duk_breakpoint *) NULL;
  29088. b = heap->dbg_breakpoints + (heap->dbg_breakpoint_count++);
  29089. b->filename = filename;
  29090. b->line = line;
  29091. DUK_HSTRING_INCREF(thr, filename);
  29092. return heap->dbg_breakpoint_count - 1; /* index */
  29093. }
  29094. DUK_INTERNAL duk_bool_t duk_debug_remove_breakpoint(duk_hthread *thr, duk_small_uint_t breakpoint_index) {
  29095. duk_heap *heap;
  29096. duk_hstring *h;
  29097. duk_breakpoint *b;
  29098. duk_size_t move_size;
  29099. /* Caller must trigger recomputation of active breakpoint list. To
  29100. * ensure stale values are not used if that doesn't happen, clear the
  29101. * active breakpoint list here.
  29102. */
  29103. DUK_ASSERT(thr != NULL);
  29104. heap = thr->heap;
  29105. DUK_ASSERT(heap != NULL);
  29106. DUK_ASSERT_DISABLE(breakpoint_index >= 0); /* unsigned */
  29107. if (breakpoint_index >= heap->dbg_breakpoint_count) {
  29108. DUK_D(DUK_DPRINT("invalid breakpoint index: %ld", (long) breakpoint_index));
  29109. return 0;
  29110. }
  29111. b = heap->dbg_breakpoints + breakpoint_index;
  29112. h = b->filename;
  29113. DUK_ASSERT(h != NULL);
  29114. move_size = sizeof(duk_breakpoint) * (heap->dbg_breakpoint_count - breakpoint_index - 1);
  29115. if (move_size > 0) {
  29116. DUK_MEMMOVE((void *) b,
  29117. (void *) (b + 1),
  29118. move_size);
  29119. }
  29120. heap->dbg_breakpoint_count--;
  29121. heap->dbg_breakpoints_active[0] = (duk_breakpoint *) NULL;
  29122. DUK_HSTRING_DECREF(thr, h); /* side effects */
  29123. /* Breakpoint entries above the used area are left as garbage. */
  29124. return 1;
  29125. }
  29126. #undef DUK__SET_CONN_BROKEN
  29127. #else /* DUK_USE_DEBUGGER_SUPPORT */
  29128. /* No debugger support. */
  29129. #endif /* DUK_USE_DEBUGGER_SUPPORT */
  29130. #line 1 "duk_error_augment.c"
  29131. /*
  29132. * Augmenting errors at their creation site and their throw site.
  29133. *
  29134. * When errors are created, traceback data is added by built-in code
  29135. * and a user error handler (if defined) can process or replace the
  29136. * error. Similarly, when errors are thrown, a user error handler
  29137. * (if defined) can process or replace the error.
  29138. *
  29139. * Augmentation and other processing at error creation time is nice
  29140. * because an error is only created once, but it may be thrown and
  29141. * rethrown multiple times. User error handler registered for processing
  29142. * an error at its throw site must be careful to handle rethrowing in
  29143. * a useful manner.
  29144. *
  29145. * Error augmentation may throw an internal error (e.g. alloc error).
  29146. *
  29147. * Ecmascript allows throwing any values, so all values cannot be
  29148. * augmented. Currently, the built-in augmentation at error creation
  29149. * only augments error values which are Error instances (= have the
  29150. * built-in Error.prototype in their prototype chain) and are also
  29151. * extensible. User error handlers have no limitations in this respect.
  29152. */
  29153. /* include removed: duk_internal.h */
  29154. /*
  29155. * Helper for calling a user error handler.
  29156. *
  29157. * 'thr' must be the currently active thread; the error handler is called
  29158. * in its context. The valstack of 'thr' must have the error value on
  29159. * top, and will be replaced by another error value based on the return
  29160. * value of the error handler.
  29161. *
  29162. * The helper calls duk_handle_call() recursively in protected mode.
  29163. * Before that call happens, no longjmps should happen; as a consequence,
  29164. * we must assume that the valstack contains enough temporary space for
  29165. * arguments and such.
  29166. *
  29167. * While the error handler runs, any errors thrown will not trigger a
  29168. * recursive error handler call (this is implemented using a heap level
  29169. * flag which will "follow" through any coroutines resumed inside the
  29170. * error handler). If the error handler is not callable or throws an
  29171. * error, the resulting error replaces the original error (for Duktape
  29172. * internal errors, duk_error_throw.c further substitutes this error with
  29173. * a DoubleError which is not ideal). This would be easy to change and
  29174. * even signal to the caller.
  29175. *
  29176. * The user error handler is stored in 'Duktape.errCreate' or
  29177. * 'Duktape.errThrow' depending on whether we're augmenting the error at
  29178. * creation or throw time. There are several alternatives to this approach,
  29179. * see doc/error-objects.txt for discussion.
  29180. *
  29181. * Note: since further longjmp()s may occur while calling the error handler
  29182. * (for many reasons, e.g. a labeled 'break' inside the handler), the
  29183. * caller can make no assumptions on the thr->heap->lj state after the
  29184. * call (this affects especially duk_error_throw.c). This is not an issue
  29185. * as long as the caller writes to the lj state only after the error handler
  29186. * finishes.
  29187. */
  29188. #if defined(DUK_USE_ERRTHROW) || defined(DUK_USE_ERRCREATE)
  29189. DUK_LOCAL void duk__err_augment_user(duk_hthread *thr, duk_small_uint_t stridx_cb) {
  29190. duk_context *ctx = (duk_context *) thr;
  29191. duk_tval *tv_hnd;
  29192. duk_small_uint_t call_flags;
  29193. duk_int_t rc;
  29194. DUK_ASSERT(thr != NULL);
  29195. DUK_ASSERT(thr->heap != NULL);
  29196. DUK_ASSERT_DISABLE(stridx_cb >= 0); /* unsigned */
  29197. DUK_ASSERT(stridx_cb < DUK_HEAP_NUM_STRINGS);
  29198. if (DUK_HEAP_HAS_ERRHANDLER_RUNNING(thr->heap)) {
  29199. DUK_DD(DUK_DDPRINT("recursive call to error handler, ignore"));
  29200. return;
  29201. }
  29202. /*
  29203. * Check whether or not we have an error handler.
  29204. *
  29205. * We must be careful of not triggering an error when looking up the
  29206. * property. For instance, if the property is a getter, we don't want
  29207. * to call it, only plain values are allowed. The value, if it exists,
  29208. * is not checked. If the value is not a function, a TypeError happens
  29209. * when it is called and that error replaces the original one.
  29210. */
  29211. DUK_ASSERT_VALSTACK_SPACE(thr, 4); /* 3 entries actually needed below */
  29212. /* [ ... errval ] */
  29213. if (thr->builtins[DUK_BIDX_DUKTAPE] == NULL) {
  29214. /* When creating built-ins, some of the built-ins may not be set
  29215. * and we want to tolerate that when throwing errors.
  29216. */
  29217. DUK_DD(DUK_DDPRINT("error occurred when DUK_BIDX_DUKTAPE is NULL, ignoring"));
  29218. return;
  29219. }
  29220. tv_hnd = duk_hobject_find_existing_entry_tval_ptr(thr->heap,
  29221. thr->builtins[DUK_BIDX_DUKTAPE],
  29222. DUK_HTHREAD_GET_STRING(thr, stridx_cb));
  29223. if (tv_hnd == NULL) {
  29224. DUK_DD(DUK_DDPRINT("error handler does not exist or is not a plain value: %!T",
  29225. (duk_tval *) tv_hnd));
  29226. return;
  29227. }
  29228. DUK_DDD(DUK_DDDPRINT("error handler dump (callability not checked): %!T",
  29229. (duk_tval *) tv_hnd));
  29230. duk_push_tval(ctx, tv_hnd);
  29231. /* [ ... errval errhandler ] */
  29232. duk_insert(ctx, -2); /* -> [ ... errhandler errval ] */
  29233. duk_push_undefined(ctx);
  29234. duk_insert(ctx, -2); /* -> [ ... errhandler undefined(= this) errval ] */
  29235. /* [ ... errhandler undefined errval ] */
  29236. /*
  29237. * DUK_CALL_FLAG_IGNORE_RECLIMIT causes duk_handle_call() to ignore C
  29238. * recursion depth limit (and won't increase it either). This is
  29239. * dangerous, but useful because it allows the error handler to run
  29240. * even if the original error is caused by C recursion depth limit.
  29241. *
  29242. * The heap level DUK_HEAP_FLAG_ERRHANDLER_RUNNING is set for the
  29243. * duration of the error handler and cleared afterwards. This flag
  29244. * prevents the error handler from running recursively. The flag is
  29245. * heap level so that the flag properly controls even coroutines
  29246. * launched by an error handler. Since the flag is heap level, it is
  29247. * critical to restore it correctly.
  29248. *
  29249. * We ignore errors now: a success return and an error value both
  29250. * replace the original error value. (This would be easy to change.)
  29251. */
  29252. DUK_ASSERT(!DUK_HEAP_HAS_ERRHANDLER_RUNNING(thr->heap)); /* since no recursive error handler calls */
  29253. DUK_HEAP_SET_ERRHANDLER_RUNNING(thr->heap);
  29254. call_flags = DUK_CALL_FLAG_PROTECTED |
  29255. DUK_CALL_FLAG_IGNORE_RECLIMIT; /* protected, ignore reclimit, not constructor */
  29256. rc = duk_handle_call(thr,
  29257. 1, /* num args */
  29258. call_flags); /* call_flags */
  29259. DUK_UNREF(rc); /* no need to check now: both success and error are OK */
  29260. DUK_ASSERT(DUK_HEAP_HAS_ERRHANDLER_RUNNING(thr->heap));
  29261. DUK_HEAP_CLEAR_ERRHANDLER_RUNNING(thr->heap);
  29262. /* [ ... errval ] */
  29263. }
  29264. #endif /* DUK_USE_ERRTHROW || DUK_USE_ERRHANDLE */
  29265. /*
  29266. * Add tracedata to an error on the stack top.
  29267. */
  29268. #ifdef DUK_USE_TRACEBACKS
  29269. DUK_LOCAL void duk__add_traceback(duk_hthread *thr, duk_hthread *thr_callstack, const char *c_filename, duk_int_t c_line, duk_bool_t noblame_fileline) {
  29270. duk_context *ctx = (duk_context *) thr;
  29271. duk_small_uint_t depth;
  29272. duk_int_t i, i_min;
  29273. duk_uarridx_t arr_idx;
  29274. duk_double_t d;
  29275. DUK_ASSERT(thr != NULL);
  29276. DUK_ASSERT(thr_callstack != NULL);
  29277. DUK_ASSERT(ctx != NULL);
  29278. /* [ ... error ] */
  29279. /*
  29280. * The traceback format is pretty arcane in an attempt to keep it compact
  29281. * and cheap to create. It may change arbitrarily from version to version.
  29282. * It should be decoded/accessed through version specific accessors only.
  29283. *
  29284. * See doc/error-objects.txt.
  29285. */
  29286. DUK_DDD(DUK_DDDPRINT("adding traceback to object: %!T",
  29287. (duk_tval *) duk_get_tval(ctx, -1)));
  29288. duk_push_array(ctx); /* XXX: specify array size, as we know it */
  29289. arr_idx = 0;
  29290. /* compiler SyntaxErrors (and other errors) come first; blame the source
  29291. * code file/line primarily.
  29292. */
  29293. if (thr->compile_ctx != NULL && thr->compile_ctx->h_filename != NULL) {
  29294. duk_push_hstring(ctx, thr->compile_ctx->h_filename);
  29295. duk_xdef_prop_index_wec(ctx, -2, arr_idx);
  29296. arr_idx++;
  29297. duk_push_uint(ctx, (duk_uint_t) thr->compile_ctx->curr_token.start_line); /* (flags<<32) + (line), flags = 0 */
  29298. duk_xdef_prop_index_wec(ctx, -2, arr_idx);
  29299. arr_idx++;
  29300. }
  29301. /* filename/line from C macros (__FILE__, __LINE__) are added as an
  29302. * entry with a special format: (string, number). The number contains
  29303. * the line and flags.
  29304. */
  29305. /* XXX: optimize: allocate an array part to the necessary size (upwards
  29306. * estimate) and fill in the values directly into the array part; finally
  29307. * update 'length'.
  29308. */
  29309. /* XXX: using duk_put_prop_index() would cause obscure error cases when Array.prototype
  29310. * has write-protected array index named properties. This was seen as DoubleErrors
  29311. * in e.g. some test262 test cases. Using duk_xdef_prop_index() is better but heavier.
  29312. * The best fix is to fill in the tracedata directly into the array part.
  29313. */
  29314. /* [ ... error arr ] */
  29315. if (c_filename) {
  29316. duk_push_string(ctx, c_filename);
  29317. duk_xdef_prop_index_wec(ctx, -2, arr_idx);
  29318. arr_idx++;
  29319. d = (noblame_fileline ? ((duk_double_t) DUK_TB_FLAG_NOBLAME_FILELINE) * DUK_DOUBLE_2TO32 : 0.0) +
  29320. (duk_double_t) c_line;
  29321. duk_push_number(ctx, d);
  29322. duk_xdef_prop_index_wec(ctx, -2, arr_idx);
  29323. arr_idx++;
  29324. }
  29325. /* traceback depth doesn't take into account the filename/line
  29326. * special handling above (intentional)
  29327. */
  29328. depth = DUK_USE_TRACEBACK_DEPTH;
  29329. i_min = (thr_callstack->callstack_top > (duk_size_t) depth ? (duk_int_t) (thr_callstack->callstack_top - depth) : 0);
  29330. DUK_ASSERT(i_min >= 0);
  29331. /* [ ... error arr ] */
  29332. DUK_ASSERT(thr_callstack->callstack_top <= DUK_INT_MAX); /* callstack limits */
  29333. for (i = (duk_int_t) (thr_callstack->callstack_top - 1); i >= i_min; i--) {
  29334. duk_uint32_t pc;
  29335. /*
  29336. * Note: each API operation potentially resizes the callstack,
  29337. * so be careful to re-lookup after every operation. Currently
  29338. * these is no issue because we don't store a temporary 'act'
  29339. * pointer at all. (This would be a non-issue if we operated
  29340. * directly on the array part.)
  29341. */
  29342. /* [... arr] */
  29343. DUK_ASSERT_DISABLE(thr_callstack->callstack[i].pc >= 0); /* unsigned */
  29344. /* Add function object. */
  29345. duk_push_tval(ctx, &(thr_callstack->callstack + i)->tv_func);
  29346. duk_xdef_prop_index_wec(ctx, -2, arr_idx);
  29347. arr_idx++;
  29348. /* Add a number containing: pc, activation flags.
  29349. *
  29350. * PC points to next instruction, find offending PC. Note that
  29351. * PC == 0 for native code.
  29352. */
  29353. pc = thr_callstack->callstack[i].pc;
  29354. if (pc > 0) {
  29355. pc--;
  29356. }
  29357. DUK_ASSERT_DISABLE(pc >= 0); /* unsigned */
  29358. DUK_ASSERT((duk_double_t) pc < DUK_DOUBLE_2TO32); /* assume PC is at most 32 bits and non-negative */
  29359. d = ((duk_double_t) thr_callstack->callstack[i].flags) * DUK_DOUBLE_2TO32 + (duk_double_t) pc;
  29360. duk_push_number(ctx, d); /* -> [... arr num] */
  29361. duk_xdef_prop_index_wec(ctx, -2, arr_idx);
  29362. arr_idx++;
  29363. }
  29364. /* XXX: set with duk_hobject_set_length() when tracedata is filled directly */
  29365. duk_push_uint(ctx, (duk_uint_t) arr_idx);
  29366. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_WC);
  29367. /* [ ... error arr ] */
  29368. duk_xdef_prop_stridx_wec(ctx, -2, DUK_STRIDX_INT_TRACEDATA); /* -> [ ... error ] */
  29369. }
  29370. #endif /* DUK_USE_TRACEBACKS */
  29371. #if defined(DUK_USE_AUGMENT_ERROR_CREATE)
  29372. DUK_LOCAL void duk__err_augment_builtin_throw(duk_hthread *thr, duk_hthread *thr_callstack, const char *c_filename, duk_int_t c_line, duk_small_int_t noblame_fileline, duk_hobject *obj) {
  29373. duk_context *ctx = (duk_context *) thr;
  29374. #ifdef DUK_USE_ASSERTIONS
  29375. duk_int_t entry_top;
  29376. #endif
  29377. #ifdef DUK_USE_ASSERTIONS
  29378. entry_top = duk_get_top(ctx);
  29379. #endif
  29380. DUK_ASSERT(obj != NULL);
  29381. DUK_UNREF(obj); /* unreferenced w/o tracebacks */
  29382. DUK_UNREF(ctx); /* unreferenced w/ tracebacks */
  29383. #ifdef DUK_USE_TRACEBACKS
  29384. /*
  29385. * If tracebacks are enabled, the '_Tracedata' property is the only
  29386. * thing we need: 'fileName' and 'lineNumber' are virtual properties
  29387. * which use '_Tracedata'.
  29388. */
  29389. if (duk_hobject_hasprop_raw(thr, obj, DUK_HTHREAD_STRING_INT_TRACEDATA(thr))) {
  29390. DUK_DDD(DUK_DDDPRINT("error value already has a '_Tracedata' property, not modifying it"));
  29391. } else {
  29392. duk__add_traceback(thr, thr_callstack, c_filename, c_line, noblame_fileline);
  29393. }
  29394. #else
  29395. /*
  29396. * If tracebacks are disabled, 'fileName' and 'lineNumber' are added
  29397. * as plain own properties. Since Error.prototype has accessors of
  29398. * the same name, we need to define own properties directly (cannot
  29399. * just use e.g. duk_put_prop_stridx). Existing properties are not
  29400. * overwritten in case they already exist.
  29401. */
  29402. if (thr->compile_ctx != NULL && thr->compile_ctx->h_filename != NULL) {
  29403. /* Compiler SyntaxError (or other error) gets the primary blame. */
  29404. duk_push_hstring(ctx, thr->compile_ctx->h_filename);
  29405. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_FILE_NAME, DUK_PROPDESC_FLAGS_WC | DUK_PROPDESC_FLAG_NO_OVERWRITE);
  29406. duk_push_uint(ctx, (duk_uint_t) thr->compile_ctx->curr_token.start_line);
  29407. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LINE_NUMBER, DUK_PROPDESC_FLAGS_WC | DUK_PROPDESC_FLAG_NO_OVERWRITE);
  29408. } else if (c_filename && !noblame_fileline) {
  29409. /* XXX: file/line is disabled in minimal builds, so disable this too
  29410. * when appropriate.
  29411. */
  29412. duk_push_string(ctx, c_filename);
  29413. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_FILE_NAME, DUK_PROPDESC_FLAGS_WC | DUK_PROPDESC_FLAG_NO_OVERWRITE);
  29414. duk_push_int(ctx, c_line);
  29415. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LINE_NUMBER, DUK_PROPDESC_FLAGS_WC | DUK_PROPDESC_FLAG_NO_OVERWRITE);
  29416. } else if (thr_callstack->callstack_top > 0) {
  29417. duk_activation *act;
  29418. duk_hobject *func;
  29419. act = thr_callstack->callstack + thr_callstack->callstack_top - 1;
  29420. DUK_ASSERT(act >= thr_callstack->callstack && act < thr_callstack->callstack + thr_callstack->callstack_size);
  29421. func = DUK_ACT_GET_FUNC(act);
  29422. if (func) {
  29423. duk_uint32_t pc;
  29424. /* PC points to next instruction, find offending PC. Note that
  29425. * PC == 0 for native code.
  29426. */
  29427. pc = act->pc;
  29428. if (pc > 0) {
  29429. pc--;
  29430. }
  29431. DUK_ASSERT_DISABLE(pc >= 0); /* unsigned */
  29432. DUK_ASSERT((duk_double_t) pc < DUK_DOUBLE_2TO32); /* assume PC is at most 32 bits and non-negative */
  29433. act = NULL; /* invalidated by pushes, so get out of the way */
  29434. duk_push_hobject(ctx, func);
  29435. /* [ ... error func ] */
  29436. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_FILE_NAME);
  29437. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_FILE_NAME, DUK_PROPDESC_FLAGS_WC | DUK_PROPDESC_FLAG_NO_OVERWRITE);
  29438. #if defined(DUK_USE_PC2LINE)
  29439. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  29440. duk_uint32_t ecma_line;
  29441. #if 0
  29442. duk_push_u32(ctx, pc);
  29443. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_PC, DUK_PROPDESC_FLAGS_WC | DUK_PROPDESC_FLAGS_NO_OVERWRITE);
  29444. #endif
  29445. ecma_line = duk_hobject_pc2line_query(ctx, -1, (duk_uint_fast32_t) pc);
  29446. if (ecma_line > 0) {
  29447. duk_push_u32(ctx, (duk_uint32_t) ecma_line); /* -> [ ... error func line ] */
  29448. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_LINE_NUMBER, DUK_PROPDESC_FLAGS_WC | DUK_PROPDESC_FLAG_NO_OVERWRITE);
  29449. }
  29450. } else {
  29451. /* Native function, no relevant lineNumber. */
  29452. }
  29453. #endif /* DUK_USE_PC2LINE */
  29454. duk_pop(ctx);
  29455. }
  29456. }
  29457. #endif /* DUK_USE_TRACEBACKS */
  29458. #ifdef DUK_USE_ASSERTIONS
  29459. DUK_ASSERT(duk_get_top(ctx) == entry_top);
  29460. #endif
  29461. }
  29462. #endif /* DUK_USE_AUGMENT_ERROR_CREATE */
  29463. /*
  29464. * Augment an error at creation time with _Tracedata/fileName/lineNumber
  29465. * and allow a user error handler (if defined) to process/replace the error.
  29466. * The error to be augmented is at the stack top.
  29467. *
  29468. * thr: thread containing the error value
  29469. * thr_callstack: thread which should be used for generating callstack etc.
  29470. * c_filename: C __FILE__ related to the error
  29471. * c_line: C __LINE__ related to the error
  29472. * noblame_fileline: if true, don't fileName/line as error source, otherwise use traceback
  29473. * (needed because user code filename/line are reported but internal ones
  29474. * are not)
  29475. *
  29476. * XXX: rename noblame_fileline to flags field; combine it to some existing
  29477. * field (there are only a few call sites so this may not be worth it).
  29478. */
  29479. #if defined(DUK_USE_AUGMENT_ERROR_CREATE)
  29480. DUK_INTERNAL void duk_err_augment_error_create(duk_hthread *thr, duk_hthread *thr_callstack, const char *c_filename, duk_int_t c_line, duk_bool_t noblame_fileline) {
  29481. duk_context *ctx = (duk_context *) thr;
  29482. duk_hobject *obj;
  29483. DUK_ASSERT(thr != NULL);
  29484. DUK_ASSERT(thr_callstack != NULL);
  29485. DUK_ASSERT(ctx != NULL);
  29486. /* [ ... error ] */
  29487. /*
  29488. * Criteria for augmenting:
  29489. *
  29490. * - augmentation enabled in build (naturally)
  29491. * - error value internal prototype chain contains the built-in
  29492. * Error prototype object (i.e. 'val instanceof Error')
  29493. *
  29494. * Additional criteria for built-in augmenting:
  29495. *
  29496. * - error value is an extensible object
  29497. */
  29498. obj = duk_get_hobject(ctx, -1);
  29499. if (!obj) {
  29500. DUK_DDD(DUK_DDDPRINT("value is not an object, skip both built-in and user augment"));
  29501. return;
  29502. }
  29503. if (!duk_hobject_prototype_chain_contains(thr, obj, thr->builtins[DUK_BIDX_ERROR_PROTOTYPE], 1 /*ignore_loop*/)) {
  29504. /* If the value has a prototype loop, it's critical not to
  29505. * throw here. Instead, assume the value is not to be
  29506. * augmented.
  29507. */
  29508. DUK_DDD(DUK_DDDPRINT("value is not an error instance, skip both built-in and user augment"));
  29509. return;
  29510. }
  29511. if (DUK_HOBJECT_HAS_EXTENSIBLE(obj)) {
  29512. DUK_DDD(DUK_DDDPRINT("error meets criteria, built-in augment"));
  29513. duk__err_augment_builtin_throw(thr, thr_callstack, c_filename, c_line, noblame_fileline, obj);
  29514. } else {
  29515. DUK_DDD(DUK_DDDPRINT("error does not meet criteria, no built-in augment"));
  29516. }
  29517. /* [ ... error ] */
  29518. #if defined(DUK_USE_ERRCREATE)
  29519. duk__err_augment_user(thr, DUK_STRIDX_ERR_CREATE);
  29520. #endif
  29521. }
  29522. #endif /* DUK_USE_AUGMENT_ERROR_CREATE */
  29523. /*
  29524. * Augment an error at throw time; allow a user error handler (if defined)
  29525. * to process/replace the error. The error to be augmented is at the
  29526. * stack top.
  29527. */
  29528. #if defined(DUK_USE_AUGMENT_ERROR_THROW)
  29529. DUK_INTERNAL void duk_err_augment_error_throw(duk_hthread *thr) {
  29530. #if defined(DUK_USE_ERRTHROW)
  29531. duk__err_augment_user(thr, DUK_STRIDX_ERR_THROW);
  29532. #endif /* DUK_USE_ERRTHROW */
  29533. }
  29534. #endif /* DUK_USE_AUGMENT_ERROR_THROW */
  29535. #line 1 "duk_error_longjmp.c"
  29536. /*
  29537. * Do a longjmp call, calling the fatal error handler if no
  29538. * catchpoint exists.
  29539. */
  29540. /* include removed: duk_internal.h */
  29541. DUK_INTERNAL void duk_err_longjmp(duk_hthread *thr) {
  29542. DUK_ASSERT(thr != NULL);
  29543. if (!thr->heap->lj.jmpbuf_ptr) {
  29544. /*
  29545. * If we don't have a jmpbuf_ptr, there is little we can do
  29546. * except panic. The caller's expectation is that we never
  29547. * return.
  29548. */
  29549. DUK_D(DUK_DPRINT("uncaught error: type=%d iserror=%d value1=%!T value2=%!T",
  29550. (int) thr->heap->lj.type, (int) thr->heap->lj.iserror,
  29551. &thr->heap->lj.value1, &thr->heap->lj.value2));
  29552. duk_fatal((duk_context *) thr, DUK_ERR_UNCAUGHT_ERROR, "uncaught error");
  29553. DUK_UNREACHABLE();
  29554. }
  29555. DUK_LONGJMP(thr->heap->lj.jmpbuf_ptr->jb);
  29556. DUK_UNREACHABLE();
  29557. }
  29558. #line 1 "duk_error_misc.c"
  29559. /*
  29560. * Error helpers
  29561. */
  29562. /* include removed: duk_internal.h */
  29563. /*
  29564. * Get prototype object for an integer error code.
  29565. */
  29566. DUK_INTERNAL duk_hobject *duk_error_prototype_from_code(duk_hthread *thr, duk_errcode_t code) {
  29567. switch (code) {
  29568. case DUK_ERR_EVAL_ERROR:
  29569. return thr->builtins[DUK_BIDX_EVAL_ERROR_PROTOTYPE];
  29570. case DUK_ERR_RANGE_ERROR:
  29571. return thr->builtins[DUK_BIDX_RANGE_ERROR_PROTOTYPE];
  29572. case DUK_ERR_REFERENCE_ERROR:
  29573. return thr->builtins[DUK_BIDX_REFERENCE_ERROR_PROTOTYPE];
  29574. case DUK_ERR_SYNTAX_ERROR:
  29575. return thr->builtins[DUK_BIDX_SYNTAX_ERROR_PROTOTYPE];
  29576. case DUK_ERR_TYPE_ERROR:
  29577. return thr->builtins[DUK_BIDX_TYPE_ERROR_PROTOTYPE];
  29578. case DUK_ERR_URI_ERROR:
  29579. return thr->builtins[DUK_BIDX_URI_ERROR_PROTOTYPE];
  29580. /* XXX: more specific error classes? */
  29581. case DUK_ERR_UNIMPLEMENTED_ERROR:
  29582. case DUK_ERR_INTERNAL_ERROR:
  29583. case DUK_ERR_ALLOC_ERROR:
  29584. case DUK_ERR_ASSERTION_ERROR:
  29585. case DUK_ERR_API_ERROR:
  29586. case DUK_ERR_ERROR:
  29587. default:
  29588. return thr->builtins[DUK_BIDX_ERROR_PROTOTYPE];
  29589. }
  29590. }
  29591. /*
  29592. * Exposed helper for setting up heap longjmp state.
  29593. */
  29594. DUK_INTERNAL void duk_err_setup_heap_ljstate(duk_hthread *thr, duk_small_int_t lj_type) {
  29595. duk_tval tv_tmp;
  29596. thr->heap->lj.type = lj_type;
  29597. DUK_ASSERT(thr->valstack_top > thr->valstack);
  29598. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value1);
  29599. DUK_TVAL_SET_TVAL(&thr->heap->lj.value1, thr->valstack_top - 1);
  29600. DUK_TVAL_INCREF(thr, &thr->heap->lj.value1);
  29601. DUK_TVAL_DECREF(thr, &tv_tmp);
  29602. duk_pop((duk_context *) thr);
  29603. }
  29604. #line 1 "duk_error_throw.c"
  29605. /*
  29606. * Create and throw an Ecmascript error object based on a code and a message.
  29607. *
  29608. * Used when we throw errors internally. Ecmascript generated error objects
  29609. * are created by Ecmascript code, and the throwing is handled by the bytecode
  29610. * executor.
  29611. */
  29612. /* include removed: duk_internal.h */
  29613. /*
  29614. * Create and throw an error (originating from Duktape internally)
  29615. *
  29616. * Push an error object on top of the stack, possibly throw augmenting
  29617. * the error, and finally longjmp.
  29618. *
  29619. * If an error occurs while we're dealing with the current error, we might
  29620. * enter an infinite recursion loop. This is prevented by detecting a
  29621. * "double fault" through the heap->handling_error flag; the recursion
  29622. * then stops at the second level.
  29623. */
  29624. #ifdef DUK_USE_VERBOSE_ERRORS
  29625. DUK_INTERNAL void duk_err_create_and_throw(duk_hthread *thr, duk_errcode_t code, const char *msg, const char *filename, duk_int_t line) {
  29626. #else
  29627. DUK_INTERNAL void duk_err_create_and_throw(duk_hthread *thr, duk_errcode_t code) {
  29628. #endif
  29629. duk_context *ctx = (duk_context *) thr;
  29630. duk_bool_t double_error = thr->heap->handling_error;
  29631. #ifdef DUK_USE_VERBOSE_ERRORS
  29632. DUK_DD(DUK_DDPRINT("duk_err_create_and_throw(): code=%ld, msg=%s, filename=%s, line=%ld",
  29633. (long) code, (const char *) msg,
  29634. (const char *) filename, (long) line));
  29635. #else
  29636. DUK_DD(DUK_DDPRINT("duk_err_create_and_throw(): code=%ld", (long) code));
  29637. #endif
  29638. DUK_ASSERT(thr != NULL);
  29639. DUK_ASSERT(ctx != NULL);
  29640. thr->heap->handling_error = 1;
  29641. /*
  29642. * Create and push an error object onto the top of stack.
  29643. * If a "double error" occurs, use a fixed error instance
  29644. * to avoid further trouble.
  29645. */
  29646. /* XXX: if attempt to push beyond allocated valstack, this double fault
  29647. * handling fails miserably. We should really write the double error
  29648. * directly to thr->heap->lj.value1 and avoid valstack use entirely.
  29649. */
  29650. if (double_error) {
  29651. if (thr->builtins[DUK_BIDX_DOUBLE_ERROR]) {
  29652. DUK_D(DUK_DPRINT("double fault detected -> push built-in fixed 'double error' instance"));
  29653. duk_push_hobject_bidx(ctx, DUK_BIDX_DOUBLE_ERROR);
  29654. } else {
  29655. DUK_D(DUK_DPRINT("double fault detected; there is no built-in fixed 'double error' instance "
  29656. "-> push the error code as a number"));
  29657. duk_push_int(ctx, (duk_int_t) code);
  29658. }
  29659. } else {
  29660. /* Error object is augmented at its creation here. */
  29661. duk_require_stack(ctx, 1);
  29662. /* XXX: unnecessary '%s' formatting here, but cannot use
  29663. * 'msg' as a format string directly.
  29664. */
  29665. #ifdef DUK_USE_VERBOSE_ERRORS
  29666. duk_push_error_object_raw(ctx,
  29667. code | DUK_ERRCODE_FLAG_NOBLAME_FILELINE,
  29668. filename,
  29669. line,
  29670. "%s",
  29671. (const char *) msg);
  29672. #else
  29673. duk_push_error_object_raw(ctx,
  29674. code | DUK_ERRCODE_FLAG_NOBLAME_FILELINE,
  29675. NULL,
  29676. 0,
  29677. NULL);
  29678. #endif
  29679. }
  29680. /*
  29681. * Augment error (throw time), unless alloc/double error
  29682. */
  29683. if (double_error || code == DUK_ERR_ALLOC_ERROR) {
  29684. DUK_D(DUK_DPRINT("alloc or double error: skip throw augmenting to avoid further trouble"));
  29685. } else {
  29686. #if defined(DUK_USE_AUGMENT_ERROR_THROW)
  29687. DUK_DDD(DUK_DDDPRINT("THROW ERROR (INTERNAL): %!iT (before throw augment)",
  29688. (duk_tval *) duk_get_tval(ctx, -1)));
  29689. duk_err_augment_error_throw(thr);
  29690. #endif
  29691. }
  29692. /*
  29693. * Finally, longjmp
  29694. */
  29695. thr->heap->handling_error = 0;
  29696. duk_err_setup_heap_ljstate(thr, DUK_LJ_TYPE_THROW);
  29697. DUK_DDD(DUK_DDDPRINT("THROW ERROR (INTERNAL): %!iT, %!iT (after throw augment)",
  29698. (duk_tval *) &thr->heap->lj.value1, (duk_tval *) &thr->heap->lj.value2));
  29699. duk_err_longjmp(thr);
  29700. DUK_UNREACHABLE();
  29701. }
  29702. /*
  29703. * Helper for C function call negative return values.
  29704. */
  29705. DUK_INTERNAL void duk_error_throw_from_negative_rc(duk_hthread *thr, duk_ret_t rc) {
  29706. duk_context *ctx = (duk_context *) thr;
  29707. const char *msg;
  29708. duk_errcode_t code;
  29709. DUK_ASSERT(thr != NULL);
  29710. DUK_ASSERT(rc < 0);
  29711. /* XXX: this generates quite large code - perhaps select the error
  29712. * class based on the code and then just use the error 'name'?
  29713. */
  29714. code = -rc;
  29715. switch (rc) {
  29716. case DUK_RET_UNIMPLEMENTED_ERROR: msg = "unimplemented"; break;
  29717. case DUK_RET_UNSUPPORTED_ERROR: msg = "unsupported"; break;
  29718. case DUK_RET_INTERNAL_ERROR: msg = "internal"; break;
  29719. case DUK_RET_ALLOC_ERROR: msg = "alloc"; break;
  29720. case DUK_RET_ASSERTION_ERROR: msg = "assertion"; break;
  29721. case DUK_RET_API_ERROR: msg = "api"; break;
  29722. case DUK_RET_UNCAUGHT_ERROR: msg = "uncaught"; break;
  29723. case DUK_RET_ERROR: msg = "error"; break;
  29724. case DUK_RET_EVAL_ERROR: msg = "eval"; break;
  29725. case DUK_RET_RANGE_ERROR: msg = "range"; break;
  29726. case DUK_RET_REFERENCE_ERROR: msg = "reference"; break;
  29727. case DUK_RET_SYNTAX_ERROR: msg = "syntax"; break;
  29728. case DUK_RET_TYPE_ERROR: msg = "type"; break;
  29729. case DUK_RET_URI_ERROR: msg = "uri"; break;
  29730. default: msg = "unknown"; break;
  29731. }
  29732. DUK_ASSERT(msg != NULL);
  29733. /*
  29734. * The __FILE__ and __LINE__ information is intentionally not used in the
  29735. * creation of the error object, as it isn't useful in the tracedata. The
  29736. * tracedata still contains the function which returned the negative return
  29737. * code, and having the file/line of this function isn't very useful.
  29738. */
  29739. duk_error_raw(ctx, code, NULL, 0, "%s error (rc %ld)", (const char *) msg, (long) rc);
  29740. DUK_UNREACHABLE();
  29741. }
  29742. #line 1 "duk_hbuffer_alloc.c"
  29743. /*
  29744. * duk_hbuffer allocation and freeing.
  29745. */
  29746. /* include removed: duk_internal.h */
  29747. DUK_INTERNAL duk_hbuffer *duk_hbuffer_alloc(duk_heap *heap, duk_size_t size, duk_small_uint_t flags) {
  29748. duk_hbuffer *res = NULL;
  29749. duk_size_t alloc_size;
  29750. DUK_DDD(DUK_DDDPRINT("allocate hbuffer"));
  29751. /* Size sanity check. Should not be necessary because caller is
  29752. * required to check this, but we don't want to cause a segfault
  29753. * if the size wraps either in duk_size_t computation or when
  29754. * storing the size in a 16-bit field.
  29755. */
  29756. if (size > DUK_HBUFFER_MAX_BYTELEN) {
  29757. DUK_D(DUK_DPRINT("hbuffer alloc failed: size too large: %ld", (long) size));
  29758. return NULL;
  29759. }
  29760. if (flags & DUK_BUF_FLAG_DYNAMIC) {
  29761. alloc_size = sizeof(duk_hbuffer_dynamic);
  29762. } else {
  29763. alloc_size = sizeof(duk_hbuffer_fixed) + size;
  29764. DUK_ASSERT(alloc_size >= sizeof(duk_hbuffer_fixed)); /* no wrapping */
  29765. }
  29766. res = (duk_hbuffer *) DUK_ALLOC(heap, alloc_size);
  29767. if (!res) {
  29768. goto error;
  29769. }
  29770. /* zero everything unless requested not to do so */
  29771. #if defined(DUK_USE_ZERO_BUFFER_DATA)
  29772. DUK_MEMZERO((void *) res,
  29773. (flags & DUK_BUF_FLAG_NOZERO) ?
  29774. ((flags & DUK_BUF_FLAG_DYNAMIC) ?
  29775. sizeof(duk_hbuffer_dynamic) :
  29776. sizeof(duk_hbuffer_fixed)) :
  29777. alloc_size);
  29778. #else
  29779. DUK_MEMZERO((void *) res,
  29780. (flags & DUK_BUF_FLAG_DYNAMIC) ? sizeof(duk_hbuffer_dynamic) : sizeof(duk_hbuffer_fixed));
  29781. #endif
  29782. if (flags & DUK_BUF_FLAG_DYNAMIC) {
  29783. duk_hbuffer_dynamic *h = (duk_hbuffer_dynamic *) res;
  29784. void *ptr;
  29785. if (size > 0) {
  29786. DUK_DDD(DUK_DDDPRINT("dynamic buffer with nonzero size, alloc actual buffer"));
  29787. #ifdef DUK_USE_ZERO_BUFFER_DATA
  29788. ptr = DUK_ALLOC_ZEROED(heap, size);
  29789. #else
  29790. ptr = DUK_ALLOC(heap, size);
  29791. #endif
  29792. if (!ptr) {
  29793. /* Because size > 0, NULL check is correct */
  29794. goto error;
  29795. }
  29796. DUK_HBUFFER_DYNAMIC_SET_DATA_PTR(heap, h, ptr);
  29797. DUK_HBUFFER_DYNAMIC_SET_ALLOC_SIZE(h, size); /* snug */
  29798. } else {
  29799. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  29800. h->curr_alloc = NULL;
  29801. #endif
  29802. DUK_ASSERT(DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(h) == 0);
  29803. }
  29804. }
  29805. DUK_HBUFFER_SET_SIZE(res, size);
  29806. DUK_HEAPHDR_SET_TYPE(&res->hdr, DUK_HTYPE_BUFFER);
  29807. if (flags & DUK_BUF_FLAG_DYNAMIC) {
  29808. DUK_HBUFFER_SET_DYNAMIC(res);
  29809. }
  29810. DUK_HEAP_INSERT_INTO_HEAP_ALLOCATED(heap, &res->hdr);
  29811. DUK_DDD(DUK_DDDPRINT("allocated hbuffer: %p", (void *) res));
  29812. return res;
  29813. error:
  29814. DUK_DD(DUK_DDPRINT("hbuffer allocation failed"));
  29815. DUK_FREE(heap, res);
  29816. return NULL;
  29817. }
  29818. /* For indirect allocs. */
  29819. DUK_INTERNAL void *duk_hbuffer_get_dynalloc_ptr(duk_heap *heap, void *ud) {
  29820. duk_hbuffer_dynamic *buf = (duk_hbuffer_dynamic *) ud;
  29821. DUK_UNREF(heap);
  29822. return (void *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(heap, buf);
  29823. }
  29824. #line 1 "duk_hbuffer_ops.c"
  29825. /*
  29826. * duk_hbuffer operations such as resizing and inserting/appending data to
  29827. * a dynamic buffer.
  29828. *
  29829. * Append operations append to the end of the buffer and they are relatively
  29830. * efficient: the buffer is grown with a "spare" part relative to the buffer
  29831. * size to minimize reallocations. Insert operations need to move existing
  29832. * data forward in the buffer with memmove() and are not very efficient.
  29833. * They are used e.g. by the regexp compiler to "backpatch" regexp bytecode.
  29834. */
  29835. /* include removed: duk_internal.h */
  29836. /*
  29837. * Resizing
  29838. */
  29839. DUK_LOCAL duk_size_t duk__add_spare(duk_size_t size) {
  29840. duk_size_t spare = (size / DUK_HBUFFER_SPARE_DIVISOR) + DUK_HBUFFER_SPARE_ADD;
  29841. duk_size_t res;
  29842. res = size + spare;
  29843. if (res < size) {
  29844. /* XXX: handle corner cases where size is close to size limit (wraparound) */
  29845. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "duk_size_t wrapped");
  29846. }
  29847. DUK_ASSERT(res >= size);
  29848. return res;
  29849. }
  29850. DUK_INTERNAL void duk_hbuffer_resize(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t new_size, duk_size_t new_alloc_size) {
  29851. void *res;
  29852. duk_size_t prev_alloc_size;
  29853. DUK_ASSERT(thr != NULL);
  29854. DUK_ASSERT(buf != NULL);
  29855. DUK_ASSERT(new_alloc_size >= new_size);
  29856. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29857. /*
  29858. * Maximum size check
  29859. */
  29860. if (new_alloc_size > DUK_HBUFFER_MAX_BYTELEN) {
  29861. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, "buffer too long");
  29862. }
  29863. /*
  29864. * Note: use indirect realloc variant just in case mark-and-sweep
  29865. * (finalizers) might resize this same buffer during garbage
  29866. * collection.
  29867. */
  29868. res = DUK_REALLOC_INDIRECT(thr->heap, duk_hbuffer_get_dynalloc_ptr, (void *) buf, new_alloc_size);
  29869. if (res != NULL || new_alloc_size == 0) {
  29870. /* 'res' may be NULL if new allocation size is 0. */
  29871. DUK_DDD(DUK_DDDPRINT("resized dynamic buffer %p:%ld:%ld -> %p:%ld:%ld",
  29872. (void *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, buf),
  29873. (long) DUK_HBUFFER_DYNAMIC_GET_SIZE(buf),
  29874. (long) DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(buf),
  29875. (void *) res,
  29876. (long) new_size,
  29877. (long) new_alloc_size));
  29878. /*
  29879. * The entire allocated buffer area, regardless of actual used
  29880. * size, is kept zeroed in resizes for simplicity. If the buffer
  29881. * is grown, zero the new part. Another policy would be to
  29882. * ensure data is zeroed as the used part is extended. The
  29883. * current approach is much more simple and is not a big deal
  29884. * because the spare part is relatively small.
  29885. */
  29886. prev_alloc_size = DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(buf);
  29887. if (new_alloc_size > prev_alloc_size) {
  29888. DUK_ASSERT(new_alloc_size - prev_alloc_size > 0);
  29889. #ifdef DUK_USE_ZERO_BUFFER_DATA
  29890. DUK_MEMZERO((void *) ((char *) res + prev_alloc_size),
  29891. new_alloc_size - prev_alloc_size);
  29892. #endif
  29893. }
  29894. DUK_HBUFFER_DYNAMIC_SET_SIZE(buf, new_size);
  29895. DUK_HBUFFER_DYNAMIC_SET_ALLOC_SIZE(buf, new_alloc_size);
  29896. DUK_HBUFFER_DYNAMIC_SET_DATA_PTR(thr->heap, buf, res);
  29897. } else {
  29898. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, "buffer resize failed: %ld:%ld to %ld:%ld",
  29899. (long) DUK_HBUFFER_DYNAMIC_GET_SIZE(buf),
  29900. (long) DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(buf),
  29901. (long) new_size,
  29902. (long) new_alloc_size);
  29903. }
  29904. DUK_ASSERT(res != NULL || new_alloc_size == 0);
  29905. }
  29906. DUK_INTERNAL void duk_hbuffer_reset(duk_hthread *thr, duk_hbuffer_dynamic *buf) {
  29907. DUK_ASSERT(thr != NULL);
  29908. DUK_ASSERT(buf != NULL);
  29909. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29910. duk_hbuffer_resize(thr, buf, 0, 0);
  29911. }
  29912. #if 0 /*unused*/
  29913. DUK_INTERNAL void duk_hbuffer_compact(duk_hthread *thr, duk_hbuffer_dynamic *buf) {
  29914. duk_size_t curr_size;
  29915. DUK_ASSERT(thr != NULL);
  29916. DUK_ASSERT(buf != NULL);
  29917. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29918. curr_size = DUK_HBUFFER_GET_SIZE(buf);
  29919. duk_hbuffer_resize(thr, buf, curr_size, curr_size);
  29920. }
  29921. #endif
  29922. /*
  29923. * Inserts
  29924. */
  29925. DUK_INTERNAL void duk_hbuffer_insert_bytes(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, const duk_uint8_t *data, duk_size_t length) {
  29926. duk_uint8_t *p;
  29927. /* XXX: allow inserts with offset > curr_size? i.e., insert zeroes automatically? */
  29928. DUK_ASSERT(thr != NULL);
  29929. DUK_ASSERT(buf != NULL);
  29930. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29931. DUK_ASSERT_DISABLE(offset >= 0); /* unsigned, so always true */
  29932. DUK_ASSERT(offset <= DUK_HBUFFER_GET_SIZE(buf)); /* equality is OK (= append) */
  29933. DUK_ASSERT(data != NULL);
  29934. DUK_ASSERT_DISABLE(length >= 0); /* unsigned, so always true */
  29935. if (length == 0) {
  29936. return;
  29937. }
  29938. if (DUK_HBUFFER_DYNAMIC_GET_SPARE_SIZE(buf) < length) {
  29939. duk_hbuffer_resize(thr,
  29940. buf,
  29941. DUK_HBUFFER_GET_SIZE(buf),
  29942. duk__add_spare(DUK_HBUFFER_GET_SIZE(buf) + length));
  29943. }
  29944. DUK_ASSERT(DUK_HBUFFER_DYNAMIC_GET_SPARE_SIZE(buf) >= length);
  29945. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, buf);
  29946. if (offset < DUK_HBUFFER_GET_SIZE(buf)) {
  29947. /* not an append */
  29948. DUK_ASSERT(DUK_HBUFFER_GET_SIZE(buf) - offset > 0);
  29949. DUK_MEMMOVE((void *) (p + offset + length),
  29950. (void *) (p + offset),
  29951. DUK_HBUFFER_GET_SIZE(buf) - offset);
  29952. }
  29953. DUK_ASSERT(length > 0);
  29954. DUK_MEMCPY((void *) (p + offset),
  29955. data,
  29956. length);
  29957. DUK_HBUFFER_DYNAMIC_ADD_SIZE(buf, length);
  29958. }
  29959. #if 0 /*unused*/
  29960. DUK_INTERNAL void duk_hbuffer_insert_byte(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_uint8_t byte) {
  29961. DUK_ASSERT(thr != NULL);
  29962. DUK_ASSERT(buf != NULL);
  29963. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29964. duk_hbuffer_insert_bytes(thr, buf, offset, &byte, 1);
  29965. }
  29966. #endif
  29967. #if 0 /*unused*/
  29968. DUK_INTERNAL duk_size_t duk_hbuffer_insert_cstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, const char *str) {
  29969. duk_size_t len;
  29970. DUK_ASSERT(thr != NULL);
  29971. DUK_ASSERT(buf != NULL);
  29972. DUK_ASSERT(str != NULL);
  29973. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29974. len = DUK_STRLEN(str);
  29975. duk_hbuffer_insert_bytes(thr, buf, offset, (duk_uint8_t *) str, len);
  29976. return len;
  29977. }
  29978. #endif
  29979. #if 0 /*unused*/
  29980. DUK_INTERNAL duk_size_t duk_hbuffer_insert_hstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_hstring *str) {
  29981. duk_size_t len;
  29982. DUK_ASSERT(thr != NULL);
  29983. DUK_ASSERT(buf != NULL);
  29984. DUK_ASSERT(str != NULL);
  29985. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29986. len = DUK_HSTRING_GET_BYTELEN(str);
  29987. duk_hbuffer_insert_bytes(thr, buf, offset, (duk_uint8_t *) DUK_HSTRING_GET_DATA(str), len);
  29988. return len;
  29989. }
  29990. #endif
  29991. DUK_INTERNAL duk_size_t duk_hbuffer_insert_xutf8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_ucodepoint_t codepoint) {
  29992. duk_uint8_t tmp[DUK_UNICODE_MAX_XUTF8_LENGTH];
  29993. duk_size_t len;
  29994. DUK_ASSERT(thr != NULL);
  29995. DUK_ASSERT(buf != NULL);
  29996. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  29997. /* No range assertion for 'codepoint' */
  29998. /* Intentionally no fast path: insertion is not that central */
  29999. len = (duk_size_t) duk_unicode_encode_xutf8(codepoint, tmp);
  30000. duk_hbuffer_insert_bytes(thr, buf, offset, tmp, len);
  30001. return len;
  30002. }
  30003. /* Append a Unicode codepoint to the buffer in CESU-8 format, i.e., convert
  30004. * non-BMP characters to surrogate pairs which are then "UTF-8" encoded.
  30005. * If the codepoint is initially a surrogate, it is also encoded into CESU-8.
  30006. * Codepoints above valid Unicode range (> U+10FFFF) are mangled.
  30007. */
  30008. #if 0 /*unused*/
  30009. DUK_INTERNAL duk_size_t duk_hbuffer_insert_cesu8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_ucodepoint_t codepoint) {
  30010. duk_uint8_t tmp[DUK_UNICODE_MAX_CESU8_LENGTH];
  30011. duk_size_t len;
  30012. DUK_ASSERT(thr != NULL);
  30013. DUK_ASSERT(buf != NULL);
  30014. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30015. DUK_ASSERT_DISABLE(codepoint >= 0); /* unsigned */
  30016. DUK_ASSERT(codepoint <= 0x10ffff); /* if not in this range, results are garbage (but no crash) */
  30017. /* Intentionally no fast path: insertion is not that central */
  30018. len = (duk_size_t) duk_unicode_encode_cesu8(codepoint, tmp);
  30019. duk_hbuffer_insert_bytes(thr, buf, offset, tmp, len);
  30020. return len;
  30021. }
  30022. #endif
  30023. /*
  30024. * Appends
  30025. *
  30026. * Note: an optimized duk_hbuffer_append_bytes() could be implemented, but
  30027. * it is more compact to use duk_hbuffer_insert_bytes() instead. The
  30028. * important fast paths bypass these functions. anyway.
  30029. */
  30030. DUK_INTERNAL void duk_hbuffer_append_bytes(duk_hthread *thr, duk_hbuffer_dynamic *buf, const duk_uint8_t *data, duk_size_t length) {
  30031. DUK_ASSERT(thr != NULL);
  30032. DUK_ASSERT(buf != NULL);
  30033. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30034. DUK_ASSERT(data != NULL);
  30035. duk_hbuffer_insert_bytes(thr, buf, DUK_HBUFFER_GET_SIZE(buf), data, length);
  30036. }
  30037. DUK_INTERNAL void duk_hbuffer_append_byte(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_uint8_t byte) {
  30038. DUK_ASSERT(thr != NULL);
  30039. DUK_ASSERT(buf != NULL);
  30040. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30041. duk_hbuffer_insert_bytes(thr, buf, DUK_HBUFFER_GET_SIZE(buf), &byte, 1);
  30042. }
  30043. DUK_INTERNAL duk_size_t duk_hbuffer_append_cstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, const char *str) {
  30044. duk_size_t len;
  30045. DUK_ASSERT(thr != NULL);
  30046. DUK_ASSERT(buf != NULL);
  30047. DUK_ASSERT(str != NULL);
  30048. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30049. len = DUK_STRLEN(str);
  30050. duk_hbuffer_insert_bytes(thr, buf, DUK_HBUFFER_GET_SIZE(buf), (duk_uint8_t *) str, len);
  30051. return len;
  30052. }
  30053. DUK_INTERNAL duk_size_t duk_hbuffer_append_hstring(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_hstring *str) {
  30054. duk_size_t len;
  30055. DUK_ASSERT(thr != NULL);
  30056. DUK_ASSERT(buf != NULL);
  30057. DUK_ASSERT(str != NULL);
  30058. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30059. len = DUK_HSTRING_GET_BYTELEN(str);
  30060. duk_hbuffer_insert_bytes(thr, buf, DUK_HBUFFER_GET_SIZE(buf), (duk_uint8_t *) DUK_HSTRING_GET_DATA(str), len);
  30061. return len;
  30062. }
  30063. /* Append a Unicode codepoint to the buffer in extended UTF-8 format, i.e.
  30064. * allow codepoints above standard Unicode range (> U+10FFFF) up to seven
  30065. * byte encoding (36 bits, but argument type is 32 bits). In particular,
  30066. * allows encoding of all unsigned 32-bit integers. If the codepoint is
  30067. * initially a surrogate, it is encoded without checking (and will become,
  30068. * effectively, CESU-8 encoded).
  30069. */
  30070. DUK_INTERNAL duk_size_t duk_hbuffer_append_xutf8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_ucodepoint_t codepoint) {
  30071. duk_uint8_t tmp[DUK_UNICODE_MAX_XUTF8_LENGTH];
  30072. duk_size_t len;
  30073. duk_size_t sz;
  30074. DUK_ASSERT(thr != NULL);
  30075. DUK_ASSERT(buf != NULL);
  30076. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30077. /* No range assertion for 'codepoint' */
  30078. if (DUK_LIKELY(codepoint < 0x80 && DUK_HBUFFER_DYNAMIC_GET_SPARE_SIZE(buf) > 0)) {
  30079. /* fast path: ASCII and there is spare */
  30080. duk_uint8_t *p = ((duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, buf));
  30081. sz = DUK_HBUFFER_DYNAMIC_GET_SIZE(buf);
  30082. p[sz++] = (duk_uint8_t) codepoint;
  30083. DUK_HBUFFER_DYNAMIC_SET_SIZE(buf, sz);
  30084. return 1;
  30085. }
  30086. len = (duk_size_t) duk_unicode_encode_xutf8(codepoint, tmp);
  30087. duk_hbuffer_insert_bytes(thr, buf, DUK_HBUFFER_GET_SIZE(buf), tmp, len);
  30088. return len;
  30089. }
  30090. /* Append a Unicode codepoint to the buffer in CESU-8 format, i.e., convert
  30091. * non-BMP characters to surrogate pairs which are then "UTF-8" encoded.
  30092. * If the codepoint is initially a surrogate, it is also encoded into CESU-8.
  30093. * Codepoints above valid Unicode range (> U+10FFFF) are mangled.
  30094. */
  30095. DUK_INTERNAL duk_size_t duk_hbuffer_append_cesu8(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_ucodepoint_t codepoint) {
  30096. duk_uint8_t tmp[DUK_UNICODE_MAX_CESU8_LENGTH];
  30097. duk_size_t len;
  30098. duk_size_t sz;
  30099. DUK_ASSERT(thr != NULL);
  30100. DUK_ASSERT(buf != NULL);
  30101. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30102. DUK_ASSERT_DISABLE(codepoint >= 0); /* unsigned */
  30103. DUK_ASSERT(codepoint <= 0x10ffff); /* if not in this range, results are garbage (but no crash) */
  30104. if (DUK_LIKELY(codepoint < 0x80 && DUK_HBUFFER_DYNAMIC_GET_SPARE_SIZE(buf) > 0)) {
  30105. /* fast path: ASCII and there is spare */
  30106. duk_uint8_t *p = ((duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, buf));
  30107. sz = DUK_HBUFFER_DYNAMIC_GET_SIZE(buf);
  30108. p[sz++] = (duk_uint8_t) codepoint;
  30109. DUK_HBUFFER_DYNAMIC_SET_SIZE(buf, sz);
  30110. return 1;
  30111. }
  30112. len = (duk_size_t) duk_unicode_encode_cesu8(codepoint, tmp);
  30113. duk_hbuffer_insert_bytes(thr, buf, DUK_HBUFFER_GET_SIZE(buf), tmp, len);
  30114. return len;
  30115. }
  30116. /* Append an duk_uint32_t in native byte order. */
  30117. #if 0 /*unused*/
  30118. DUK_INTERNAL void duk_hbuffer_append_native_u32(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_uint32_t val) {
  30119. /* relies on duk_uint32_t being exactly right size */
  30120. DUK_ASSERT(sizeof(val) == 4);
  30121. duk_hbuffer_insert_bytes(thr,
  30122. buf,
  30123. DUK_HBUFFER_GET_SIZE(buf),
  30124. (duk_uint8_t *) &val,
  30125. sizeof(duk_uint32_t));
  30126. }
  30127. #endif
  30128. /*
  30129. * In-buffer "slices"
  30130. *
  30131. * Slices are identified with an offset+length pair, referring to the current
  30132. * buffer data. A caller cannot otherwise reliably refer to existing data,
  30133. * because the buffer may be reallocated before a data pointer is referenced.
  30134. */
  30135. DUK_INTERNAL void duk_hbuffer_remove_slice(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t offset, duk_size_t length) {
  30136. duk_uint8_t *p;
  30137. duk_size_t end_offset;
  30138. DUK_UNREF(thr);
  30139. DUK_ASSERT(thr != NULL);
  30140. DUK_ASSERT(buf != NULL);
  30141. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30142. DUK_ASSERT_DISABLE(offset >= 0); /* always true */
  30143. DUK_ASSERT(offset <= DUK_HBUFFER_GET_SIZE(buf)); /* allow equality */
  30144. DUK_ASSERT_DISABLE(length >= 0); /* always true */
  30145. DUK_ASSERT(offset + length <= DUK_HBUFFER_GET_SIZE(buf)); /* allow equality */
  30146. if (length == 0) {
  30147. return;
  30148. }
  30149. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, buf);
  30150. end_offset = offset + length;
  30151. if (end_offset < DUK_HBUFFER_GET_SIZE(buf)) {
  30152. /* not strictly from end of buffer; need to shuffle data */
  30153. DUK_ASSERT(DUK_HBUFFER_GET_SIZE(buf) - end_offset > 0);
  30154. DUK_MEMMOVE(p + offset,
  30155. p + end_offset,
  30156. DUK_HBUFFER_GET_SIZE(buf) - end_offset);
  30157. }
  30158. /* Here we want to zero data even with automatic buffer zeroing
  30159. * disabled as we depend on this internally too.
  30160. */
  30161. DUK_ASSERT(length > 0);
  30162. DUK_MEMZERO(p + DUK_HBUFFER_GET_SIZE(buf) - length,
  30163. length);
  30164. DUK_HBUFFER_DYNAMIC_SUB_SIZE(buf, length);
  30165. /* Note: no shrink check, intentional */
  30166. }
  30167. DUK_INTERNAL void duk_hbuffer_insert_slice(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t dst_offset, duk_size_t src_offset, duk_size_t length) {
  30168. duk_uint8_t *p;
  30169. duk_size_t src_end_offset; /* source end (exclusive) in initial buffer */
  30170. duk_size_t len;
  30171. DUK_ASSERT(thr != NULL);
  30172. DUK_ASSERT(buf != NULL);
  30173. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30174. DUK_ASSERT_DISABLE(dst_offset >= 0); /* always true */
  30175. DUK_ASSERT(dst_offset <= DUK_HBUFFER_GET_SIZE(buf)); /* allow equality */
  30176. DUK_ASSERT_DISABLE(src_offset >= 0); /* always true */
  30177. DUK_ASSERT(src_offset <= DUK_HBUFFER_GET_SIZE(buf)); /* allow equality */
  30178. DUK_ASSERT_DISABLE(length >= 0); /* always true */
  30179. DUK_ASSERT(src_offset + length <= DUK_HBUFFER_GET_SIZE(buf)); /* allow equality */
  30180. if (length == 0) {
  30181. return;
  30182. }
  30183. if (DUK_HBUFFER_DYNAMIC_GET_SPARE_SIZE(buf) < length) {
  30184. duk_hbuffer_resize(thr,
  30185. buf,
  30186. DUK_HBUFFER_GET_SIZE(buf),
  30187. duk__add_spare(DUK_HBUFFER_GET_SIZE(buf) + length));
  30188. }
  30189. DUK_ASSERT(DUK_HBUFFER_DYNAMIC_GET_SPARE_SIZE(buf) >= length);
  30190. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, buf);
  30191. DUK_ASSERT(p != NULL); /* must be the case because length > 0, and buffer has been resized if necessary */
  30192. /*
  30193. * src_offset and dst_offset refer to the state of the buffer
  30194. * before any changes are made. This must be taken into account
  30195. * when moving data around; in particular, the source data may
  30196. * "straddle" the dst_offset, so the insert may need to be handled
  30197. * in two pieces.
  30198. */
  30199. src_end_offset = src_offset + length;
  30200. /* create a hole for the insert */
  30201. len = DUK_HBUFFER_GET_SIZE(buf) - dst_offset;
  30202. DUK_MEMMOVE(p + dst_offset + length,
  30203. p + dst_offset,
  30204. len); /* zero size is not an issue: pointers are valid */
  30205. if (src_offset < dst_offset) {
  30206. if (src_end_offset <= dst_offset) {
  30207. /* entire source is before 'dst_offset' */
  30208. DUK_MEMCPY(p + dst_offset,
  30209. p + src_offset,
  30210. length);
  30211. } else {
  30212. /* part of the source is before 'dst_offset'; straddles */
  30213. len = dst_offset - src_offset;
  30214. DUK_ASSERT(len >= 1 && len < length);
  30215. DUK_ASSERT(length - len >= 1);
  30216. DUK_MEMCPY(p + dst_offset,
  30217. p + src_offset,
  30218. len);
  30219. DUK_MEMCPY(p + dst_offset + len,
  30220. p + src_offset + length + len, /* take above memmove() into account */
  30221. length - len);
  30222. }
  30223. } else {
  30224. /* entire source is after 'dst_offset' */
  30225. DUK_MEMCPY(p + dst_offset,
  30226. p + src_offset + length, /* take above memmove() into account */
  30227. length);
  30228. }
  30229. DUK_HBUFFER_DYNAMIC_ADD_SIZE(buf, length);
  30230. }
  30231. DUK_INTERNAL void duk_hbuffer_append_slice(duk_hthread *thr, duk_hbuffer_dynamic *buf, duk_size_t src_offset, duk_size_t length) {
  30232. DUK_ASSERT(thr != NULL);
  30233. DUK_ASSERT(buf != NULL);
  30234. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  30235. DUK_ASSERT_DISABLE(src_offset >= 0); /* always true */
  30236. DUK_ASSERT(src_offset <= DUK_HBUFFER_GET_SIZE(buf)); /* allow equality */
  30237. DUK_ASSERT_DISABLE(length >= 0); /* always true */
  30238. DUK_ASSERT(src_offset + length <= DUK_HBUFFER_GET_SIZE(buf)); /* allow equality */
  30239. duk_hbuffer_insert_slice(thr,
  30240. buf,
  30241. DUK_HBUFFER_GET_SIZE(buf),
  30242. src_offset,
  30243. length);
  30244. }
  30245. #line 1 "duk_heap_alloc.c"
  30246. /*
  30247. * duk_heap allocation and freeing.
  30248. */
  30249. /* include removed: duk_internal.h */
  30250. /* constants for built-in string data depacking */
  30251. #define DUK__BITPACK_LETTER_LIMIT 26
  30252. #define DUK__BITPACK_UNDERSCORE 26
  30253. #define DUK__BITPACK_FF 27
  30254. #define DUK__BITPACK_SWITCH1 29
  30255. #define DUK__BITPACK_SWITCH 30
  30256. #define DUK__BITPACK_SEVENBIT 31
  30257. /*
  30258. * Free a heap object.
  30259. *
  30260. * Free heap object and its internal (non-heap) pointers. Assumes that
  30261. * caller has removed the object from heap allocated list or the string
  30262. * intern table, and any weak references (which strings may have) have
  30263. * been already dealt with.
  30264. */
  30265. DUK_INTERNAL void duk_free_hobject_inner(duk_heap *heap, duk_hobject *h) {
  30266. DUK_ASSERT(heap != NULL);
  30267. DUK_ASSERT(h != NULL);
  30268. DUK_FREE(heap, DUK_HOBJECT_GET_PROPS(heap, h));
  30269. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
  30270. duk_hcompiledfunction *f = (duk_hcompiledfunction *) h;
  30271. DUK_UNREF(f);
  30272. /* Currently nothing to free; 'data' is a heap object */
  30273. } else if (DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  30274. duk_hnativefunction *f = (duk_hnativefunction *) h;
  30275. DUK_UNREF(f);
  30276. /* Currently nothing to free */
  30277. } else if (DUK_HOBJECT_IS_THREAD(h)) {
  30278. duk_hthread *t = (duk_hthread *) h;
  30279. DUK_FREE(heap, t->valstack);
  30280. DUK_FREE(heap, t->callstack);
  30281. DUK_FREE(heap, t->catchstack);
  30282. /* Don't free h->resumer because it exists in the heap.
  30283. * Callstack entries also contain function pointers which
  30284. * are not freed for the same reason.
  30285. */
  30286. /* XXX: with 'caller' property the callstack would need
  30287. * to be unwound to update the 'caller' properties of
  30288. * functions in the callstack.
  30289. */
  30290. }
  30291. }
  30292. DUK_INTERNAL void duk_free_hbuffer_inner(duk_heap *heap, duk_hbuffer *h) {
  30293. DUK_ASSERT(heap != NULL);
  30294. DUK_ASSERT(h != NULL);
  30295. if (DUK_HBUFFER_HAS_DYNAMIC(h)) {
  30296. duk_hbuffer_dynamic *g = (duk_hbuffer_dynamic *) h;
  30297. DUK_DDD(DUK_DDDPRINT("free dynamic buffer %p", (void *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(heap, g)));
  30298. DUK_FREE(heap, DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(heap, g));
  30299. }
  30300. }
  30301. DUK_INTERNAL void duk_free_hstring_inner(duk_heap *heap, duk_hstring *h) {
  30302. DUK_ASSERT(heap != NULL);
  30303. DUK_ASSERT(h != NULL);
  30304. DUK_UNREF(heap);
  30305. DUK_UNREF(h);
  30306. #if defined(DUK_USE_HSTRING_EXTDATA) && defined(DUK_USE_EXTSTR_FREE)
  30307. if (DUK_HSTRING_HAS_EXTDATA(h)) {
  30308. DUK_DDD(DUK_DDDPRINT("free extstr: hstring %!O, extdata: %p",
  30309. h, DUK_HSTRING_GET_EXTDATA((duk_hstring_external *) h)));
  30310. DUK_USE_EXTSTR_FREE(heap->heap_udata, (const void *) DUK_HSTRING_GET_EXTDATA((duk_hstring_external *) h));
  30311. }
  30312. #endif
  30313. }
  30314. DUK_INTERNAL void duk_heap_free_heaphdr_raw(duk_heap *heap, duk_heaphdr *hdr) {
  30315. DUK_ASSERT(heap);
  30316. DUK_ASSERT(hdr);
  30317. DUK_DDD(DUK_DDDPRINT("free heaphdr %p, htype %ld", (void *) hdr, (long) DUK_HEAPHDR_GET_TYPE(hdr)));
  30318. switch ((int) DUK_HEAPHDR_GET_TYPE(hdr)) {
  30319. case DUK_HTYPE_STRING:
  30320. duk_free_hstring_inner(heap, (duk_hstring *) hdr);
  30321. break;
  30322. case DUK_HTYPE_OBJECT:
  30323. duk_free_hobject_inner(heap, (duk_hobject *) hdr);
  30324. break;
  30325. case DUK_HTYPE_BUFFER:
  30326. duk_free_hbuffer_inner(heap, (duk_hbuffer *) hdr);
  30327. break;
  30328. default:
  30329. DUK_UNREACHABLE();
  30330. }
  30331. DUK_FREE(heap, hdr);
  30332. }
  30333. /*
  30334. * Free the heap.
  30335. *
  30336. * Frees heap-related non-heap-tracked allocations such as the
  30337. * string intern table; then frees the heap allocated objects;
  30338. * and finally frees the heap structure itself. Reference counts
  30339. * and GC markers are ignored (and not updated) in this process,
  30340. * and finalizers won't be called.
  30341. *
  30342. * The heap pointer and heap object pointers must not be used
  30343. * after this call.
  30344. */
  30345. DUK_LOCAL void duk__free_allocated(duk_heap *heap) {
  30346. duk_heaphdr *curr;
  30347. duk_heaphdr *next;
  30348. curr = heap->heap_allocated;
  30349. while (curr) {
  30350. /* We don't log or warn about freeing zero refcount objects
  30351. * because they may happen with finalizer processing.
  30352. */
  30353. DUK_DDD(DUK_DDDPRINT("FINALFREE (allocated): %!iO",
  30354. (duk_heaphdr *) curr));
  30355. next = DUK_HEAPHDR_GET_NEXT(heap, curr);
  30356. duk_heap_free_heaphdr_raw(heap, curr);
  30357. curr = next;
  30358. }
  30359. }
  30360. #ifdef DUK_USE_REFERENCE_COUNTING
  30361. DUK_LOCAL void duk__free_refzero_list(duk_heap *heap) {
  30362. duk_heaphdr *curr;
  30363. duk_heaphdr *next;
  30364. curr = heap->refzero_list;
  30365. while (curr) {
  30366. DUK_DDD(DUK_DDDPRINT("FINALFREE (refzero_list): %!iO",
  30367. (duk_heaphdr *) curr));
  30368. next = DUK_HEAPHDR_GET_NEXT(heap, curr);
  30369. duk_heap_free_heaphdr_raw(heap, curr);
  30370. curr = next;
  30371. }
  30372. }
  30373. #endif
  30374. #ifdef DUK_USE_MARK_AND_SWEEP
  30375. DUK_LOCAL void duk__free_markandsweep_finalize_list(duk_heap *heap) {
  30376. duk_heaphdr *curr;
  30377. duk_heaphdr *next;
  30378. curr = heap->finalize_list;
  30379. while (curr) {
  30380. DUK_DDD(DUK_DDDPRINT("FINALFREE (finalize_list): %!iO",
  30381. (duk_heaphdr *) curr));
  30382. next = DUK_HEAPHDR_GET_NEXT(heap, curr);
  30383. duk_heap_free_heaphdr_raw(heap, curr);
  30384. curr = next;
  30385. }
  30386. }
  30387. #endif
  30388. DUK_LOCAL void duk__free_stringtable(duk_heap *heap) {
  30389. /* strings are only tracked by stringtable */
  30390. duk_heap_free_strtab(heap);
  30391. }
  30392. DUK_LOCAL void duk__free_run_finalizers(duk_heap *heap) {
  30393. duk_hthread *thr;
  30394. duk_heaphdr *curr;
  30395. #ifdef DUK_USE_DEBUG
  30396. duk_size_t count_obj = 0;
  30397. #endif
  30398. DUK_ASSERT(heap != NULL);
  30399. DUK_ASSERT(heap->heap_thread != NULL);
  30400. #ifdef DUK_USE_REFERENCE_COUNTING
  30401. DUK_ASSERT(heap->refzero_list == NULL); /* refzero not running -> must be empty */
  30402. #endif
  30403. #ifdef DUK_USE_MARK_AND_SWEEP
  30404. DUK_ASSERT(heap->finalize_list == NULL); /* mark-and-sweep not running -> must be empty */
  30405. #endif
  30406. /* XXX: here again finalizer thread is the heap_thread which needs
  30407. * to be coordinated with finalizer thread fixes.
  30408. */
  30409. thr = heap->heap_thread;
  30410. DUK_ASSERT(thr != NULL);
  30411. curr = heap->heap_allocated;
  30412. while (curr) {
  30413. if (DUK_HEAPHDR_GET_TYPE(curr) == DUK_HTYPE_OBJECT) {
  30414. /* Only objects in heap_allocated may have finalizers. Check that
  30415. * the object itself has a _Finalizer property so that we don't
  30416. * execute finalizers for e.g. Proxy objects.
  30417. */
  30418. DUK_ASSERT(thr != NULL);
  30419. DUK_ASSERT(curr != NULL);
  30420. if (duk_hobject_hasprop_raw(thr, (duk_hobject *) curr, DUK_HTHREAD_STRING_INT_FINALIZER(thr))) {
  30421. duk_hobject_run_finalizer(thr, (duk_hobject *) curr);
  30422. }
  30423. #ifdef DUK_USE_DEBUG
  30424. count_obj++;
  30425. #endif
  30426. }
  30427. curr = DUK_HEAPHDR_GET_NEXT(heap, curr);
  30428. }
  30429. /* Note: count includes all objects, not only those with an actual finalizer. */
  30430. #ifdef DUK_USE_DEBUG
  30431. DUK_D(DUK_DPRINT("checked %ld objects for finalizers before freeing heap", (long) count_obj));
  30432. #endif
  30433. }
  30434. DUK_INTERNAL void duk_heap_free(duk_heap *heap) {
  30435. DUK_D(DUK_DPRINT("free heap: %p", (void *) heap));
  30436. #if defined(DUK_USE_DEBUG)
  30437. duk_heap_dump_strtab(heap);
  30438. #endif
  30439. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  30440. /* Detach a debugger if attached (can be called multiple times)
  30441. * safely.
  30442. */
  30443. duk_debug_do_detach(heap);
  30444. #endif
  30445. /* Execute finalizers before freeing the heap, even for reachable
  30446. * objects, and regardless of whether or not mark-and-sweep is
  30447. * enabled. This gives finalizers the chance to free any native
  30448. * resources like file handles, allocations made outside Duktape,
  30449. * etc.
  30450. *
  30451. * XXX: this perhaps requires an execution time limit.
  30452. */
  30453. DUK_D(DUK_DPRINT("execute finalizers before freeing heap"));
  30454. #ifdef DUK_USE_MARK_AND_SWEEP
  30455. /* run mark-and-sweep a few times just in case (unreachable
  30456. * object finalizers run already here)
  30457. */
  30458. duk_heap_mark_and_sweep(heap, 0);
  30459. duk_heap_mark_and_sweep(heap, 0);
  30460. #endif
  30461. duk__free_run_finalizers(heap);
  30462. /* Note: heap->heap_thread, heap->curr_thread, heap->heap_object,
  30463. * and heap->log_buffer are on the heap allocated list.
  30464. */
  30465. DUK_D(DUK_DPRINT("freeing heap objects of heap: %p", (void *) heap));
  30466. duk__free_allocated(heap);
  30467. #ifdef DUK_USE_REFERENCE_COUNTING
  30468. DUK_D(DUK_DPRINT("freeing refzero list of heap: %p", (void *) heap));
  30469. duk__free_refzero_list(heap);
  30470. #endif
  30471. #ifdef DUK_USE_MARK_AND_SWEEP
  30472. DUK_D(DUK_DPRINT("freeing mark-and-sweep finalize list of heap: %p", (void *) heap));
  30473. duk__free_markandsweep_finalize_list(heap);
  30474. #endif
  30475. DUK_D(DUK_DPRINT("freeing string table of heap: %p", (void *) heap));
  30476. duk__free_stringtable(heap);
  30477. DUK_D(DUK_DPRINT("freeing heap structure: %p", (void *) heap));
  30478. heap->free_func(heap->heap_udata, heap);
  30479. }
  30480. /*
  30481. * Allocate a heap.
  30482. *
  30483. * String table is initialized with built-in strings from genstrings.py.
  30484. */
  30485. /* intern built-in strings from precooked data (genstrings.py) */
  30486. DUK_LOCAL duk_bool_t duk__init_heap_strings(duk_heap *heap) {
  30487. duk_bitdecoder_ctx bd_ctx;
  30488. duk_bitdecoder_ctx *bd = &bd_ctx; /* convenience */
  30489. duk_small_uint_t i, j;
  30490. DUK_MEMZERO(&bd_ctx, sizeof(bd_ctx));
  30491. bd->data = (const duk_uint8_t *) duk_strings_data;
  30492. bd->length = (duk_size_t) DUK_STRDATA_DATA_LENGTH;
  30493. for (i = 0; i < DUK_HEAP_NUM_STRINGS; i++) {
  30494. duk_uint8_t tmp[DUK_STRDATA_MAX_STRLEN];
  30495. duk_hstring *h;
  30496. duk_small_uint_t len;
  30497. duk_small_uint_t mode;
  30498. duk_small_uint_t t;
  30499. len = duk_bd_decode(bd, 5);
  30500. mode = 32; /* 0 = uppercase, 32 = lowercase (= 'a' - 'A') */
  30501. for (j = 0; j < len; j++) {
  30502. t = duk_bd_decode(bd, 5);
  30503. if (t < DUK__BITPACK_LETTER_LIMIT) {
  30504. t = t + DUK_ASC_UC_A + mode;
  30505. } else if (t == DUK__BITPACK_UNDERSCORE) {
  30506. t = DUK_ASC_UNDERSCORE;
  30507. } else if (t == DUK__BITPACK_FF) {
  30508. /* Internal keys are prefixed with 0xFF in the stringtable
  30509. * (which makes them invalid UTF-8 on purpose).
  30510. */
  30511. t = 0xff;
  30512. } else if (t == DUK__BITPACK_SWITCH1) {
  30513. t = duk_bd_decode(bd, 5);
  30514. DUK_ASSERT_DISABLE(t >= 0); /* unsigned */
  30515. DUK_ASSERT(t <= 25);
  30516. t = t + DUK_ASC_UC_A + (mode ^ 32);
  30517. } else if (t == DUK__BITPACK_SWITCH) {
  30518. mode = mode ^ 32;
  30519. t = duk_bd_decode(bd, 5);
  30520. DUK_ASSERT_DISABLE(t >= 0);
  30521. DUK_ASSERT(t <= 25);
  30522. t = t + DUK_ASC_UC_A + mode;
  30523. } else if (t == DUK__BITPACK_SEVENBIT) {
  30524. t = duk_bd_decode(bd, 7);
  30525. }
  30526. tmp[j] = (duk_uint8_t) t;
  30527. }
  30528. /* No need to length check string: it will never exceed even
  30529. * the 16-bit length maximum.
  30530. */
  30531. DUK_ASSERT(len <= 0xffffUL);
  30532. DUK_DDD(DUK_DDDPRINT("intern built-in string %ld", (long) i));
  30533. h = duk_heap_string_intern(heap, tmp, len);
  30534. if (!h) {
  30535. goto error;
  30536. }
  30537. /* Special flags checks. Since these strings are always
  30538. * reachable and a string cannot appear twice in the string
  30539. * table, there's no need to check/set these flags elsewhere.
  30540. * The 'internal' flag is set by string intern code.
  30541. */
  30542. if (i == DUK_STRIDX_EVAL || i == DUK_STRIDX_LC_ARGUMENTS) {
  30543. DUK_HSTRING_SET_EVAL_OR_ARGUMENTS(h);
  30544. }
  30545. if (i >= DUK_STRIDX_START_RESERVED && i < DUK_STRIDX_END_RESERVED) {
  30546. DUK_HSTRING_SET_RESERVED_WORD(h);
  30547. if (i >= DUK_STRIDX_START_STRICT_RESERVED) {
  30548. DUK_HSTRING_SET_STRICT_RESERVED_WORD(h);
  30549. }
  30550. }
  30551. DUK_DDD(DUK_DDDPRINT("interned: %!O", (duk_heaphdr *) h));
  30552. /* XXX: The incref macro takes a thread pointer but doesn't
  30553. * use it right now.
  30554. */
  30555. DUK_HSTRING_INCREF(_never_referenced_, h);
  30556. #if defined(DUK_USE_HEAPPTR16)
  30557. heap->strs16[i] = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) h);
  30558. #else
  30559. heap->strs[i] = h;
  30560. #endif
  30561. }
  30562. return 1;
  30563. error:
  30564. return 0;
  30565. }
  30566. DUK_LOCAL duk_bool_t duk__init_heap_thread(duk_heap *heap) {
  30567. duk_hthread *thr;
  30568. DUK_DD(DUK_DDPRINT("heap init: alloc heap thread"));
  30569. thr = duk_hthread_alloc(heap,
  30570. DUK_HOBJECT_FLAG_EXTENSIBLE |
  30571. DUK_HOBJECT_FLAG_THREAD |
  30572. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_THREAD));
  30573. if (!thr) {
  30574. DUK_D(DUK_DPRINT("failed to alloc heap_thread"));
  30575. return 0;
  30576. }
  30577. thr->state = DUK_HTHREAD_STATE_INACTIVE;
  30578. #if defined(DUK_USE_HEAPPTR16)
  30579. thr->strs16 = heap->strs16;
  30580. #else
  30581. thr->strs = heap->strs;
  30582. #endif
  30583. heap->heap_thread = thr;
  30584. DUK_HTHREAD_INCREF(thr, thr); /* Note: first argument not really used */
  30585. /* 'thr' is now reachable */
  30586. if (!duk_hthread_init_stacks(heap, thr)) {
  30587. return 0;
  30588. }
  30589. /* XXX: this may now fail, and is not handled correctly */
  30590. duk_hthread_create_builtin_objects(thr);
  30591. /* default prototype (Note: 'thr' must be reachable) */
  30592. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, (duk_hobject *) thr, thr->builtins[DUK_BIDX_THREAD_PROTOTYPE]);
  30593. return 1;
  30594. }
  30595. #ifdef DUK_USE_DEBUG
  30596. #define DUK__DUMPSZ(t) do { \
  30597. DUK_D(DUK_DPRINT("" #t "=%ld", (long) sizeof(t))); \
  30598. } while (0)
  30599. /* These is not 100% because format would need to be non-portable "long long".
  30600. * Also print out as doubles to catch cases where the "long" type is not wide
  30601. * enough; the limits will then not be printed accurately but the magnitude
  30602. * will be correct.
  30603. */
  30604. #define DUK__DUMPLM_SIGNED_RAW(t,a,b) do { \
  30605. DUK_D(DUK_DPRINT(t "=[%ld,%ld]=[%lf,%lf]", \
  30606. (long) (a), (long) (b), \
  30607. (double) (a), (double) (b))); \
  30608. } while(0)
  30609. #define DUK__DUMPLM_UNSIGNED_RAW(t,a,b) do { \
  30610. DUK_D(DUK_DPRINT(t "=[%lu,%lu]=[%lf,%lf]", \
  30611. (unsigned long) (a), (unsigned long) (b), \
  30612. (double) (a), (double) (b))); \
  30613. } while(0)
  30614. #define DUK__DUMPLM_SIGNED(t) do { \
  30615. DUK__DUMPLM_SIGNED_RAW("DUK_" #t "_{MIN,MAX}", DUK_##t##_MIN, DUK_##t##_MAX); \
  30616. } while(0)
  30617. #define DUK__DUMPLM_UNSIGNED(t) do { \
  30618. DUK__DUMPLM_UNSIGNED_RAW("DUK_" #t "_{MIN,MAX}", DUK_##t##_MIN, DUK_##t##_MAX); \
  30619. } while(0)
  30620. DUK_LOCAL void duk__dump_type_sizes(void) {
  30621. DUK_D(DUK_DPRINT("sizeof()"));
  30622. /* basic platform types */
  30623. DUK__DUMPSZ(char);
  30624. DUK__DUMPSZ(short);
  30625. DUK__DUMPSZ(int);
  30626. DUK__DUMPSZ(long);
  30627. DUK__DUMPSZ(double);
  30628. DUK__DUMPSZ(void *);
  30629. DUK__DUMPSZ(size_t);
  30630. /* basic types from duk_features.h */
  30631. DUK__DUMPSZ(duk_uint8_t);
  30632. DUK__DUMPSZ(duk_int8_t);
  30633. DUK__DUMPSZ(duk_uint16_t);
  30634. DUK__DUMPSZ(duk_int16_t);
  30635. DUK__DUMPSZ(duk_uint32_t);
  30636. DUK__DUMPSZ(duk_int32_t);
  30637. DUK__DUMPSZ(duk_uint64_t);
  30638. DUK__DUMPSZ(duk_int64_t);
  30639. DUK__DUMPSZ(duk_uint_least8_t);
  30640. DUK__DUMPSZ(duk_int_least8_t);
  30641. DUK__DUMPSZ(duk_uint_least16_t);
  30642. DUK__DUMPSZ(duk_int_least16_t);
  30643. DUK__DUMPSZ(duk_uint_least32_t);
  30644. DUK__DUMPSZ(duk_int_least32_t);
  30645. #if defined(DUK_USE_64BIT_OPS)
  30646. DUK__DUMPSZ(duk_uint_least64_t);
  30647. DUK__DUMPSZ(duk_int_least64_t);
  30648. #endif
  30649. DUK__DUMPSZ(duk_uint_fast8_t);
  30650. DUK__DUMPSZ(duk_int_fast8_t);
  30651. DUK__DUMPSZ(duk_uint_fast16_t);
  30652. DUK__DUMPSZ(duk_int_fast16_t);
  30653. DUK__DUMPSZ(duk_uint_fast32_t);
  30654. DUK__DUMPSZ(duk_int_fast32_t);
  30655. #if defined(DUK_USE_64BIT_OPS)
  30656. DUK__DUMPSZ(duk_uint_fast64_t);
  30657. DUK__DUMPSZ(duk_int_fast64_t);
  30658. #endif
  30659. DUK__DUMPSZ(duk_uintptr_t);
  30660. DUK__DUMPSZ(duk_intptr_t);
  30661. DUK__DUMPSZ(duk_uintmax_t);
  30662. DUK__DUMPSZ(duk_intmax_t);
  30663. DUK__DUMPSZ(duk_double_t);
  30664. /* important chosen base types */
  30665. DUK__DUMPSZ(duk_int_t);
  30666. DUK__DUMPSZ(duk_uint_t);
  30667. DUK__DUMPSZ(duk_int_fast_t);
  30668. DUK__DUMPSZ(duk_uint_fast_t);
  30669. DUK__DUMPSZ(duk_small_int_t);
  30670. DUK__DUMPSZ(duk_small_uint_t);
  30671. DUK__DUMPSZ(duk_small_int_fast_t);
  30672. DUK__DUMPSZ(duk_small_uint_fast_t);
  30673. /* some derived types */
  30674. DUK__DUMPSZ(duk_codepoint_t);
  30675. DUK__DUMPSZ(duk_ucodepoint_t);
  30676. DUK__DUMPSZ(duk_idx_t);
  30677. DUK__DUMPSZ(duk_errcode_t);
  30678. DUK__DUMPSZ(duk_uarridx_t);
  30679. /* tval */
  30680. DUK__DUMPSZ(duk_double_union);
  30681. DUK__DUMPSZ(duk_tval);
  30682. /* structs from duk_forwdecl.h */
  30683. DUK__DUMPSZ(duk_jmpbuf);
  30684. DUK__DUMPSZ(duk_heaphdr);
  30685. DUK__DUMPSZ(duk_heaphdr_string);
  30686. DUK__DUMPSZ(duk_hstring);
  30687. DUK__DUMPSZ(duk_hstring_external);
  30688. DUK__DUMPSZ(duk_hobject);
  30689. DUK__DUMPSZ(duk_hcompiledfunction);
  30690. DUK__DUMPSZ(duk_hnativefunction);
  30691. DUK__DUMPSZ(duk_hthread);
  30692. DUK__DUMPSZ(duk_hbuffer);
  30693. DUK__DUMPSZ(duk_hbuffer_fixed);
  30694. DUK__DUMPSZ(duk_hbuffer_dynamic);
  30695. DUK__DUMPSZ(duk_propaccessor);
  30696. DUK__DUMPSZ(duk_propvalue);
  30697. DUK__DUMPSZ(duk_propdesc);
  30698. DUK__DUMPSZ(duk_heap);
  30699. #if defined(DUK_USE_STRTAB_CHAIN)
  30700. DUK__DUMPSZ(duk_strtab_entry);
  30701. #endif
  30702. DUK__DUMPSZ(duk_activation);
  30703. DUK__DUMPSZ(duk_catcher);
  30704. DUK__DUMPSZ(duk_strcache);
  30705. DUK__DUMPSZ(duk_ljstate);
  30706. DUK__DUMPSZ(duk_fixedbuffer);
  30707. DUK__DUMPSZ(duk_bitdecoder_ctx);
  30708. DUK__DUMPSZ(duk_bitencoder_ctx);
  30709. DUK__DUMPSZ(duk_token);
  30710. DUK__DUMPSZ(duk_re_token);
  30711. DUK__DUMPSZ(duk_lexer_point);
  30712. DUK__DUMPSZ(duk_lexer_ctx);
  30713. DUK__DUMPSZ(duk_compiler_instr);
  30714. DUK__DUMPSZ(duk_compiler_func);
  30715. DUK__DUMPSZ(duk_compiler_ctx);
  30716. DUK__DUMPSZ(duk_re_matcher_ctx);
  30717. DUK__DUMPSZ(duk_re_compiler_ctx);
  30718. }
  30719. DUK_LOCAL void duk__dump_type_limits(void) {
  30720. DUK_D(DUK_DPRINT("limits"));
  30721. /* basic types */
  30722. DUK__DUMPLM_SIGNED(INT8);
  30723. DUK__DUMPLM_UNSIGNED(UINT8);
  30724. DUK__DUMPLM_SIGNED(INT_FAST8);
  30725. DUK__DUMPLM_UNSIGNED(UINT_FAST8);
  30726. DUK__DUMPLM_SIGNED(INT_LEAST8);
  30727. DUK__DUMPLM_UNSIGNED(UINT_LEAST8);
  30728. DUK__DUMPLM_SIGNED(INT16);
  30729. DUK__DUMPLM_UNSIGNED(UINT16);
  30730. DUK__DUMPLM_SIGNED(INT_FAST16);
  30731. DUK__DUMPLM_UNSIGNED(UINT_FAST16);
  30732. DUK__DUMPLM_SIGNED(INT_LEAST16);
  30733. DUK__DUMPLM_UNSIGNED(UINT_LEAST16);
  30734. DUK__DUMPLM_SIGNED(INT32);
  30735. DUK__DUMPLM_UNSIGNED(UINT32);
  30736. DUK__DUMPLM_SIGNED(INT_FAST32);
  30737. DUK__DUMPLM_UNSIGNED(UINT_FAST32);
  30738. DUK__DUMPLM_SIGNED(INT_LEAST32);
  30739. DUK__DUMPLM_UNSIGNED(UINT_LEAST32);
  30740. #if defined(DUK_USE_64BIT_OPS)
  30741. DUK__DUMPLM_SIGNED(INT64);
  30742. DUK__DUMPLM_UNSIGNED(UINT64);
  30743. DUK__DUMPLM_SIGNED(INT_FAST64);
  30744. DUK__DUMPLM_UNSIGNED(UINT_FAST64);
  30745. DUK__DUMPLM_SIGNED(INT_LEAST64);
  30746. DUK__DUMPLM_UNSIGNED(UINT_LEAST64);
  30747. #endif
  30748. DUK__DUMPLM_SIGNED(INTPTR);
  30749. DUK__DUMPLM_UNSIGNED(UINTPTR);
  30750. DUK__DUMPLM_SIGNED(INTMAX);
  30751. DUK__DUMPLM_UNSIGNED(UINTMAX);
  30752. /* derived types */
  30753. DUK__DUMPLM_SIGNED(INT);
  30754. DUK__DUMPLM_UNSIGNED(UINT);
  30755. DUK__DUMPLM_SIGNED(INT_FAST);
  30756. DUK__DUMPLM_UNSIGNED(UINT_FAST);
  30757. DUK__DUMPLM_SIGNED(SMALL_INT);
  30758. DUK__DUMPLM_UNSIGNED(SMALL_UINT);
  30759. DUK__DUMPLM_SIGNED(SMALL_INT_FAST);
  30760. DUK__DUMPLM_UNSIGNED(SMALL_UINT_FAST);
  30761. }
  30762. #undef DUK__DUMPSZ
  30763. #undef DUK__DUMPLM_SIGNED_RAW
  30764. #undef DUK__DUMPLM_UNSIGNED_RAW
  30765. #undef DUK__DUMPLM_SIGNED
  30766. #undef DUK__DUMPLM_UNSIGNED
  30767. DUK_LOCAL void duk__dump_misc_options(void) {
  30768. DUK_D(DUK_DPRINT("DUK_VERSION: %ld", (long) DUK_VERSION));
  30769. DUK_D(DUK_DPRINT("DUK_GIT_DESCRIBE: %s", DUK_GIT_DESCRIBE));
  30770. #if defined(DUK_USE_PACKED_TVAL)
  30771. DUK_D(DUK_DPRINT("DUK_USE_PACKED_TVAL: yes"));
  30772. #else
  30773. DUK_D(DUK_DPRINT("DUK_USE_PACKED_TVAL: no"));
  30774. #endif
  30775. #if defined(DUK_USE_INTEGER_LE)
  30776. DUK_D(DUK_DPRINT("Integer endianness: little"));
  30777. #elif defined(DUK_USE_INTEGER_ME)
  30778. DUK_D(DUK_DPRINT("Integer endianness: mixed"));
  30779. #elif defined(DUK_USE_INTEGER_BE)
  30780. DUK_D(DUK_DPRINT("Integer endianness: big"));
  30781. #else
  30782. DUK_D(DUK_DPRINT("Integer endianness: ???"));
  30783. #endif
  30784. #if defined(DUK_USE_DOUBLE_LE)
  30785. DUK_D(DUK_DPRINT("IEEE double endianness: little"));
  30786. #elif defined(DUK_USE_DOUBLE_ME)
  30787. DUK_D(DUK_DPRINT("IEEE double endianness: mixed"));
  30788. #elif defined(DUK_USE_DOUBLE_BE)
  30789. DUK_D(DUK_DPRINT("IEEE double endianness: big"));
  30790. #else
  30791. DUK_D(DUK_DPRINT("IEEE double endianness: ???"));
  30792. #endif
  30793. }
  30794. #endif /* DUK_USE_DEBUG */
  30795. DUK_INTERNAL
  30796. duk_heap *duk_heap_alloc(duk_alloc_function alloc_func,
  30797. duk_realloc_function realloc_func,
  30798. duk_free_function free_func,
  30799. void *heap_udata,
  30800. duk_fatal_function fatal_func) {
  30801. duk_heap *res = NULL;
  30802. DUK_D(DUK_DPRINT("allocate heap"));
  30803. /*
  30804. * Debug dump type sizes
  30805. */
  30806. #ifdef DUK_USE_DEBUG
  30807. duk__dump_misc_options();
  30808. duk__dump_type_sizes();
  30809. duk__dump_type_limits();
  30810. #endif
  30811. /*
  30812. * If selftests enabled, run them as early as possible
  30813. */
  30814. #ifdef DUK_USE_SELF_TESTS
  30815. DUK_D(DUK_DPRINT("running self tests"));
  30816. duk_selftest_run_tests();
  30817. DUK_D(DUK_DPRINT("self tests passed"));
  30818. #endif
  30819. #ifdef DUK_USE_COMPUTED_NAN
  30820. do {
  30821. /* Workaround for some exotic platforms where NAN is missing
  30822. * and the expression (0.0 / 0.0) does NOT result in a NaN.
  30823. * Such platforms use the global 'duk_computed_nan' which must
  30824. * be initialized at runtime. Use 'volatile' to ensure that
  30825. * the compiler will actually do the computation and not try
  30826. * to do constant folding which might result in the original
  30827. * problem.
  30828. */
  30829. volatile double dbl1 = 0.0;
  30830. volatile double dbl2 = 0.0;
  30831. duk_computed_nan = dbl1 / dbl2;
  30832. } while (0);
  30833. #endif
  30834. /*
  30835. * Computed values (e.g. INFINITY)
  30836. */
  30837. #ifdef DUK_USE_COMPUTED_INFINITY
  30838. do {
  30839. /* Similar workaround for INFINITY. */
  30840. volatile double dbl1 = 1.0;
  30841. volatile double dbl2 = 0.0;
  30842. duk_computed_infinity = dbl1 / dbl2;
  30843. } while (0);
  30844. #endif
  30845. /*
  30846. * Allocate heap struct
  30847. *
  30848. * Use a raw call, all macros expect the heap to be initialized
  30849. */
  30850. res = (duk_heap *) alloc_func(heap_udata, sizeof(duk_heap));
  30851. if (!res) {
  30852. goto error;
  30853. }
  30854. /*
  30855. * Zero the struct, and start initializing roughly in order
  30856. */
  30857. DUK_MEMZERO(res, sizeof(*res));
  30858. /* explicit NULL inits */
  30859. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  30860. res->heap_udata = NULL;
  30861. res->heap_allocated = NULL;
  30862. #ifdef DUK_USE_REFERENCE_COUNTING
  30863. res->refzero_list = NULL;
  30864. res->refzero_list_tail = NULL;
  30865. #endif
  30866. #ifdef DUK_USE_MARK_AND_SWEEP
  30867. res->finalize_list = NULL;
  30868. #endif
  30869. res->heap_thread = NULL;
  30870. res->curr_thread = NULL;
  30871. res->heap_object = NULL;
  30872. res->log_buffer = NULL;
  30873. #if defined(DUK_USE_STRTAB_CHAIN)
  30874. /* nothing to NULL */
  30875. #elif defined(DUK_USE_STRTAB_PROBE)
  30876. #if defined(DUK_USE_HEAPPTR16)
  30877. res->strtable16 = (duk_uint16_t *) NULL;
  30878. #else
  30879. res->strtable = (duk_hstring **) NULL;
  30880. #endif
  30881. #endif
  30882. {
  30883. duk_small_uint_t i;
  30884. for (i = 0; i < DUK_HEAP_NUM_STRINGS; i++) {
  30885. res->strs[i] = NULL;
  30886. }
  30887. }
  30888. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  30889. res->dbg_read_cb = NULL;
  30890. res->dbg_write_cb = NULL;
  30891. res->dbg_peek_cb = NULL;
  30892. res->dbg_read_flush_cb = NULL;
  30893. res->dbg_write_flush_cb = NULL;
  30894. res->dbg_udata = NULL;
  30895. res->dbg_step_thread = NULL;
  30896. #endif
  30897. #endif /* DUK_USE_EXPLICIT_NULL_INIT */
  30898. res->alloc_func = alloc_func;
  30899. res->realloc_func = realloc_func;
  30900. res->free_func = free_func;
  30901. res->heap_udata = heap_udata;
  30902. res->fatal_func = fatal_func;
  30903. #if defined(DUK_USE_HEAPPTR16)
  30904. /* XXX: zero assumption */
  30905. res->heapptr_null16 = DUK_USE_HEAPPTR_ENC16(res->heap_udata, (void *) NULL);
  30906. res->heapptr_deleted16 = DUK_USE_HEAPPTR_ENC16(res->heap_udata, (void *) DUK_STRTAB_DELETED_MARKER(res));
  30907. #endif
  30908. /* res->mark_and_sweep_trigger_counter == 0 -> now causes immediate GC; which is OK */
  30909. res->call_recursion_depth = 0;
  30910. res->call_recursion_limit = DUK_HEAP_DEFAULT_CALL_RECURSION_LIMIT;
  30911. /* XXX: use the pointer as a seed for now: mix in time at least */
  30912. /* The casts through duk_intr_pt is to avoid the following GCC warning:
  30913. *
  30914. * warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
  30915. *
  30916. * This still generates a /Wp64 warning on VS2010 when compiling for x86.
  30917. */
  30918. res->hash_seed = (duk_uint32_t) (duk_intptr_t) res;
  30919. res->rnd_state = (duk_uint32_t) (duk_intptr_t) res;
  30920. #ifdef DUK_USE_INTERRUPT_COUNTER
  30921. /* zero value causes an interrupt before executing first instruction */
  30922. DUK_ASSERT(res->interrupt_counter == 0);
  30923. DUK_ASSERT(res->interrupt_init == 0);
  30924. #endif
  30925. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  30926. res->lj.jmpbuf_ptr = NULL;
  30927. #endif
  30928. DUK_ASSERT(res->lj.type == DUK_LJ_TYPE_UNKNOWN); /* zero */
  30929. DUK_TVAL_SET_UNDEFINED_UNUSED(&res->lj.value1);
  30930. DUK_TVAL_SET_UNDEFINED_UNUSED(&res->lj.value2);
  30931. #if (DUK_STRTAB_INITIAL_SIZE < DUK_UTIL_MIN_HASH_PRIME)
  30932. #error initial heap stringtable size is defined incorrectly
  30933. #endif
  30934. /*
  30935. * Init stringtable: fixed variant
  30936. */
  30937. #if defined(DUK_USE_STRTAB_CHAIN)
  30938. DUK_MEMZERO(res->strtable, sizeof(duk_strtab_entry) * DUK_STRTAB_CHAIN_SIZE);
  30939. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  30940. {
  30941. duk_small_uint_t i;
  30942. for (i = 0; i < DUK_STRTAB_CHAIN_SIZE; i++) {
  30943. #if defined(DUK_USE_HEAPPTR16)
  30944. res->strtable[i].u.str16 = res->heapptr_null16;
  30945. #else
  30946. res->strtable[i].u.str = NULL;
  30947. #endif
  30948. }
  30949. }
  30950. #endif /* DUK_USE_EXPLICIT_NULL_INIT */
  30951. #endif /* DUK_USE_STRTAB_CHAIN */
  30952. /*
  30953. * Init stringtable: probe variant
  30954. */
  30955. #if defined(DUK_USE_STRTAB_PROBE)
  30956. #if defined(DUK_USE_HEAPPTR16)
  30957. res->strtable16 = (duk_uint16_t *) alloc_func(heap_udata, sizeof(duk_uint16_t) * DUK_STRTAB_INITIAL_SIZE);
  30958. if (!res->strtable16) {
  30959. goto error;
  30960. }
  30961. #else /* DUK_USE_HEAPPTR16 */
  30962. res->strtable = (duk_hstring **) alloc_func(heap_udata, sizeof(duk_hstring *) * DUK_STRTAB_INITIAL_SIZE);
  30963. if (!res->strtable) {
  30964. goto error;
  30965. }
  30966. #endif /* DUK_USE_HEAPPTR16 */
  30967. res->st_size = DUK_STRTAB_INITIAL_SIZE;
  30968. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  30969. {
  30970. duk_small_uint_t i;
  30971. DUK_ASSERT(res->st_size == DUK_STRTAB_INITIAL_SIZE);
  30972. for (i = 0; i < DUK_STRTAB_INITIAL_SIZE; i++) {
  30973. #if defined(DUK_USE_HEAPPTR16)
  30974. res->strtable16[i] = res->heapptr_null16;
  30975. #else
  30976. res->strtable[i] = NULL;
  30977. #endif
  30978. }
  30979. }
  30980. #else /* DUK_USE_EXPLICIT_NULL_INIT */
  30981. #if defined(DUK_USE_HEAPPTR16)
  30982. DUK_MEMZERO(res->strtable16, sizeof(duk_uint16_t) * DUK_STRTAB_INITIAL_SIZE);
  30983. #else
  30984. DUK_MEMZERO(res->strtable, sizeof(duk_hstring *) * DUK_STRTAB_INITIAL_SIZE);
  30985. #endif
  30986. #endif /* DUK_USE_EXPLICIT_NULL_INIT */
  30987. #endif /* DUK_USE_STRTAB_PROBE */
  30988. /*
  30989. * Init stringcache
  30990. */
  30991. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  30992. {
  30993. duk_small_uint_t i;
  30994. for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
  30995. res->strcache[i].h = NULL;
  30996. }
  30997. }
  30998. #endif
  30999. /* XXX: error handling is incomplete. It would be cleanest if
  31000. * there was a setjmp catchpoint, so that all init code could
  31001. * freely throw errors. If that were the case, the return code
  31002. * passing here could be removed.
  31003. */
  31004. /*
  31005. * Init built-in strings
  31006. */
  31007. DUK_DD(DUK_DDPRINT("HEAP: INIT STRINGS"));
  31008. if (!duk__init_heap_strings(res)) {
  31009. goto error;
  31010. }
  31011. /*
  31012. * Init the heap thread
  31013. */
  31014. DUK_DD(DUK_DDPRINT("HEAP: INIT HEAP THREAD"));
  31015. if (!duk__init_heap_thread(res)) {
  31016. goto error;
  31017. }
  31018. /*
  31019. * Init the heap object
  31020. */
  31021. DUK_DD(DUK_DDPRINT("HEAP: INIT HEAP OBJECT"));
  31022. DUK_ASSERT(res->heap_thread != NULL);
  31023. res->heap_object = duk_hobject_alloc(res, DUK_HOBJECT_FLAG_EXTENSIBLE |
  31024. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT));
  31025. if (!res->heap_object) {
  31026. goto error;
  31027. }
  31028. DUK_HOBJECT_INCREF(res->heap_thread, res->heap_object);
  31029. /*
  31030. * Init log buffer
  31031. */
  31032. DUK_DD(DUK_DDPRINT("HEAP: INIT LOG BUFFER"));
  31033. res->log_buffer = (duk_hbuffer_dynamic *) duk_hbuffer_alloc(res,
  31034. DUK_BI_LOGGER_SHORT_MSG_LIMIT,
  31035. DUK_BUF_FLAG_DYNAMIC /*flags*/);
  31036. if (!res->log_buffer) {
  31037. goto error;
  31038. }
  31039. DUK_HBUFFER_INCREF(res->heap_thread, res->log_buffer);
  31040. /*
  31041. * All done
  31042. */
  31043. DUK_D(DUK_DPRINT("allocated heap: %p", (void *) res));
  31044. return res;
  31045. error:
  31046. DUK_D(DUK_DPRINT("heap allocation failed"));
  31047. if (res) {
  31048. /* assumes that allocated pointers and alloc funcs are valid
  31049. * if res exists
  31050. */
  31051. DUK_ASSERT(res->alloc_func != NULL);
  31052. DUK_ASSERT(res->realloc_func != NULL);
  31053. DUK_ASSERT(res->free_func != NULL);
  31054. duk_heap_free(res);
  31055. }
  31056. return NULL;
  31057. }
  31058. #line 1 "duk_heap_hashstring.c"
  31059. /*
  31060. * String hash computation (interning).
  31061. */
  31062. /* include removed: duk_internal.h */
  31063. /* constants for duk_hashstring() */
  31064. #define DUK__STRHASH_SHORTSTRING 4096L
  31065. #define DUK__STRHASH_MEDIUMSTRING (256L * 1024L)
  31066. #define DUK__STRHASH_BLOCKSIZE 256L
  31067. DUK_INTERNAL duk_uint32_t duk_heap_hashstring(duk_heap *heap, const duk_uint8_t *str, duk_size_t len) {
  31068. duk_uint32_t hash;
  31069. /*
  31070. * Sampling long strings by byte skipping (like Lua does) is potentially
  31071. * a cache problem. Here we do 'block skipping' instead for long strings:
  31072. * hash an initial part, and then sample the rest of the string with
  31073. * reasonably sized chunks.
  31074. *
  31075. * Skip should depend on length and bound the total time to roughly
  31076. * logarithmic.
  31077. *
  31078. * With current values:
  31079. *
  31080. * 1M string => 256 * 241 = 61696 bytes (0.06M) of hashing
  31081. * 1G string => 256 * 16321 = 4178176 bytes (3.98M) of hashing
  31082. *
  31083. * After an initial part has been hashed, an offset is applied before
  31084. * starting the sampling. The initial offset is computed from the
  31085. * hash of the initial part of the string. The idea is to avoid the
  31086. * case that all long strings have certain offset ranges that are never
  31087. * sampled.
  31088. */
  31089. /* note: mixing len into seed improves hashing when skipping */
  31090. duk_uint32_t str_seed = heap->hash_seed ^ ((duk_uint32_t) len);
  31091. if (len <= DUK__STRHASH_SHORTSTRING) {
  31092. hash = duk_util_hashbytes(str, len, str_seed);
  31093. } else {
  31094. duk_size_t off;
  31095. duk_size_t skip;
  31096. if (len <= DUK__STRHASH_MEDIUMSTRING) {
  31097. skip = (duk_size_t) (16 * DUK__STRHASH_BLOCKSIZE + DUK__STRHASH_BLOCKSIZE);
  31098. } else {
  31099. skip = (duk_size_t) (256 * DUK__STRHASH_BLOCKSIZE + DUK__STRHASH_BLOCKSIZE);
  31100. }
  31101. hash = duk_util_hashbytes(str, (duk_size_t) DUK__STRHASH_SHORTSTRING, str_seed);
  31102. off = DUK__STRHASH_SHORTSTRING + (skip * (hash % 256)) / 256;
  31103. /* XXX: inefficient loop */
  31104. while (off < len) {
  31105. duk_size_t left = len - off;
  31106. duk_size_t now = (duk_size_t) (left > DUK__STRHASH_BLOCKSIZE ? DUK__STRHASH_BLOCKSIZE : left);
  31107. hash ^= duk_util_hashbytes(str + off, now, str_seed);
  31108. off += skip;
  31109. }
  31110. }
  31111. #if defined(DUK_USE_STRHASH16)
  31112. /* Truncate to 16 bits here, so that a computed hash can be compared
  31113. * against a hash stored in a 16-bit field.
  31114. */
  31115. hash &= 0x0000ffffUL;
  31116. #endif
  31117. return hash;
  31118. }
  31119. #line 1 "duk_heap_markandsweep.c"
  31120. /*
  31121. * Mark-and-sweep garbage collection.
  31122. */
  31123. /* include removed: duk_internal.h */
  31124. #ifdef DUK_USE_MARK_AND_SWEEP
  31125. DUK_LOCAL_DECL void duk__mark_heaphdr(duk_heap *heap, duk_heaphdr *h);
  31126. DUK_LOCAL_DECL void duk__mark_tval(duk_heap *heap, duk_tval *tv);
  31127. /*
  31128. * Misc
  31129. */
  31130. /* Select a thread for mark-and-sweep use.
  31131. *
  31132. * XXX: This needs to change later.
  31133. */
  31134. DUK_LOCAL duk_hthread *duk__get_temp_hthread(duk_heap *heap) {
  31135. if (heap->curr_thread) {
  31136. return heap->curr_thread;
  31137. }
  31138. return heap->heap_thread; /* may be NULL, too */
  31139. }
  31140. /*
  31141. * Marking functions for heap types: mark children recursively
  31142. */
  31143. DUK_LOCAL void duk__mark_hstring(duk_heap *heap, duk_hstring *h) {
  31144. DUK_UNREF(heap);
  31145. DUK_UNREF(h);
  31146. DUK_DDD(DUK_DDDPRINT("duk__mark_hstring: %p", (void *) h));
  31147. DUK_ASSERT(h);
  31148. /* nothing to process */
  31149. }
  31150. DUK_LOCAL void duk__mark_hobject(duk_heap *heap, duk_hobject *h) {
  31151. duk_uint_fast32_t i;
  31152. DUK_DDD(DUK_DDDPRINT("duk__mark_hobject: %p", (void *) h));
  31153. DUK_ASSERT(h);
  31154. /* XXX: use advancing pointers instead of index macros -> faster and smaller? */
  31155. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(h); i++) {
  31156. duk_hstring *key = DUK_HOBJECT_E_GET_KEY(heap, h, i);
  31157. if (!key) {
  31158. continue;
  31159. }
  31160. duk__mark_heaphdr(heap, (duk_heaphdr *) key);
  31161. if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(heap, h, i)) {
  31162. duk__mark_heaphdr(heap, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->a.get);
  31163. duk__mark_heaphdr(heap, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->a.set);
  31164. } else {
  31165. duk__mark_tval(heap, &DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->v);
  31166. }
  31167. }
  31168. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ASIZE(h); i++) {
  31169. duk__mark_tval(heap, DUK_HOBJECT_A_GET_VALUE_PTR(heap, h, i));
  31170. }
  31171. /* hash part is a 'weak reference' and does not contribute */
  31172. duk__mark_heaphdr(heap, (duk_heaphdr *) DUK_HOBJECT_GET_PROTOTYPE(heap, h));
  31173. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
  31174. duk_hcompiledfunction *f = (duk_hcompiledfunction *) h;
  31175. duk_tval *tv, *tv_end;
  31176. duk_hobject **funcs, **funcs_end;
  31177. /* 'data' is reachable through every compiled function which
  31178. * contains a reference.
  31179. */
  31180. duk__mark_heaphdr(heap, (duk_heaphdr *) DUK_HCOMPILEDFUNCTION_GET_DATA(heap, f));
  31181. tv = DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(heap, f);
  31182. tv_end = DUK_HCOMPILEDFUNCTION_GET_CONSTS_END(heap, f);
  31183. while (tv < tv_end) {
  31184. duk__mark_tval(heap, tv);
  31185. tv++;
  31186. }
  31187. funcs = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(heap, f);
  31188. funcs_end = DUK_HCOMPILEDFUNCTION_GET_FUNCS_END(heap, f);
  31189. while (funcs < funcs_end) {
  31190. duk__mark_heaphdr(heap, (duk_heaphdr *) *funcs);
  31191. funcs++;
  31192. }
  31193. } else if (DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  31194. duk_hnativefunction *f = (duk_hnativefunction *) h;
  31195. DUK_UNREF(f);
  31196. /* nothing to mark */
  31197. } else if (DUK_HOBJECT_IS_THREAD(h)) {
  31198. duk_hthread *t = (duk_hthread *) h;
  31199. duk_tval *tv;
  31200. tv = t->valstack;
  31201. while (tv < t->valstack_end) {
  31202. duk__mark_tval(heap, tv);
  31203. tv++;
  31204. }
  31205. for (i = 0; i < (duk_uint_fast32_t) t->callstack_top; i++) {
  31206. duk_activation *act = t->callstack + i;
  31207. duk__mark_heaphdr(heap, (duk_heaphdr *) DUK_ACT_GET_FUNC(act));
  31208. duk__mark_heaphdr(heap, (duk_heaphdr *) act->var_env);
  31209. duk__mark_heaphdr(heap, (duk_heaphdr *) act->lex_env);
  31210. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  31211. duk__mark_heaphdr(heap, (duk_heaphdr *) act->prev_caller);
  31212. #endif
  31213. }
  31214. #if 0 /* nothing now */
  31215. for (i = 0; i < (duk_uint_fast32_t) t->catchstack_top; i++) {
  31216. duk_catcher *cat = t->catchstack + i;
  31217. }
  31218. #endif
  31219. duk__mark_heaphdr(heap, (duk_heaphdr *) t->resumer);
  31220. /* XXX: duk_small_uint_t would be enough for this loop */
  31221. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  31222. duk__mark_heaphdr(heap, (duk_heaphdr *) t->builtins[i]);
  31223. }
  31224. }
  31225. }
  31226. /* recursion tracking happens here only */
  31227. DUK_LOCAL void duk__mark_heaphdr(duk_heap *heap, duk_heaphdr *h) {
  31228. DUK_DDD(DUK_DDDPRINT("duk__mark_heaphdr %p, type %ld",
  31229. (void *) h,
  31230. (h != NULL ? (long) DUK_HEAPHDR_GET_TYPE(h) : (long) -1)));
  31231. if (!h) {
  31232. return;
  31233. }
  31234. if (DUK_HEAPHDR_HAS_REACHABLE(h)) {
  31235. DUK_DDD(DUK_DDDPRINT("already marked reachable, skip"));
  31236. return;
  31237. }
  31238. DUK_HEAPHDR_SET_REACHABLE(h);
  31239. if (heap->mark_and_sweep_recursion_depth >= DUK_HEAP_MARK_AND_SWEEP_RECURSION_LIMIT) {
  31240. /* log this with a normal debug level because this should be relatively rare */
  31241. DUK_D(DUK_DPRINT("mark-and-sweep recursion limit reached, marking as temproot: %p", (void *) h));
  31242. DUK_HEAP_SET_MARKANDSWEEP_RECLIMIT_REACHED(heap);
  31243. DUK_HEAPHDR_SET_TEMPROOT(h);
  31244. return;
  31245. }
  31246. heap->mark_and_sweep_recursion_depth++;
  31247. switch ((int) DUK_HEAPHDR_GET_TYPE(h)) {
  31248. case DUK_HTYPE_STRING:
  31249. duk__mark_hstring(heap, (duk_hstring *) h);
  31250. break;
  31251. case DUK_HTYPE_OBJECT:
  31252. duk__mark_hobject(heap, (duk_hobject *) h);
  31253. break;
  31254. case DUK_HTYPE_BUFFER:
  31255. /* nothing to mark */
  31256. break;
  31257. default:
  31258. DUK_D(DUK_DPRINT("attempt to mark heaphdr %p with invalid htype %ld", (void *) h, (long) DUK_HEAPHDR_GET_TYPE(h)));
  31259. DUK_UNREACHABLE();
  31260. }
  31261. heap->mark_and_sweep_recursion_depth--;
  31262. }
  31263. DUK_LOCAL void duk__mark_tval(duk_heap *heap, duk_tval *tv) {
  31264. DUK_DDD(DUK_DDDPRINT("duk__mark_tval %p", (void *) tv));
  31265. if (!tv) {
  31266. return;
  31267. }
  31268. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  31269. duk__mark_heaphdr(heap, DUK_TVAL_GET_HEAPHDR(tv));
  31270. }
  31271. }
  31272. /*
  31273. * Mark the heap.
  31274. */
  31275. DUK_LOCAL void duk__mark_roots_heap(duk_heap *heap) {
  31276. duk_small_uint_t i;
  31277. DUK_DD(DUK_DDPRINT("duk__mark_roots_heap: %p", (void *) heap));
  31278. duk__mark_heaphdr(heap, (duk_heaphdr *) heap->heap_thread);
  31279. duk__mark_heaphdr(heap, (duk_heaphdr *) heap->heap_object);
  31280. duk__mark_heaphdr(heap, (duk_heaphdr *) heap->log_buffer);
  31281. for (i = 0; i < DUK_HEAP_NUM_STRINGS; i++) {
  31282. duk_hstring *h = DUK_HEAP_GET_STRING(heap, i);
  31283. duk__mark_heaphdr(heap, (duk_heaphdr *) h);
  31284. }
  31285. duk__mark_tval(heap, &heap->lj.value1);
  31286. duk__mark_tval(heap, &heap->lj.value2);
  31287. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  31288. for (i = 0; i < heap->dbg_breakpoint_count; i++) {
  31289. duk__mark_heaphdr(heap, (duk_heaphdr *) heap->dbg_breakpoints[i].filename);
  31290. }
  31291. #endif
  31292. }
  31293. /*
  31294. * Mark refzero_list objects.
  31295. *
  31296. * Objects on the refzero_list have no inbound references. They might have
  31297. * outbound references to objects that we might free, which would invalidate
  31298. * any references held by the refzero objects. A refzero object might also
  31299. * be rescued by refcount finalization. Refzero objects are treated as
  31300. * reachability roots to ensure they (or anything they point to) are not
  31301. * freed in mark-and-sweep.
  31302. */
  31303. #ifdef DUK_USE_REFERENCE_COUNTING
  31304. DUK_LOCAL void duk__mark_refzero_list(duk_heap *heap) {
  31305. duk_heaphdr *hdr;
  31306. DUK_DD(DUK_DDPRINT("duk__mark_refzero_list: %p", (void *) heap));
  31307. hdr = heap->refzero_list;
  31308. while (hdr) {
  31309. duk__mark_heaphdr(heap, hdr);
  31310. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31311. }
  31312. }
  31313. #endif
  31314. /*
  31315. * Mark unreachable, finalizable objects.
  31316. *
  31317. * Such objects will be moved aside and their finalizers run later. They have
  31318. * to be treated as reachability roots for their properties etc to remain
  31319. * allocated. This marking is only done for unreachable values which would
  31320. * be swept later (refzero_list is thus excluded).
  31321. *
  31322. * Objects are first marked FINALIZABLE and only then marked as reachability
  31323. * roots; otherwise circular references might be handled inconsistently.
  31324. */
  31325. DUK_LOCAL void duk__mark_finalizable(duk_heap *heap) {
  31326. duk_hthread *thr;
  31327. duk_heaphdr *hdr;
  31328. duk_size_t count_finalizable = 0;
  31329. DUK_DD(DUK_DDPRINT("duk__mark_finalizable: %p", (void *) heap));
  31330. thr = duk__get_temp_hthread(heap);
  31331. DUK_ASSERT(thr != NULL);
  31332. hdr = heap->heap_allocated;
  31333. while (hdr) {
  31334. /* A finalizer is looked up from the object and up its prototype chain
  31335. * (which allows inherited finalizers). A prototype loop must not cause
  31336. * an error to be thrown here; duk_hobject_hasprop_raw() will ignore a
  31337. * prototype loop silently and indicate that the property doesn't exist.
  31338. */
  31339. if (!DUK_HEAPHDR_HAS_REACHABLE(hdr) &&
  31340. DUK_HEAPHDR_GET_TYPE(hdr) == DUK_HTYPE_OBJECT &&
  31341. !DUK_HEAPHDR_HAS_FINALIZED(hdr) &&
  31342. duk_hobject_hasprop_raw(thr, (duk_hobject *) hdr, DUK_HTHREAD_STRING_INT_FINALIZER(thr))) {
  31343. /* heaphdr:
  31344. * - is not reachable
  31345. * - is an object
  31346. * - is not a finalized object
  31347. * - has a finalizer
  31348. */
  31349. DUK_DD(DUK_DDPRINT("unreachable heap object will be "
  31350. "finalized -> mark as finalizable "
  31351. "and treat as a reachability root: %p",
  31352. (void *) hdr));
  31353. DUK_HEAPHDR_SET_FINALIZABLE(hdr);
  31354. count_finalizable ++;
  31355. }
  31356. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31357. }
  31358. if (count_finalizable == 0) {
  31359. return;
  31360. }
  31361. DUK_DD(DUK_DDPRINT("marked %ld heap objects as finalizable, now mark them reachable",
  31362. (long) count_finalizable));
  31363. hdr = heap->heap_allocated;
  31364. while (hdr) {
  31365. if (DUK_HEAPHDR_HAS_FINALIZABLE(hdr)) {
  31366. duk__mark_heaphdr(heap, hdr);
  31367. }
  31368. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31369. }
  31370. /* Caller will finish the marking process if we hit a recursion limit. */
  31371. }
  31372. /*
  31373. * Mark objects on finalize_list.
  31374. *
  31375. */
  31376. DUK_LOCAL void duk__mark_finalize_list(duk_heap *heap) {
  31377. duk_heaphdr *hdr;
  31378. #ifdef DUK_USE_DEBUG
  31379. duk_size_t count_finalize_list = 0;
  31380. #endif
  31381. DUK_DD(DUK_DDPRINT("duk__mark_finalize_list: %p", (void *) heap));
  31382. hdr = heap->finalize_list;
  31383. while (hdr) {
  31384. duk__mark_heaphdr(heap, hdr);
  31385. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31386. #ifdef DUK_USE_DEBUG
  31387. count_finalize_list++;
  31388. #endif
  31389. }
  31390. #ifdef DUK_USE_DEBUG
  31391. if (count_finalize_list > 0) {
  31392. DUK_D(DUK_DPRINT("marked %ld objects on the finalize_list as reachable (previous finalizer run skipped)",
  31393. (long) count_finalize_list));
  31394. }
  31395. #endif
  31396. }
  31397. /*
  31398. * Fallback marking handler if recursion limit is reached.
  31399. *
  31400. * Iterates 'temproots' until recursion limit is no longer hit. Note
  31401. * that temproots may reside either in heap allocated list or the
  31402. * refzero work list. This is a slow scan, but guarantees that we
  31403. * finish with a bounded C stack.
  31404. *
  31405. * Note that nodes may have been marked as temproots before this
  31406. * scan begun, OR they may have been marked during the scan (as
  31407. * we process nodes recursively also during the scan). This is
  31408. * intended behavior.
  31409. */
  31410. #ifdef DUK_USE_DEBUG
  31411. DUK_LOCAL void duk__handle_temproot(duk_heap *heap, duk_heaphdr *hdr, duk_size_t *count) {
  31412. #else
  31413. DUK_LOCAL void duk__handle_temproot(duk_heap *heap, duk_heaphdr *hdr) {
  31414. #endif
  31415. if (!DUK_HEAPHDR_HAS_TEMPROOT(hdr)) {
  31416. DUK_DDD(DUK_DDDPRINT("not a temp root: %p", (void *) hdr));
  31417. return;
  31418. }
  31419. DUK_DDD(DUK_DDDPRINT("found a temp root: %p", (void *) hdr));
  31420. DUK_HEAPHDR_CLEAR_TEMPROOT(hdr);
  31421. DUK_HEAPHDR_CLEAR_REACHABLE(hdr); /* done so that duk__mark_heaphdr() works correctly */
  31422. duk__mark_heaphdr(heap, hdr);
  31423. #ifdef DUK_USE_DEBUG
  31424. (*count)++;
  31425. #endif
  31426. }
  31427. DUK_LOCAL void duk__mark_temproots_by_heap_scan(duk_heap *heap) {
  31428. duk_heaphdr *hdr;
  31429. #ifdef DUK_USE_DEBUG
  31430. duk_size_t count;
  31431. #endif
  31432. DUK_DD(DUK_DDPRINT("duk__mark_temproots_by_heap_scan: %p", (void *) heap));
  31433. while (DUK_HEAP_HAS_MARKANDSWEEP_RECLIMIT_REACHED(heap)) {
  31434. DUK_DD(DUK_DDPRINT("recursion limit reached, doing heap scan to continue from temproots"));
  31435. #ifdef DUK_USE_DEBUG
  31436. count = 0;
  31437. #endif
  31438. DUK_HEAP_CLEAR_MARKANDSWEEP_RECLIMIT_REACHED(heap);
  31439. hdr = heap->heap_allocated;
  31440. while (hdr) {
  31441. #ifdef DUK_USE_DEBUG
  31442. duk__handle_temproot(heap, hdr, &count);
  31443. #else
  31444. duk__handle_temproot(heap, hdr);
  31445. #endif
  31446. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31447. }
  31448. /* must also check refzero_list */
  31449. #ifdef DUK_USE_REFERENCE_COUNTING
  31450. hdr = heap->refzero_list;
  31451. while (hdr) {
  31452. #ifdef DUK_USE_DEBUG
  31453. duk__handle_temproot(heap, hdr, &count);
  31454. #else
  31455. duk__handle_temproot(heap, hdr);
  31456. #endif
  31457. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31458. }
  31459. #endif /* DUK_USE_REFERENCE_COUNTING */
  31460. #ifdef DUK_USE_DEBUG
  31461. DUK_DD(DUK_DDPRINT("temproot mark heap scan processed %ld temp roots", (long) count));
  31462. #endif
  31463. }
  31464. }
  31465. /*
  31466. * Finalize refcounts for heap elements just about to be freed.
  31467. * This must be done for all objects before freeing to avoid any
  31468. * stale pointer dereferences.
  31469. *
  31470. * Note that this must deduce the set of objects to be freed
  31471. * identically to duk__sweep_heap().
  31472. */
  31473. #ifdef DUK_USE_REFERENCE_COUNTING
  31474. DUK_LOCAL void duk__finalize_refcounts(duk_heap *heap) {
  31475. duk_hthread *thr;
  31476. duk_heaphdr *hdr;
  31477. thr = duk__get_temp_hthread(heap);
  31478. DUK_ASSERT(thr != NULL);
  31479. DUK_DD(DUK_DDPRINT("duk__finalize_refcounts: heap=%p, hthread=%p",
  31480. (void *) heap, (void *) thr));
  31481. hdr = heap->heap_allocated;
  31482. while (hdr) {
  31483. if (!DUK_HEAPHDR_HAS_REACHABLE(hdr)) {
  31484. /*
  31485. * Unreachable object about to be swept. Finalize target refcounts
  31486. * (objects which the unreachable object points to) without doing
  31487. * refzero processing. Recursive decrefs are also prevented when
  31488. * refzero processing is disabled.
  31489. *
  31490. * Value cannot be a finalizable object, as they have been made
  31491. * temporarily reachable for this round.
  31492. */
  31493. DUK_DDD(DUK_DDDPRINT("unreachable object, refcount finalize before sweeping: %p", (void *) hdr));
  31494. duk_heaphdr_refcount_finalize(thr, hdr);
  31495. }
  31496. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31497. }
  31498. }
  31499. #endif /* DUK_USE_REFERENCE_COUNTING */
  31500. /*
  31501. * Clear (reachable) flags of refzero work list.
  31502. */
  31503. #ifdef DUK_USE_REFERENCE_COUNTING
  31504. DUK_LOCAL void duk__clear_refzero_list_flags(duk_heap *heap) {
  31505. duk_heaphdr *hdr;
  31506. DUK_DD(DUK_DDPRINT("duk__clear_refzero_list_flags: %p", (void *) heap));
  31507. hdr = heap->refzero_list;
  31508. while (hdr) {
  31509. DUK_HEAPHDR_CLEAR_REACHABLE(hdr);
  31510. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(hdr));
  31511. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZED(hdr));
  31512. DUK_ASSERT(!DUK_HEAPHDR_HAS_TEMPROOT(hdr));
  31513. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31514. }
  31515. }
  31516. #endif /* DUK_USE_REFERENCE_COUNTING */
  31517. /*
  31518. * Clear (reachable) flags of finalize_list
  31519. *
  31520. * We could mostly do in the sweep phase when we move objects from the
  31521. * heap into the finalize_list. However, if a finalizer run is skipped
  31522. * during a mark-and-sweep, the objects on the finalize_list will be marked
  31523. * reachable during the next mark-and-sweep. Since they're already on the
  31524. * finalize_list, no-one will be clearing their REACHABLE flag so we do it
  31525. * here. (This now overlaps with the sweep handling in a harmless way.)
  31526. */
  31527. DUK_LOCAL void duk__clear_finalize_list_flags(duk_heap *heap) {
  31528. duk_heaphdr *hdr;
  31529. DUK_DD(DUK_DDPRINT("duk__clear_finalize_list_flags: %p", (void *) heap));
  31530. hdr = heap->finalize_list;
  31531. while (hdr) {
  31532. DUK_HEAPHDR_CLEAR_REACHABLE(hdr);
  31533. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(hdr));
  31534. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZED(hdr));
  31535. DUK_ASSERT(!DUK_HEAPHDR_HAS_TEMPROOT(hdr));
  31536. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31537. }
  31538. }
  31539. /*
  31540. * Sweep stringtable
  31541. */
  31542. #if defined(DUK_USE_STRTAB_CHAIN)
  31543. /* XXX: skip count_free w/o debug? */
  31544. #if defined(DUK_USE_HEAPPTR16)
  31545. DUK_LOCAL void duk__sweep_string_chain16(duk_heap *heap, duk_uint16_t *slot, duk_size_t *count_keep, duk_size_t *count_free) {
  31546. duk_uint16_t h16 = *slot;
  31547. duk_hstring *h;
  31548. duk_uint16_t null16 = heap->heapptr_null16;
  31549. if (h16 == null16) {
  31550. /* nop */
  31551. return;
  31552. }
  31553. h = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, h16);
  31554. DUK_ASSERT(h != NULL);
  31555. if (DUK_HEAPHDR_HAS_REACHABLE((duk_heaphdr *) h)) {
  31556. DUK_HEAPHDR_CLEAR_REACHABLE((duk_heaphdr *) h);
  31557. (*count_keep)++;
  31558. } else {
  31559. #if defined(DUK_USE_REFERENCE_COUNTING)
  31560. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT((duk_heaphdr *) h) == 0);
  31561. #endif
  31562. /* deal with weak references first */
  31563. duk_heap_strcache_string_remove(heap, (duk_hstring *) h);
  31564. *slot = null16;
  31565. /* free inner references (these exist e.g. when external
  31566. * strings are enabled)
  31567. */
  31568. duk_free_hstring_inner(heap, h);
  31569. DUK_FREE(heap, h);
  31570. (*count_free)++;
  31571. }
  31572. }
  31573. #else /* DUK_USE_HEAPPTR16 */
  31574. DUK_LOCAL void duk__sweep_string_chain(duk_heap *heap, duk_hstring **slot, duk_size_t *count_keep, duk_size_t *count_free) {
  31575. duk_hstring *h = *slot;
  31576. if (h == NULL) {
  31577. /* nop */
  31578. return;
  31579. }
  31580. if (DUK_HEAPHDR_HAS_REACHABLE((duk_heaphdr *) h)) {
  31581. DUK_HEAPHDR_CLEAR_REACHABLE((duk_heaphdr *) h);
  31582. (*count_keep)++;
  31583. } else {
  31584. #if defined(DUK_USE_REFERENCE_COUNTING)
  31585. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT((duk_heaphdr *) h) == 0);
  31586. #endif
  31587. /* deal with weak references first */
  31588. duk_heap_strcache_string_remove(heap, (duk_hstring *) h);
  31589. *slot = NULL;
  31590. /* free inner references (these exist e.g. when external
  31591. * strings are enabled)
  31592. */
  31593. duk_free_hstring_inner(heap, h);
  31594. DUK_FREE(heap, h);
  31595. (*count_free)++;
  31596. }
  31597. }
  31598. #endif /* DUK_USE_HEAPPTR16 */
  31599. DUK_LOCAL void duk__sweep_stringtable_chain(duk_heap *heap, duk_size_t *out_count_keep) {
  31600. duk_strtab_entry *e;
  31601. duk_uint_fast32_t i;
  31602. duk_size_t count_free = 0;
  31603. duk_size_t count_keep = 0;
  31604. duk_size_t j, n;
  31605. #if defined(DUK_USE_HEAPPTR16)
  31606. duk_uint16_t *lst;
  31607. #else
  31608. duk_hstring **lst;
  31609. #endif
  31610. DUK_DD(DUK_DDPRINT("duk__sweep_stringtable: %p", (void *) heap));
  31611. /* Non-zero refcounts should not happen for unreachable strings,
  31612. * because we refcount finalize all unreachable objects which
  31613. * should have decreased unreachable string refcounts to zero
  31614. * (even for cycles).
  31615. */
  31616. for (i = 0; i < DUK_STRTAB_CHAIN_SIZE; i++) {
  31617. e = heap->strtable + i;
  31618. if (e->listlen == 0) {
  31619. #if defined(DUK_USE_HEAPPTR16)
  31620. duk__sweep_string_chain16(heap, &e->u.str16, &count_keep, &count_free);
  31621. #else
  31622. duk__sweep_string_chain(heap, &e->u.str, &count_keep, &count_free);
  31623. #endif
  31624. } else {
  31625. #if defined(DUK_USE_HEAPPTR16)
  31626. lst = (duk_uint16_t *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.strlist16);
  31627. #else
  31628. lst = e->u.strlist;
  31629. #endif
  31630. for (j = 0, n = e->listlen; j < n; j++) {
  31631. #if defined(DUK_USE_HEAPPTR16)
  31632. duk__sweep_string_chain16(heap, lst + j, &count_keep, &count_free);
  31633. #else
  31634. duk__sweep_string_chain(heap, lst + j, &count_keep, &count_free);
  31635. #endif
  31636. }
  31637. }
  31638. }
  31639. DUK_D(DUK_DPRINT("mark-and-sweep sweep stringtable: %ld freed, %ld kept",
  31640. (long) count_free, (long) count_keep));
  31641. *out_count_keep = count_keep;
  31642. }
  31643. #endif /* DUK_USE_STRTAB_CHAIN */
  31644. #if defined(DUK_USE_STRTAB_PROBE)
  31645. DUK_LOCAL void duk__sweep_stringtable_probe(duk_heap *heap, duk_size_t *out_count_keep) {
  31646. duk_hstring *h;
  31647. duk_uint_fast32_t i;
  31648. #ifdef DUK_USE_DEBUG
  31649. duk_size_t count_free = 0;
  31650. #endif
  31651. duk_size_t count_keep = 0;
  31652. DUK_DD(DUK_DDPRINT("duk__sweep_stringtable: %p", (void *) heap));
  31653. for (i = 0; i < heap->st_size; i++) {
  31654. #if defined(DUK_USE_HEAPPTR16)
  31655. h = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->strtable16[i]);
  31656. #else
  31657. h = heap->strtable[i];
  31658. #endif
  31659. if (h == NULL || h == DUK_STRTAB_DELETED_MARKER(heap)) {
  31660. continue;
  31661. } else if (DUK_HEAPHDR_HAS_REACHABLE((duk_heaphdr *) h)) {
  31662. DUK_HEAPHDR_CLEAR_REACHABLE((duk_heaphdr *) h);
  31663. count_keep++;
  31664. continue;
  31665. }
  31666. #ifdef DUK_USE_DEBUG
  31667. count_free++;
  31668. #endif
  31669. #if defined(DUK_USE_REFERENCE_COUNTING)
  31670. /* Non-zero refcounts should not happen for unreachable strings,
  31671. * because we refcount finalize all unreachable objects which
  31672. * should have decreased unreachable string refcounts to zero
  31673. * (even for cycles).
  31674. */
  31675. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT((duk_heaphdr *) h) == 0);
  31676. #endif
  31677. DUK_DDD(DUK_DDDPRINT("sweep string, not reachable: %p", (void *) h));
  31678. /* deal with weak references first */
  31679. duk_heap_strcache_string_remove(heap, (duk_hstring *) h);
  31680. /* remove the string (mark DELETED), could also call
  31681. * duk_heap_string_remove() but that would be slow and
  31682. * pointless because we already know the slot.
  31683. */
  31684. #if defined(DUK_USE_HEAPPTR16)
  31685. heap->strtable16[i] = heap->heapptr_deleted16;
  31686. #else
  31687. heap->strtable[i] = DUK_STRTAB_DELETED_MARKER(heap);
  31688. #endif
  31689. /* free inner references (these exist e.g. when external
  31690. * strings are enabled)
  31691. */
  31692. duk_free_hstring_inner(heap, (duk_hstring *) h);
  31693. /* finally free the struct itself */
  31694. DUK_FREE(heap, h);
  31695. }
  31696. #ifdef DUK_USE_DEBUG
  31697. DUK_D(DUK_DPRINT("mark-and-sweep sweep stringtable: %ld freed, %ld kept",
  31698. (long) count_free, (long) count_keep));
  31699. #endif
  31700. *out_count_keep = count_keep;
  31701. }
  31702. #endif /* DUK_USE_STRTAB_PROBE */
  31703. /*
  31704. * Sweep heap
  31705. */
  31706. DUK_LOCAL void duk__sweep_heap(duk_heap *heap, duk_int_t flags, duk_size_t *out_count_keep) {
  31707. duk_heaphdr *prev; /* last element that was left in the heap */
  31708. duk_heaphdr *curr;
  31709. duk_heaphdr *next;
  31710. #ifdef DUK_USE_DEBUG
  31711. duk_size_t count_free = 0;
  31712. duk_size_t count_finalize = 0;
  31713. duk_size_t count_rescue = 0;
  31714. #endif
  31715. duk_size_t count_keep = 0;
  31716. DUK_UNREF(flags);
  31717. DUK_DD(DUK_DDPRINT("duk__sweep_heap: %p", (void *) heap));
  31718. prev = NULL;
  31719. curr = heap->heap_allocated;
  31720. heap->heap_allocated = NULL;
  31721. while (curr) {
  31722. /* strings are never placed on the heap allocated list */
  31723. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(curr) != DUK_HTYPE_STRING);
  31724. next = DUK_HEAPHDR_GET_NEXT(heap, curr);
  31725. if (DUK_HEAPHDR_HAS_REACHABLE(curr)) {
  31726. /*
  31727. * Reachable object, keep
  31728. */
  31729. DUK_DDD(DUK_DDDPRINT("sweep, reachable: %p", (void *) curr));
  31730. if (DUK_HEAPHDR_HAS_FINALIZABLE(curr)) {
  31731. /*
  31732. * If object has been marked finalizable, move it to the
  31733. * "to be finalized" work list. It will be collected on
  31734. * the next mark-and-sweep if it is still unreachable
  31735. * after running the finalizer.
  31736. */
  31737. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZED(curr));
  31738. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(curr) == DUK_HTYPE_OBJECT);
  31739. DUK_DDD(DUK_DDDPRINT("object has finalizer, move to finalization work list: %p", (void *) curr));
  31740. #ifdef DUK_USE_DOUBLE_LINKED_HEAP
  31741. if (heap->finalize_list) {
  31742. DUK_HEAPHDR_SET_PREV(heap, heap->finalize_list, curr);
  31743. }
  31744. DUK_HEAPHDR_SET_PREV(heap, curr, NULL);
  31745. #endif
  31746. DUK_HEAPHDR_SET_NEXT(heap, curr, heap->finalize_list);
  31747. heap->finalize_list = curr;
  31748. #ifdef DUK_USE_DEBUG
  31749. count_finalize++;
  31750. #endif
  31751. } else {
  31752. /*
  31753. * Object will be kept; queue object back to heap_allocated (to tail)
  31754. */
  31755. if (DUK_HEAPHDR_HAS_FINALIZED(curr)) {
  31756. /*
  31757. * Object's finalizer was executed on last round, and
  31758. * object has been happily rescued.
  31759. */
  31760. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(curr));
  31761. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(curr) == DUK_HTYPE_OBJECT);
  31762. DUK_DD(DUK_DDPRINT("object rescued during mark-and-sweep finalization: %p", (void *) curr));
  31763. #ifdef DUK_USE_DEBUG
  31764. count_rescue++;
  31765. #endif
  31766. } else {
  31767. /*
  31768. * Plain, boring reachable object.
  31769. */
  31770. count_keep++;
  31771. }
  31772. if (!heap->heap_allocated) {
  31773. heap->heap_allocated = curr;
  31774. }
  31775. if (prev) {
  31776. DUK_HEAPHDR_SET_NEXT(heap, prev, curr);
  31777. }
  31778. #ifdef DUK_USE_DOUBLE_LINKED_HEAP
  31779. DUK_HEAPHDR_SET_PREV(heap, curr, prev);
  31780. #endif
  31781. prev = curr;
  31782. }
  31783. DUK_HEAPHDR_CLEAR_REACHABLE(curr);
  31784. DUK_HEAPHDR_CLEAR_FINALIZED(curr);
  31785. DUK_HEAPHDR_CLEAR_FINALIZABLE(curr);
  31786. DUK_ASSERT(!DUK_HEAPHDR_HAS_REACHABLE(curr));
  31787. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZED(curr));
  31788. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(curr));
  31789. curr = next;
  31790. } else {
  31791. /*
  31792. * Unreachable object, free
  31793. */
  31794. DUK_DDD(DUK_DDDPRINT("sweep, not reachable: %p", (void *) curr));
  31795. #if defined(DUK_USE_REFERENCE_COUNTING)
  31796. /* Non-zero refcounts should not happen because we refcount
  31797. * finalize all unreachable objects which should cancel out
  31798. * refcounts (even for cycles).
  31799. */
  31800. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(curr) == 0);
  31801. #endif
  31802. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(curr));
  31803. if (DUK_HEAPHDR_HAS_FINALIZED(curr)) {
  31804. DUK_DDD(DUK_DDDPRINT("finalized object not rescued: %p", (void *) curr));
  31805. }
  31806. /* Note: object cannot be a finalizable unreachable object, as
  31807. * they have been marked temporarily reachable for this round,
  31808. * and are handled above.
  31809. */
  31810. #ifdef DUK_USE_DEBUG
  31811. count_free++;
  31812. #endif
  31813. /* weak refs should be handled here, but no weak refs for
  31814. * any non-string objects exist right now.
  31815. */
  31816. /* free object and all auxiliary (non-heap) allocs */
  31817. duk_heap_free_heaphdr_raw(heap, curr);
  31818. curr = next;
  31819. }
  31820. }
  31821. if (prev) {
  31822. DUK_HEAPHDR_SET_NEXT(heap, prev, NULL);
  31823. }
  31824. #ifdef DUK_USE_DEBUG
  31825. DUK_D(DUK_DPRINT("mark-and-sweep sweep objects (non-string): %ld freed, %ld kept, %ld rescued, %ld queued for finalization",
  31826. (long) count_free, (long) count_keep, (long) count_rescue, (long) count_finalize));
  31827. #endif
  31828. *out_count_keep = count_keep;
  31829. }
  31830. /*
  31831. * Run (object) finalizers in the "to be finalized" work list.
  31832. */
  31833. DUK_LOCAL void duk__run_object_finalizers(duk_heap *heap) {
  31834. duk_heaphdr *curr;
  31835. duk_heaphdr *next;
  31836. #ifdef DUK_USE_DEBUG
  31837. duk_size_t count = 0;
  31838. #endif
  31839. duk_hthread *thr;
  31840. DUK_DD(DUK_DDPRINT("duk__run_object_finalizers: %p", (void *) heap));
  31841. thr = duk__get_temp_hthread(heap);
  31842. DUK_ASSERT(thr != NULL);
  31843. curr = heap->finalize_list;
  31844. while (curr) {
  31845. DUK_DDD(DUK_DDDPRINT("mark-and-sweep finalize: %p", (void *) curr));
  31846. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(curr) == DUK_HTYPE_OBJECT); /* only objects have finalizers */
  31847. DUK_ASSERT(!DUK_HEAPHDR_HAS_REACHABLE(curr)); /* flags have been already cleared */
  31848. DUK_ASSERT(!DUK_HEAPHDR_HAS_TEMPROOT(curr));
  31849. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(curr));
  31850. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZED(curr));
  31851. /* run the finalizer */
  31852. duk_hobject_run_finalizer(thr, (duk_hobject *) curr); /* must never longjmp */
  31853. /* mark FINALIZED, for next mark-and-sweep (will collect unless has become reachable;
  31854. * prevent running finalizer again if reachable)
  31855. */
  31856. DUK_HEAPHDR_SET_FINALIZED(curr);
  31857. /* queue back to heap_allocated */
  31858. next = DUK_HEAPHDR_GET_NEXT(heap, curr);
  31859. DUK_HEAP_INSERT_INTO_HEAP_ALLOCATED(heap, curr);
  31860. curr = next;
  31861. #ifdef DUK_USE_DEBUG
  31862. count++;
  31863. #endif
  31864. }
  31865. /* finalize_list will always be processed completely */
  31866. heap->finalize_list = NULL;
  31867. #ifdef DUK_USE_DEBUG
  31868. DUK_D(DUK_DPRINT("mark-and-sweep finalize objects: %ld finalizers called", (long) count));
  31869. #endif
  31870. }
  31871. /*
  31872. * Object compaction.
  31873. *
  31874. * Compaction is assumed to never throw an error.
  31875. */
  31876. DUK_LOCAL int duk__protected_compact_object(duk_context *ctx) {
  31877. /* XXX: for threads, compact value stack, call stack, catch stack? */
  31878. duk_hobject *obj = duk_get_hobject(ctx, -1);
  31879. DUK_ASSERT(obj != NULL);
  31880. duk_hobject_compact_props((duk_hthread *) ctx, obj);
  31881. return 0;
  31882. }
  31883. #ifdef DUK_USE_DEBUG
  31884. DUK_LOCAL void duk__compact_object_list(duk_heap *heap, duk_hthread *thr, duk_heaphdr *start, duk_size_t *p_count_check, duk_size_t *p_count_compact, duk_size_t *p_count_bytes_saved) {
  31885. #else
  31886. DUK_LOCAL void duk__compact_object_list(duk_heap *heap, duk_hthread *thr, duk_heaphdr *start) {
  31887. #endif
  31888. duk_heaphdr *curr;
  31889. #ifdef DUK_USE_DEBUG
  31890. duk_size_t old_size, new_size;
  31891. #endif
  31892. duk_hobject *obj;
  31893. DUK_UNREF(heap);
  31894. curr = start;
  31895. while (curr) {
  31896. DUK_DDD(DUK_DDDPRINT("mark-and-sweep compact: %p", (void *) curr));
  31897. if (DUK_HEAPHDR_GET_TYPE(curr) != DUK_HTYPE_OBJECT) {
  31898. goto next;
  31899. }
  31900. obj = (duk_hobject *) curr;
  31901. #ifdef DUK_USE_DEBUG
  31902. old_size = DUK_HOBJECT_P_COMPUTE_SIZE(DUK_HOBJECT_GET_ESIZE(obj),
  31903. DUK_HOBJECT_GET_ASIZE(obj),
  31904. DUK_HOBJECT_GET_HSIZE(obj));
  31905. #endif
  31906. DUK_DD(DUK_DDPRINT("compact object: %p", (void *) obj));
  31907. duk_push_hobject((duk_context *) thr, obj);
  31908. /* XXX: disable error handlers for duration of compaction? */
  31909. duk_safe_call((duk_context *) thr, duk__protected_compact_object, 1, 0);
  31910. #ifdef DUK_USE_DEBUG
  31911. new_size = DUK_HOBJECT_P_COMPUTE_SIZE(DUK_HOBJECT_GET_ESIZE(obj),
  31912. DUK_HOBJECT_GET_ASIZE(obj),
  31913. DUK_HOBJECT_GET_HSIZE(obj));
  31914. #endif
  31915. #ifdef DUK_USE_DEBUG
  31916. (*p_count_compact)++;
  31917. (*p_count_bytes_saved) += (duk_size_t) (old_size - new_size);
  31918. #endif
  31919. next:
  31920. curr = DUK_HEAPHDR_GET_NEXT(heap, curr);
  31921. #ifdef DUK_USE_DEBUG
  31922. (*p_count_check)++;
  31923. #endif
  31924. }
  31925. }
  31926. DUK_LOCAL void duk__compact_objects(duk_heap *heap) {
  31927. /* XXX: which lists should participate? to be finalized? */
  31928. #ifdef DUK_USE_DEBUG
  31929. duk_size_t count_check = 0;
  31930. duk_size_t count_compact = 0;
  31931. duk_size_t count_bytes_saved = 0;
  31932. #endif
  31933. duk_hthread *thr;
  31934. DUK_DD(DUK_DDPRINT("duk__compact_objects: %p", (void *) heap));
  31935. thr = duk__get_temp_hthread(heap);
  31936. DUK_ASSERT(thr != NULL);
  31937. #ifdef DUK_USE_DEBUG
  31938. duk__compact_object_list(heap, thr, heap->heap_allocated, &count_check, &count_compact, &count_bytes_saved);
  31939. duk__compact_object_list(heap, thr, heap->finalize_list, &count_check, &count_compact, &count_bytes_saved);
  31940. #ifdef DUK_USE_REFERENCE_COUNTING
  31941. duk__compact_object_list(heap, thr, heap->refzero_list, &count_check, &count_compact, &count_bytes_saved);
  31942. #endif
  31943. #else
  31944. duk__compact_object_list(heap, thr, heap->heap_allocated);
  31945. duk__compact_object_list(heap, thr, heap->finalize_list);
  31946. #ifdef DUK_USE_REFERENCE_COUNTING
  31947. duk__compact_object_list(heap, thr, heap->refzero_list);
  31948. #endif
  31949. #endif
  31950. #ifdef DUK_USE_DEBUG
  31951. DUK_D(DUK_DPRINT("mark-and-sweep compact objects: %ld checked, %ld compaction attempts, %ld bytes saved by compaction",
  31952. (long) count_check, (long) count_compact, (long) count_bytes_saved));
  31953. #endif
  31954. }
  31955. /*
  31956. * Assertion helpers.
  31957. */
  31958. #ifdef DUK_USE_ASSERTIONS
  31959. DUK_LOCAL void duk__assert_heaphdr_flags(duk_heap *heap) {
  31960. duk_heaphdr *hdr;
  31961. hdr = heap->heap_allocated;
  31962. while (hdr) {
  31963. DUK_ASSERT(!DUK_HEAPHDR_HAS_REACHABLE(hdr));
  31964. DUK_ASSERT(!DUK_HEAPHDR_HAS_TEMPROOT(hdr));
  31965. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(hdr));
  31966. /* may have FINALIZED */
  31967. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31968. }
  31969. #ifdef DUK_USE_REFERENCE_COUNTING
  31970. hdr = heap->refzero_list;
  31971. while (hdr) {
  31972. DUK_ASSERT(!DUK_HEAPHDR_HAS_REACHABLE(hdr));
  31973. DUK_ASSERT(!DUK_HEAPHDR_HAS_TEMPROOT(hdr));
  31974. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(hdr));
  31975. DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZED(hdr));
  31976. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  31977. }
  31978. #endif /* DUK_USE_REFERENCE_COUNTING */
  31979. }
  31980. #ifdef DUK_USE_REFERENCE_COUNTING
  31981. DUK_LOCAL void duk__assert_valid_refcounts(duk_heap *heap) {
  31982. duk_heaphdr *hdr = heap->heap_allocated;
  31983. while (hdr) {
  31984. if (DUK_HEAPHDR_GET_REFCOUNT(hdr) == 0 &&
  31985. DUK_HEAPHDR_HAS_FINALIZED(hdr)) {
  31986. /* An object may be in heap_allocated list with a zero
  31987. * refcount if it has just been finalized and is waiting
  31988. * to be collected by the next cycle.
  31989. */
  31990. } else if (DUK_HEAPHDR_GET_REFCOUNT(hdr) == 0) {
  31991. /* An object may be in heap_allocated list with a zero
  31992. * refcount also if it is a temporary object created by
  31993. * a finalizer; because finalization now runs inside
  31994. * mark-and-sweep, such objects will not be queued to
  31995. * refzero_list and will thus appear here with refcount
  31996. * zero.
  31997. */
  31998. #if 0 /* this case can no longer occur because refcount is unsigned */
  31999. } else if (DUK_HEAPHDR_GET_REFCOUNT(hdr) < 0) {
  32000. DUK_D(DUK_DPRINT("invalid refcount: %ld, %p -> %!O",
  32001. (hdr != NULL ? (long) DUK_HEAPHDR_GET_REFCOUNT(hdr) : (long) 0),
  32002. (void *) hdr, (duk_heaphdr *) hdr));
  32003. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(hdr) > 0);
  32004. #endif
  32005. }
  32006. hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  32007. }
  32008. }
  32009. #endif /* DUK_USE_REFERENCE_COUNTING */
  32010. #endif /* DUK_USE_ASSERTIONS */
  32011. /*
  32012. * Main mark-and-sweep function.
  32013. *
  32014. * 'flags' represents the features requested by the caller. The current
  32015. * heap->mark_and_sweep_base_flags is ORed automatically into the flags;
  32016. * the base flags mask typically prevents certain mark-and-sweep operations
  32017. * to avoid trouble.
  32018. */
  32019. DUK_INTERNAL duk_bool_t duk_heap_mark_and_sweep(duk_heap *heap, duk_small_uint_t flags) {
  32020. duk_hthread *thr;
  32021. duk_size_t count_keep_obj;
  32022. duk_size_t count_keep_str;
  32023. #ifdef DUK_USE_VOLUNTARY_GC
  32024. duk_size_t tmp;
  32025. #endif
  32026. /* XXX: thread selection for mark-and-sweep is currently a hack.
  32027. * If we don't have a thread, the entire mark-and-sweep is now
  32028. * skipped (although we could just skip finalizations).
  32029. */
  32030. thr = duk__get_temp_hthread(heap);
  32031. if (thr == NULL) {
  32032. DUK_D(DUK_DPRINT("temporary hack: gc skipped because we don't have a temp thread"));
  32033. /* reset voluntary gc trigger count */
  32034. #ifdef DUK_USE_VOLUNTARY_GC
  32035. heap->mark_and_sweep_trigger_counter = DUK_HEAP_MARK_AND_SWEEP_TRIGGER_SKIP;
  32036. #endif
  32037. return 0; /* OK */
  32038. }
  32039. DUK_D(DUK_DPRINT("garbage collect (mark-and-sweep) starting, requested flags: 0x%08lx, effective flags: 0x%08lx",
  32040. (unsigned long) flags, (unsigned long) (flags | heap->mark_and_sweep_base_flags)));
  32041. flags |= heap->mark_and_sweep_base_flags;
  32042. /*
  32043. * Assertions before
  32044. */
  32045. #ifdef DUK_USE_ASSERTIONS
  32046. DUK_ASSERT(!DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap));
  32047. DUK_ASSERT(!DUK_HEAP_HAS_MARKANDSWEEP_RECLIMIT_REACHED(heap));
  32048. DUK_ASSERT(heap->mark_and_sweep_recursion_depth == 0);
  32049. duk__assert_heaphdr_flags(heap);
  32050. #ifdef DUK_USE_REFERENCE_COUNTING
  32051. /* Note: DUK_HEAP_HAS_REFZERO_FREE_RUNNING(heap) may be true; a refcount
  32052. * finalizer may trigger a mark-and-sweep.
  32053. */
  32054. duk__assert_valid_refcounts(heap);
  32055. #endif /* DUK_USE_REFERENCE_COUNTING */
  32056. #endif /* DUK_USE_ASSERTIONS */
  32057. /*
  32058. * Begin
  32059. */
  32060. DUK_HEAP_SET_MARKANDSWEEP_RUNNING(heap);
  32061. /*
  32062. * Mark roots, hoping that recursion limit is not normally hit.
  32063. * If recursion limit is hit, run additional reachability rounds
  32064. * starting from "temproots" until marking is complete.
  32065. *
  32066. * Marking happens in two phases: first we mark actual reachability
  32067. * roots (and run "temproots" to complete the process). Then we
  32068. * check which objects are unreachable and are finalizable; such
  32069. * objects are marked as FINALIZABLE and marked as reachability
  32070. * (and "temproots" is run again to complete the process).
  32071. *
  32072. * The heap finalize_list must also be marked as a reachability root.
  32073. * There may be objects on the list from a previous round if the
  32074. * previous run had finalizer skip flag.
  32075. */
  32076. duk__mark_roots_heap(heap); /* main reachability roots */
  32077. #ifdef DUK_USE_REFERENCE_COUNTING
  32078. duk__mark_refzero_list(heap); /* refzero_list treated as reachability roots */
  32079. #endif
  32080. duk__mark_temproots_by_heap_scan(heap); /* temproots */
  32081. duk__mark_finalizable(heap); /* mark finalizable as reachability roots */
  32082. duk__mark_finalize_list(heap); /* mark finalizer work list as reachability roots */
  32083. duk__mark_temproots_by_heap_scan(heap); /* temproots */
  32084. /*
  32085. * Sweep garbage and remove marking flags, and move objects with
  32086. * finalizers to the finalizer work list.
  32087. *
  32088. * Objects to be swept need to get their refcounts finalized before
  32089. * they are swept. In other words, their target object refcounts
  32090. * need to be decreased. This has to be done before freeing any
  32091. * objects to avoid decref'ing dangling pointers (which may happen
  32092. * even without bugs, e.g. with reference loops)
  32093. *
  32094. * Because strings don't point to other heap objects, similar
  32095. * finalization is not necessary for strings.
  32096. */
  32097. /* XXX: more emergency behavior, e.g. find smaller hash sizes etc */
  32098. #ifdef DUK_USE_REFERENCE_COUNTING
  32099. duk__finalize_refcounts(heap);
  32100. #endif
  32101. duk__sweep_heap(heap, flags, &count_keep_obj);
  32102. #if defined(DUK_USE_STRTAB_CHAIN)
  32103. duk__sweep_stringtable_chain(heap, &count_keep_str);
  32104. #elif defined(DUK_USE_STRTAB_PROBE)
  32105. duk__sweep_stringtable_probe(heap, &count_keep_str);
  32106. #else
  32107. #error internal error, invalid strtab options
  32108. #endif
  32109. #ifdef DUK_USE_REFERENCE_COUNTING
  32110. duk__clear_refzero_list_flags(heap);
  32111. #endif
  32112. duk__clear_finalize_list_flags(heap);
  32113. /*
  32114. * Object compaction (emergency only).
  32115. *
  32116. * Object compaction is a separate step after sweeping, as there is
  32117. * more free memory for it to work with. Also, currently compaction
  32118. * may insert new objects into the heap allocated list and the string
  32119. * table which we don't want to do during a sweep (the reachability
  32120. * flags of such objects would be incorrect). The objects inserted
  32121. * are currently:
  32122. *
  32123. * - a temporary duk_hbuffer for a new properties allocation
  32124. * - if array part is abandoned, string keys are interned
  32125. *
  32126. * The object insertions go to the front of the list, so they do not
  32127. * cause an infinite loop (they are not compacted).
  32128. */
  32129. if ((flags & DUK_MS_FLAG_EMERGENCY) &&
  32130. !(flags & DUK_MS_FLAG_NO_OBJECT_COMPACTION)) {
  32131. duk__compact_objects(heap);
  32132. }
  32133. /*
  32134. * String table resize check.
  32135. *
  32136. * Note: this may silently (and safely) fail if GC is caused by an
  32137. * allocation call in stringtable resize_hash(). Resize_hash()
  32138. * will prevent a recursive call to itself by setting the
  32139. * DUK_MS_FLAG_NO_STRINGTABLE_RESIZE in heap->mark_and_sweep_base_flags.
  32140. */
  32141. /* XXX: stringtable emergency compaction? */
  32142. #if defined(DUK_USE_MS_STRINGTABLE_RESIZE)
  32143. if (!(flags & DUK_MS_FLAG_NO_STRINGTABLE_RESIZE)) {
  32144. DUK_DD(DUK_DDPRINT("resize stringtable: %p", (void *) heap));
  32145. duk_heap_force_strtab_resize(heap);
  32146. } else {
  32147. DUK_D(DUK_DPRINT("stringtable resize skipped because DUK_MS_FLAG_NO_STRINGTABLE_RESIZE is set"));
  32148. }
  32149. #endif
  32150. /*
  32151. * Finalize objects in the finalization work list. Finalized
  32152. * objects are queued back to heap_allocated with FINALIZED set.
  32153. *
  32154. * Since finalizers may cause arbitrary side effects, they are
  32155. * prevented during string table and object property allocation
  32156. * resizing using the DUK_MS_FLAG_NO_FINALIZERS flag in
  32157. * heap->mark_and_sweep_base_flags. In this case the objects
  32158. * remain in the finalization work list after mark-and-sweep
  32159. * exits and they may be finalized on the next pass.
  32160. *
  32161. * Finalization currently happens inside "MARKANDSWEEP_RUNNING"
  32162. * protection (no mark-and-sweep may be triggered by the
  32163. * finalizers). As a side effect:
  32164. *
  32165. * 1) an out-of-memory error inside a finalizer will not
  32166. * cause a mark-and-sweep and may cause the finalizer
  32167. * to fail unnecessarily
  32168. *
  32169. * 2) any temporary objects whose refcount decreases to zero
  32170. * during finalization will not be put into refzero_list;
  32171. * they can only be collected by another mark-and-sweep
  32172. *
  32173. * This is not optimal, but since the sweep for this phase has
  32174. * already happened, this is probably good enough for now.
  32175. */
  32176. if (!(flags & DUK_MS_FLAG_NO_FINALIZERS)) {
  32177. duk__run_object_finalizers(heap);
  32178. } else {
  32179. DUK_D(DUK_DPRINT("finalizer run skipped because DUK_MS_FLAG_NO_FINALIZERS is set"));
  32180. }
  32181. /*
  32182. * Finish
  32183. */
  32184. DUK_HEAP_CLEAR_MARKANDSWEEP_RUNNING(heap);
  32185. /*
  32186. * Assertions after
  32187. */
  32188. #ifdef DUK_USE_ASSERTIONS
  32189. DUK_ASSERT(!DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap));
  32190. DUK_ASSERT(!DUK_HEAP_HAS_MARKANDSWEEP_RECLIMIT_REACHED(heap));
  32191. DUK_ASSERT(heap->mark_and_sweep_recursion_depth == 0);
  32192. duk__assert_heaphdr_flags(heap);
  32193. #ifdef DUK_USE_REFERENCE_COUNTING
  32194. /* Note: DUK_HEAP_HAS_REFZERO_FREE_RUNNING(heap) may be true; a refcount
  32195. * finalizer may trigger a mark-and-sweep.
  32196. */
  32197. duk__assert_valid_refcounts(heap);
  32198. #endif /* DUK_USE_REFERENCE_COUNTING */
  32199. #endif /* DUK_USE_ASSERTIONS */
  32200. /*
  32201. * Reset trigger counter
  32202. */
  32203. #ifdef DUK_USE_VOLUNTARY_GC
  32204. tmp = (count_keep_obj + count_keep_str) / 256;
  32205. heap->mark_and_sweep_trigger_counter = (duk_int_t) (
  32206. (tmp * DUK_HEAP_MARK_AND_SWEEP_TRIGGER_MULT) +
  32207. DUK_HEAP_MARK_AND_SWEEP_TRIGGER_ADD);
  32208. DUK_D(DUK_DPRINT("garbage collect (mark-and-sweep) finished: %ld objects kept, %ld strings kept, trigger reset to %ld",
  32209. (long) count_keep_obj, (long) count_keep_str, (long) heap->mark_and_sweep_trigger_counter));
  32210. #else
  32211. DUK_D(DUK_DPRINT("garbage collect (mark-and-sweep) finished: %ld objects kept, %ld strings kept, no voluntary trigger",
  32212. (long) count_keep_obj, (long) count_keep_str));
  32213. #endif
  32214. return 0; /* OK */
  32215. }
  32216. #else /* DUK_USE_MARK_AND_SWEEP */
  32217. /* no mark-and-sweep gc */
  32218. #endif /* DUK_USE_MARK_AND_SWEEP */
  32219. #line 1 "duk_heap_memory.c"
  32220. /*
  32221. * Memory allocation handling.
  32222. */
  32223. /* include removed: duk_internal.h */
  32224. /*
  32225. * Helpers
  32226. *
  32227. * The fast path checks are done within a macro to ensure "inlining"
  32228. * while the slow path actions use a helper (which won't typically be
  32229. * inlined in size optimized builds).
  32230. */
  32231. #if defined(DUK_USE_MARK_AND_SWEEP) && defined(DUK_USE_VOLUNTARY_GC)
  32232. #define DUK__VOLUNTARY_PERIODIC_GC(heap) do { \
  32233. (heap)->mark_and_sweep_trigger_counter--; \
  32234. if ((heap)->mark_and_sweep_trigger_counter <= 0) { \
  32235. duk__run_voluntary_gc(heap); \
  32236. } \
  32237. } while (0)
  32238. DUK_LOCAL void duk__run_voluntary_gc(duk_heap *heap) {
  32239. if (DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32240. DUK_DD(DUK_DDPRINT("mark-and-sweep in progress -> skip voluntary mark-and-sweep now"));
  32241. } else {
  32242. duk_small_uint_t flags;
  32243. duk_bool_t rc;
  32244. DUK_D(DUK_DPRINT("triggering voluntary mark-and-sweep"));
  32245. flags = 0;
  32246. rc = duk_heap_mark_and_sweep(heap, flags);
  32247. DUK_UNREF(rc);
  32248. }
  32249. }
  32250. #else
  32251. #define DUK__VOLUNTARY_PERIODIC_GC(heap) /* no voluntary gc */
  32252. #endif /* DUK_USE_MARK_AND_SWEEP && DUK_USE_VOLUNTARY_GC */
  32253. /*
  32254. * Allocate memory with garbage collection
  32255. */
  32256. #ifdef DUK_USE_MARK_AND_SWEEP
  32257. DUK_INTERNAL void *duk_heap_mem_alloc(duk_heap *heap, duk_size_t size) {
  32258. void *res;
  32259. duk_bool_t rc;
  32260. duk_small_int_t i;
  32261. DUK_ASSERT(heap != NULL);
  32262. DUK_ASSERT_DISABLE(size >= 0);
  32263. /*
  32264. * Voluntary periodic GC (if enabled)
  32265. */
  32266. DUK__VOLUNTARY_PERIODIC_GC(heap);
  32267. /*
  32268. * First attempt
  32269. */
  32270. #ifdef DUK_USE_GC_TORTURE
  32271. /* simulate alloc failure on every alloc (except when mark-and-sweep is running) */
  32272. if (!DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32273. DUK_DDD(DUK_DDDPRINT("gc torture enabled, pretend that first alloc attempt fails"));
  32274. res = NULL;
  32275. DUK_UNREF(res);
  32276. goto skip_attempt;
  32277. }
  32278. #endif
  32279. res = heap->alloc_func(heap->heap_udata, size);
  32280. if (res || size == 0) {
  32281. /* for zero size allocations NULL is allowed */
  32282. return res;
  32283. }
  32284. #ifdef DUK_USE_GC_TORTURE
  32285. skip_attempt:
  32286. #endif
  32287. DUK_D(DUK_DPRINT("first alloc attempt failed, attempt to gc and retry"));
  32288. /*
  32289. * Avoid a GC if GC is already running. This can happen at a late
  32290. * stage in a GC when we try to e.g. resize the stringtable
  32291. * or compact objects.
  32292. */
  32293. if (DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32294. DUK_D(DUK_DPRINT("duk_heap_mem_alloc() failed, gc in progress (gc skipped), alloc size %ld", (long) size));
  32295. return NULL;
  32296. }
  32297. /*
  32298. * Retry with several GC attempts. Initial attempts are made without
  32299. * emergency mode; later attempts use emergency mode which minimizes
  32300. * memory allocations forcibly.
  32301. */
  32302. for (i = 0; i < DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_LIMIT; i++) {
  32303. duk_small_uint_t flags;
  32304. flags = 0;
  32305. if (i >= DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_EMERGENCY_LIMIT - 1) {
  32306. flags |= DUK_MS_FLAG_EMERGENCY;
  32307. }
  32308. rc = duk_heap_mark_and_sweep(heap, flags);
  32309. DUK_UNREF(rc);
  32310. res = heap->alloc_func(heap->heap_udata, size);
  32311. if (res) {
  32312. DUK_D(DUK_DPRINT("duk_heap_mem_alloc() succeeded after gc (pass %ld), alloc size %ld",
  32313. (long) (i + 1), (long) size));
  32314. return res;
  32315. }
  32316. }
  32317. DUK_D(DUK_DPRINT("duk_heap_mem_alloc() failed even after gc, alloc size %ld", (long) size));
  32318. return NULL;
  32319. }
  32320. #else /* DUK_USE_MARK_AND_SWEEP */
  32321. /*
  32322. * Compared to a direct macro expansion this wrapper saves a few
  32323. * instructions because no heap dereferencing is required.
  32324. */
  32325. DUK_INTERNAL void *duk_heap_mem_alloc(duk_heap *heap, duk_size_t size) {
  32326. DUK_ASSERT(heap != NULL);
  32327. DUK_ASSERT_DISABLE(size >= 0);
  32328. return heap->alloc_func(heap->heap_udata, size);
  32329. }
  32330. #endif /* DUK_USE_MARK_AND_SWEEP */
  32331. DUK_INTERNAL void *duk_heap_mem_alloc_zeroed(duk_heap *heap, duk_size_t size) {
  32332. void *res;
  32333. DUK_ASSERT(heap != NULL);
  32334. DUK_ASSERT_DISABLE(size >= 0);
  32335. res = DUK_ALLOC(heap, size);
  32336. if (res) {
  32337. /* assume memset with zero size is OK */
  32338. DUK_MEMZERO(res, size);
  32339. }
  32340. return res;
  32341. }
  32342. /*
  32343. * Reallocate memory with garbage collection
  32344. */
  32345. #ifdef DUK_USE_MARK_AND_SWEEP
  32346. DUK_INTERNAL void *duk_heap_mem_realloc(duk_heap *heap, void *ptr, duk_size_t newsize) {
  32347. void *res;
  32348. duk_bool_t rc;
  32349. duk_small_int_t i;
  32350. DUK_ASSERT(heap != NULL);
  32351. /* ptr may be NULL */
  32352. DUK_ASSERT_DISABLE(newsize >= 0);
  32353. /*
  32354. * Voluntary periodic GC (if enabled)
  32355. */
  32356. DUK__VOLUNTARY_PERIODIC_GC(heap);
  32357. /*
  32358. * First attempt
  32359. */
  32360. #ifdef DUK_USE_GC_TORTURE
  32361. /* simulate alloc failure on every realloc (except when mark-and-sweep is running) */
  32362. if (!DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32363. DUK_DDD(DUK_DDDPRINT("gc torture enabled, pretend that first realloc attempt fails"));
  32364. res = NULL;
  32365. DUK_UNREF(res);
  32366. goto skip_attempt;
  32367. }
  32368. #endif
  32369. res = heap->realloc_func(heap->heap_udata, ptr, newsize);
  32370. if (res || newsize == 0) {
  32371. /* for zero size allocations NULL is allowed */
  32372. return res;
  32373. }
  32374. #ifdef DUK_USE_GC_TORTURE
  32375. skip_attempt:
  32376. #endif
  32377. DUK_D(DUK_DPRINT("first realloc attempt failed, attempt to gc and retry"));
  32378. /*
  32379. * Avoid a GC if GC is already running. See duk_heap_mem_alloc().
  32380. */
  32381. if (DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32382. DUK_D(DUK_DPRINT("duk_heap_mem_realloc() failed, gc in progress (gc skipped), alloc size %ld", (long) newsize));
  32383. return NULL;
  32384. }
  32385. /*
  32386. * Retry with several GC attempts. Initial attempts are made without
  32387. * emergency mode; later attempts use emergency mode which minimizes
  32388. * memory allocations forcibly.
  32389. */
  32390. for (i = 0; i < DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_LIMIT; i++) {
  32391. duk_small_uint_t flags;
  32392. flags = 0;
  32393. if (i >= DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_EMERGENCY_LIMIT - 1) {
  32394. flags |= DUK_MS_FLAG_EMERGENCY;
  32395. }
  32396. rc = duk_heap_mark_and_sweep(heap, flags);
  32397. DUK_UNREF(rc);
  32398. res = heap->realloc_func(heap->heap_udata, ptr, newsize);
  32399. if (res || newsize == 0) {
  32400. DUK_D(DUK_DPRINT("duk_heap_mem_realloc() succeeded after gc (pass %ld), alloc size %ld",
  32401. (long) (i + 1), (long) newsize));
  32402. return res;
  32403. }
  32404. }
  32405. DUK_D(DUK_DPRINT("duk_heap_mem_realloc() failed even after gc, alloc size %ld", (long) newsize));
  32406. return NULL;
  32407. }
  32408. #else /* DUK_USE_MARK_AND_SWEEP */
  32409. /* saves a few instructions to have this wrapper (see comment on duk_heap_mem_alloc) */
  32410. DUK_INTERNAL void *duk_heap_mem_realloc(duk_heap *heap, void *ptr, duk_size_t newsize) {
  32411. DUK_ASSERT(heap != NULL);
  32412. /* ptr may be NULL */
  32413. DUK_ASSERT_DISABLE(newsize >= 0);
  32414. return heap->realloc_func(heap->heap_udata, ptr, newsize);
  32415. }
  32416. #endif /* DUK_USE_MARK_AND_SWEEP */
  32417. /*
  32418. * Reallocate memory with garbage collection, using a callback to provide
  32419. * the current allocated pointer. This variant is used when a mark-and-sweep
  32420. * (e.g. finalizers) might change the original pointer.
  32421. */
  32422. #ifdef DUK_USE_MARK_AND_SWEEP
  32423. DUK_INTERNAL void *duk_heap_mem_realloc_indirect(duk_heap *heap, duk_mem_getptr cb, void *ud, duk_size_t newsize) {
  32424. void *res;
  32425. duk_bool_t rc;
  32426. duk_small_int_t i;
  32427. DUK_ASSERT(heap != NULL);
  32428. DUK_ASSERT_DISABLE(newsize >= 0);
  32429. /*
  32430. * Voluntary periodic GC (if enabled)
  32431. */
  32432. DUK__VOLUNTARY_PERIODIC_GC(heap);
  32433. /*
  32434. * First attempt
  32435. */
  32436. #ifdef DUK_USE_GC_TORTURE
  32437. /* simulate alloc failure on every realloc (except when mark-and-sweep is running) */
  32438. if (!DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32439. DUK_DDD(DUK_DDDPRINT("gc torture enabled, pretend that first indirect realloc attempt fails"));
  32440. res = NULL;
  32441. DUK_UNREF(res);
  32442. goto skip_attempt;
  32443. }
  32444. #endif
  32445. res = heap->realloc_func(heap->heap_udata, cb(heap, ud), newsize);
  32446. if (res || newsize == 0) {
  32447. /* for zero size allocations NULL is allowed */
  32448. return res;
  32449. }
  32450. #ifdef DUK_USE_GC_TORTURE
  32451. skip_attempt:
  32452. #endif
  32453. DUK_D(DUK_DPRINT("first indirect realloc attempt failed, attempt to gc and retry"));
  32454. /*
  32455. * Avoid a GC if GC is already running. See duk_heap_mem_alloc().
  32456. */
  32457. if (DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32458. DUK_D(DUK_DPRINT("duk_heap_mem_realloc_indirect() failed, gc in progress (gc skipped), alloc size %ld", (long) newsize));
  32459. return NULL;
  32460. }
  32461. /*
  32462. * Retry with several GC attempts. Initial attempts are made without
  32463. * emergency mode; later attempts use emergency mode which minimizes
  32464. * memory allocations forcibly.
  32465. */
  32466. for (i = 0; i < DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_LIMIT; i++) {
  32467. duk_small_uint_t flags;
  32468. #ifdef DUK_USE_ASSERTIONS
  32469. void *ptr_pre; /* ptr before mark-and-sweep */
  32470. void *ptr_post;
  32471. #endif
  32472. #ifdef DUK_USE_ASSERTIONS
  32473. ptr_pre = cb(heap, ud);
  32474. #endif
  32475. flags = 0;
  32476. if (i >= DUK_HEAP_ALLOC_FAIL_MARKANDSWEEP_EMERGENCY_LIMIT - 1) {
  32477. flags |= DUK_MS_FLAG_EMERGENCY;
  32478. }
  32479. rc = duk_heap_mark_and_sweep(heap, flags);
  32480. DUK_UNREF(rc);
  32481. #ifdef DUK_USE_ASSERTIONS
  32482. ptr_post = cb(heap, ud);
  32483. if (ptr_pre != ptr_post) {
  32484. /* useful for debugging */
  32485. DUK_DD(DUK_DDPRINT("note: base pointer changed by mark-and-sweep: %p -> %p",
  32486. (void *) ptr_pre, (void *) ptr_post));
  32487. }
  32488. #endif
  32489. /* Note: key issue here is to re-lookup the base pointer on every attempt.
  32490. * The pointer being reallocated may change after every mark-and-sweep.
  32491. */
  32492. res = heap->realloc_func(heap->heap_udata, cb(heap, ud), newsize);
  32493. if (res || newsize == 0) {
  32494. DUK_D(DUK_DPRINT("duk_heap_mem_realloc_indirect() succeeded after gc (pass %ld), alloc size %ld",
  32495. (long) (i + 1), (long) newsize));
  32496. return res;
  32497. }
  32498. }
  32499. DUK_D(DUK_DPRINT("duk_heap_mem_realloc_indirect() failed even after gc, alloc size %ld", (long) newsize));
  32500. return NULL;
  32501. }
  32502. #else /* DUK_USE_MARK_AND_SWEEP */
  32503. /* saves a few instructions to have this wrapper (see comment on duk_heap_mem_alloc) */
  32504. DUK_INTERNAL void *duk_heap_mem_realloc_indirect(duk_heap *heap, duk_mem_getptr cb, void *ud, duk_size_t newsize) {
  32505. return heap->realloc_func(heap->heap_udata, cb(heap, ud), newsize);
  32506. }
  32507. #endif /* DUK_USE_MARK_AND_SWEEP */
  32508. /*
  32509. * Free memory
  32510. */
  32511. #ifdef DUK_USE_MARK_AND_SWEEP
  32512. DUK_INTERNAL void duk_heap_mem_free(duk_heap *heap, void *ptr) {
  32513. DUK_ASSERT(heap != NULL);
  32514. /* ptr may be NULL */
  32515. /* Must behave like a no-op with NULL and any pointer returned from
  32516. * malloc/realloc with zero size.
  32517. */
  32518. heap->free_func(heap->heap_udata, ptr);
  32519. /* Count free operations toward triggering a GC but never actually trigger
  32520. * a GC from a free. Otherwise code which frees internal structures would
  32521. * need to put in NULLs at every turn to ensure the object is always in
  32522. * consistent state for a mark-and-sweep.
  32523. */
  32524. #ifdef DUK_USE_VOLUNTARY_GC
  32525. heap->mark_and_sweep_trigger_counter--;
  32526. #endif
  32527. }
  32528. #else
  32529. /* saves a few instructions to have this wrapper (see comment on duk_heap_mem_alloc) */
  32530. DUK_INTERNAL void duk_heap_mem_free(duk_heap *heap, void *ptr) {
  32531. DUK_ASSERT(heap != NULL);
  32532. /* ptr may be NULL */
  32533. /* Note: must behave like a no-op with NULL and any pointer
  32534. * returned from malloc/realloc with zero size.
  32535. */
  32536. heap->free_func(heap->heap_udata, ptr);
  32537. }
  32538. #endif
  32539. #line 1 "duk_heap_misc.c"
  32540. /*
  32541. * Support functions for duk_heap.
  32542. */
  32543. /* include removed: duk_internal.h */
  32544. #if defined(DUK_USE_DOUBLE_LINKED_HEAP) && defined(DUK_USE_REFERENCE_COUNTING)
  32545. /* arbitrary remove only works with double linked heap, and is only required by
  32546. * reference counting so far.
  32547. */
  32548. DUK_INTERNAL void duk_heap_remove_any_from_heap_allocated(duk_heap *heap, duk_heaphdr *hdr) {
  32549. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(hdr) != DUK_HTYPE_STRING);
  32550. if (DUK_HEAPHDR_GET_PREV(heap, hdr)) {
  32551. DUK_HEAPHDR_SET_NEXT(heap, DUK_HEAPHDR_GET_PREV(heap, hdr), DUK_HEAPHDR_GET_NEXT(heap, hdr));
  32552. } else {
  32553. heap->heap_allocated = DUK_HEAPHDR_GET_NEXT(heap, hdr);
  32554. }
  32555. if (DUK_HEAPHDR_GET_NEXT(heap, hdr)) {
  32556. DUK_HEAPHDR_SET_PREV(heap, DUK_HEAPHDR_GET_NEXT(heap, hdr), DUK_HEAPHDR_GET_PREV(heap, hdr));
  32557. } else {
  32558. ;
  32559. }
  32560. }
  32561. #endif
  32562. DUK_INTERNAL void duk_heap_insert_into_heap_allocated(duk_heap *heap, duk_heaphdr *hdr) {
  32563. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(hdr) != DUK_HTYPE_STRING);
  32564. #ifdef DUK_USE_DOUBLE_LINKED_HEAP
  32565. if (heap->heap_allocated) {
  32566. DUK_ASSERT(DUK_HEAPHDR_GET_PREV(heap, heap->heap_allocated) == NULL);
  32567. DUK_HEAPHDR_SET_PREV(heap, heap->heap_allocated, hdr);
  32568. }
  32569. DUK_HEAPHDR_SET_PREV(heap, hdr, NULL);
  32570. #endif
  32571. DUK_HEAPHDR_SET_NEXT(heap, hdr, heap->heap_allocated);
  32572. heap->heap_allocated = hdr;
  32573. }
  32574. #ifdef DUK_USE_INTERRUPT_COUNTER
  32575. DUK_INTERNAL void duk_heap_switch_thread(duk_heap *heap, duk_hthread *new_thr) {
  32576. /* Copy currently active interrupt counter from the active thread
  32577. * back to the heap structure. It doesn't need to be copied to
  32578. * the target thread, as the bytecode executor does that when it
  32579. * resumes execution for a new thread.
  32580. */
  32581. if (heap->curr_thread != NULL) {
  32582. heap->interrupt_counter = heap->curr_thread->interrupt_counter;
  32583. }
  32584. heap->curr_thread = new_thr; /* may be NULL */
  32585. }
  32586. #endif /* DUK_USE_INTERRUPT_COUNTER */
  32587. #line 1 "duk_heap_refcount.c"
  32588. /*
  32589. * Reference counting implementation.
  32590. */
  32591. /* include removed: duk_internal.h */
  32592. #ifdef DUK_USE_REFERENCE_COUNTING
  32593. #ifndef DUK_USE_DOUBLE_LINKED_HEAP
  32594. #error internal error, reference counting requires a double linked heap
  32595. #endif
  32596. /*
  32597. * Misc
  32598. */
  32599. DUK_LOCAL void duk__queue_refzero(duk_heap *heap, duk_heaphdr *hdr) {
  32600. /* tail insert: don't disturb head in case refzero is running */
  32601. if (heap->refzero_list != NULL) {
  32602. duk_heaphdr *hdr_prev;
  32603. hdr_prev = heap->refzero_list_tail;
  32604. DUK_ASSERT(hdr_prev != NULL);
  32605. DUK_ASSERT(DUK_HEAPHDR_GET_NEXT(heap, hdr_prev) == NULL);
  32606. DUK_HEAPHDR_SET_NEXT(heap, hdr, NULL);
  32607. DUK_HEAPHDR_SET_PREV(heap, hdr, hdr_prev);
  32608. DUK_HEAPHDR_SET_NEXT(heap, hdr_prev, hdr);
  32609. heap->refzero_list_tail = hdr;
  32610. } else {
  32611. DUK_ASSERT(heap->refzero_list_tail == NULL);
  32612. DUK_HEAPHDR_SET_NEXT(heap, hdr, NULL);
  32613. DUK_HEAPHDR_SET_PREV(heap, hdr, NULL);
  32614. heap->refzero_list = hdr;
  32615. heap->refzero_list_tail = hdr;
  32616. }
  32617. }
  32618. /*
  32619. * Heap object refcount finalization.
  32620. *
  32621. * When an object is about to be freed, all other objects it refers to must
  32622. * be decref'd. Refcount finalization does NOT free the object or its inner
  32623. * allocations (mark-and-sweep shares these helpers), it just manipulates
  32624. * the refcounts.
  32625. *
  32626. * Note that any of the decref's may cause a refcount to drop to zero, BUT
  32627. * it will not be processed inline; instead, because refzero is already
  32628. * running, the objects will just be queued to refzero list and processed
  32629. * later. This eliminates C recursion.
  32630. */
  32631. DUK_LOCAL void duk__refcount_finalize_hobject(duk_hthread *thr, duk_hobject *h) {
  32632. duk_uint_fast32_t i;
  32633. DUK_ASSERT(h);
  32634. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE((duk_heaphdr *) h) == DUK_HTYPE_OBJECT);
  32635. /* XXX: better to get base and walk forwards? */
  32636. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(h); i++) {
  32637. duk_hstring *key = DUK_HOBJECT_E_GET_KEY(thr->heap, h, i);
  32638. if (!key) {
  32639. continue;
  32640. }
  32641. duk_heaphdr_decref(thr, (duk_heaphdr *) key);
  32642. if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, h, i)) {
  32643. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_GETTER(thr->heap, h, i));
  32644. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, h, i));
  32645. } else {
  32646. duk_tval_decref(thr, DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, h, i));
  32647. }
  32648. }
  32649. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ASIZE(h); i++) {
  32650. duk_tval_decref(thr, DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, h, i));
  32651. }
  32652. /* hash part is a 'weak reference' and does not contribute */
  32653. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h));
  32654. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
  32655. duk_hcompiledfunction *f = (duk_hcompiledfunction *) h;
  32656. duk_tval *tv, *tv_end;
  32657. duk_hobject **funcs, **funcs_end;
  32658. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, f) != NULL); /* compiled functions must be created 'atomically' */
  32659. tv = DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(thr->heap, f);
  32660. tv_end = DUK_HCOMPILEDFUNCTION_GET_CONSTS_END(thr->heap, f);
  32661. while (tv < tv_end) {
  32662. duk_tval_decref(thr, tv);
  32663. tv++;
  32664. }
  32665. funcs = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(thr->heap, f);
  32666. funcs_end = DUK_HCOMPILEDFUNCTION_GET_FUNCS_END(thr->heap, f);
  32667. while (funcs < funcs_end) {
  32668. duk_heaphdr_decref(thr, (duk_heaphdr *) *funcs);
  32669. funcs++;
  32670. }
  32671. duk_heaphdr_decref(thr, (duk_heaphdr *) DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, f));
  32672. } else if (DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
  32673. duk_hnativefunction *f = (duk_hnativefunction *) h;
  32674. DUK_UNREF(f);
  32675. /* nothing to finalize */
  32676. } else if (DUK_HOBJECT_IS_THREAD(h)) {
  32677. duk_hthread *t = (duk_hthread *) h;
  32678. duk_tval *tv;
  32679. tv = t->valstack;
  32680. while (tv < t->valstack_end) {
  32681. duk_tval_decref(thr, tv);
  32682. tv++;
  32683. }
  32684. for (i = 0; i < (duk_uint_fast32_t) t->callstack_top; i++) {
  32685. duk_activation *act = t->callstack + i;
  32686. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_ACT_GET_FUNC(act));
  32687. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) act->var_env);
  32688. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) act->lex_env);
  32689. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  32690. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) act->prev_caller);
  32691. #endif
  32692. }
  32693. #if 0 /* nothing now */
  32694. for (i = 0; i < (duk_uint_fast32_t) t->catchstack_top; i++) {
  32695. duk_catcher *cat = t->catchstack + i;
  32696. }
  32697. #endif
  32698. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  32699. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) t->builtins[i]);
  32700. }
  32701. duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) t->resumer);
  32702. }
  32703. }
  32704. DUK_INTERNAL void duk_heaphdr_refcount_finalize(duk_hthread *thr, duk_heaphdr *hdr) {
  32705. DUK_ASSERT(hdr);
  32706. switch ((int) DUK_HEAPHDR_GET_TYPE(hdr)) {
  32707. case DUK_HTYPE_OBJECT:
  32708. duk__refcount_finalize_hobject(thr, (duk_hobject *) hdr);
  32709. break;
  32710. case DUK_HTYPE_BUFFER:
  32711. /* nothing to finalize */
  32712. break;
  32713. case DUK_HTYPE_STRING:
  32714. /* cannot happen: strings are not put into refzero list (they don't even have the next/prev pointers) */
  32715. default:
  32716. DUK_UNREACHABLE();
  32717. }
  32718. }
  32719. /*
  32720. * Refcount memory freeing loop.
  32721. *
  32722. * Frees objects in the refzero_pending list until the list becomes
  32723. * empty. When an object is freed, its references get decref'd and
  32724. * may cause further objects to be queued for freeing.
  32725. *
  32726. * This could be expanded to allow incremental freeing: just bail out
  32727. * early and resume at a future alloc/decref/refzero.
  32728. */
  32729. DUK_LOCAL void duk__refzero_free_pending(duk_hthread *thr) {
  32730. duk_heaphdr *h1, *h2;
  32731. duk_heap *heap;
  32732. duk_int_t count = 0;
  32733. DUK_ASSERT(thr != NULL);
  32734. DUK_ASSERT(thr->heap != NULL);
  32735. heap = thr->heap;
  32736. DUK_ASSERT(heap != NULL);
  32737. /*
  32738. * Detect recursive invocation
  32739. */
  32740. if (DUK_HEAP_HAS_REFZERO_FREE_RUNNING(heap)) {
  32741. DUK_DDD(DUK_DDDPRINT("refzero free running, skip run"));
  32742. return;
  32743. }
  32744. /*
  32745. * Churn refzero_list until empty
  32746. */
  32747. DUK_HEAP_SET_REFZERO_FREE_RUNNING(heap);
  32748. while (heap->refzero_list) {
  32749. duk_hobject *obj;
  32750. duk_bool_t rescued = 0;
  32751. /*
  32752. * Pick an object from the head (don't remove yet).
  32753. */
  32754. h1 = heap->refzero_list;
  32755. obj = (duk_hobject *) h1;
  32756. DUK_DD(DUK_DDPRINT("refzero processing %p: %!O", (void *) h1, (duk_heaphdr *) h1));
  32757. DUK_ASSERT(DUK_HEAPHDR_GET_PREV(heap, h1) == NULL);
  32758. DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(h1) == DUK_HTYPE_OBJECT); /* currently, always the case */
  32759. /*
  32760. * Finalizer check.
  32761. *
  32762. * Note: running a finalizer may have arbitrary side effects, e.g.
  32763. * queue more objects on refzero_list (tail), or even trigger a
  32764. * mark-and-sweep.
  32765. *
  32766. * Note: quick reject check should match vast majority of
  32767. * objects and must be safe (not throw any errors, ever).
  32768. */
  32769. /* XXX: If object has FINALIZED, it was finalized by mark-and-sweep on
  32770. * its previous run. Any point in running finalizer again here? If
  32771. * finalization semantics is changed so that finalizer is only run once,
  32772. * checking for FINALIZED would happen here.
  32773. */
  32774. /* A finalizer is looked up from the object and up its prototype chain
  32775. * (which allows inherited finalizers).
  32776. */
  32777. if (duk_hobject_hasprop_raw(thr, obj, DUK_HTHREAD_STRING_INT_FINALIZER(thr))) {
  32778. DUK_DDD(DUK_DDDPRINT("object has a finalizer, run it"));
  32779. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(h1) == 0);
  32780. DUK_HEAPHDR_PREINC_REFCOUNT(h1); /* bump refcount to prevent refzero during finalizer processing */
  32781. duk_hobject_run_finalizer(thr, obj); /* must never longjmp */
  32782. DUK_HEAPHDR_PREDEC_REFCOUNT(h1); /* remove artificial bump */
  32783. DUK_ASSERT_DISABLE(h1->h_refcount >= 0); /* refcount is unsigned, so always true */
  32784. if (DUK_HEAPHDR_GET_REFCOUNT(h1) != 0) {
  32785. DUK_DDD(DUK_DDDPRINT("-> object refcount after finalization non-zero, object will be rescued"));
  32786. rescued = 1;
  32787. } else {
  32788. DUK_DDD(DUK_DDDPRINT("-> object refcount still zero after finalization, object will be freed"));
  32789. }
  32790. }
  32791. /* Refzero head is still the same. This is the case even if finalizer
  32792. * inserted more refzero objects; they are inserted to the tail.
  32793. */
  32794. DUK_ASSERT(h1 == heap->refzero_list);
  32795. /*
  32796. * Remove the object from the refzero list. This cannot be done
  32797. * before a possible finalizer has been executed; the finalizer
  32798. * may trigger a mark-and-sweep, and mark-and-sweep must be able
  32799. * to traverse a complete refzero_list.
  32800. */
  32801. h2 = DUK_HEAPHDR_GET_NEXT(heap, h1);
  32802. if (h2) {
  32803. DUK_HEAPHDR_SET_PREV(heap, h2, NULL); /* not strictly necessary */
  32804. heap->refzero_list = h2;
  32805. } else {
  32806. heap->refzero_list = NULL;
  32807. heap->refzero_list_tail = NULL;
  32808. }
  32809. /*
  32810. * Rescue or free.
  32811. */
  32812. if (rescued) {
  32813. /* yes -> move back to heap allocated */
  32814. DUK_DD(DUK_DDPRINT("object rescued during refcount finalization: %p", (void *) h1));
  32815. DUK_HEAPHDR_SET_PREV(heap, h1, NULL);
  32816. DUK_HEAPHDR_SET_NEXT(heap, h1, heap->heap_allocated);
  32817. heap->heap_allocated = h1;
  32818. } else {
  32819. /* no -> decref members, then free */
  32820. duk__refcount_finalize_hobject(thr, obj);
  32821. duk_heap_free_heaphdr_raw(heap, h1);
  32822. }
  32823. count++;
  32824. }
  32825. DUK_HEAP_CLEAR_REFZERO_FREE_RUNNING(heap);
  32826. DUK_DDD(DUK_DDDPRINT("refzero processed %ld objects", (long) count));
  32827. /*
  32828. * Once the whole refzero cascade has been freed, check for
  32829. * a voluntary mark-and-sweep.
  32830. */
  32831. #if defined(DUK_USE_MARK_AND_SWEEP) && defined(DUK_USE_VOLUNTARY_GC)
  32832. /* 'count' is more or less comparable to normal trigger counter update
  32833. * which happens in memory block (re)allocation.
  32834. */
  32835. heap->mark_and_sweep_trigger_counter -= count;
  32836. if (heap->mark_and_sweep_trigger_counter <= 0) {
  32837. duk_bool_t rc;
  32838. duk_small_uint_t flags = 0; /* not emergency */
  32839. DUK_D(DUK_DPRINT("refcount triggering mark-and-sweep"));
  32840. rc = duk_heap_mark_and_sweep(heap, flags);
  32841. DUK_UNREF(rc);
  32842. DUK_D(DUK_DPRINT("refcount triggered mark-and-sweep => rc %ld", (long) rc));
  32843. }
  32844. #endif /* DUK_USE_MARK_AND_SWEEP && DUK_USE_VOLUNTARY_GC */
  32845. }
  32846. /*
  32847. * Incref and decref functions.
  32848. *
  32849. * Decref may trigger immediate refzero handling, which may free and finalize
  32850. * an arbitrary number of objects.
  32851. *
  32852. */
  32853. DUK_INTERNAL void duk_heaphdr_refzero(duk_hthread *thr, duk_heaphdr *h) {
  32854. duk_heap *heap;
  32855. DUK_ASSERT(thr != NULL);
  32856. DUK_ASSERT(h != NULL);
  32857. heap = thr->heap;
  32858. DUK_DDD(DUK_DDDPRINT("refzero %p: %!O", (void *) h, (duk_heaphdr *) h));
  32859. #ifdef DUK_USE_MARK_AND_SWEEP
  32860. /*
  32861. * If mark-and-sweep is running, don't process 'refzero' situations at all.
  32862. * They may happen because mark-and-sweep needs to finalize refcounts for
  32863. * each object it sweeps. Otherwise the target objects of swept objects
  32864. * would have incorrect refcounts.
  32865. *
  32866. * Note: mark-and-sweep could use a separate decref handler to avoid coming
  32867. * here at all. However, mark-and-sweep may also call finalizers, which
  32868. * can do arbitrary operations and would use this decref variant anyway.
  32869. */
  32870. if (DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
  32871. DUK_DDD(DUK_DDDPRINT("refzero handling suppressed when mark-and-sweep running, object: %p", (void *) h));
  32872. return;
  32873. }
  32874. #endif
  32875. switch ((duk_small_int_t) DUK_HEAPHDR_GET_TYPE(h)) {
  32876. case DUK_HTYPE_STRING:
  32877. /*
  32878. * Strings have no internal references but do have "weak"
  32879. * references in the string cache. Also note that strings
  32880. * are not on the heap_allocated list like other heap
  32881. * elements.
  32882. */
  32883. duk_heap_strcache_string_remove(heap, (duk_hstring *) h);
  32884. duk_heap_string_remove(heap, (duk_hstring *) h);
  32885. duk_heap_free_heaphdr_raw(heap, h);
  32886. break;
  32887. case DUK_HTYPE_OBJECT:
  32888. /*
  32889. * Objects have internal references. Must finalize through
  32890. * the "refzero" work list.
  32891. */
  32892. duk_heap_remove_any_from_heap_allocated(heap, h);
  32893. duk__queue_refzero(heap, h);
  32894. duk__refzero_free_pending(thr);
  32895. break;
  32896. case DUK_HTYPE_BUFFER:
  32897. /*
  32898. * Buffers have no internal references. However, a dynamic
  32899. * buffer has a separate allocation for the buffer. This is
  32900. * freed by duk_heap_free_heaphdr_raw().
  32901. */
  32902. duk_heap_remove_any_from_heap_allocated(heap, h);
  32903. duk_heap_free_heaphdr_raw(heap, h);
  32904. break;
  32905. default:
  32906. DUK_D(DUK_DPRINT("invalid heap type in decref: %ld", (long) DUK_HEAPHDR_GET_TYPE(h)));
  32907. DUK_UNREACHABLE();
  32908. }
  32909. }
  32910. #if !defined(DUK_USE_FAST_REFCOUNT_DEFAULT)
  32911. DUK_INTERNAL void duk_tval_incref(duk_tval *tv) {
  32912. DUK_ASSERT(tv != NULL);
  32913. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  32914. duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
  32915. DUK_ASSERT(h != NULL);
  32916. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32917. DUK_ASSERT_DISABLE(h->h_refcount >= 0);
  32918. DUK_HEAPHDR_PREINC_REFCOUNT(h);
  32919. }
  32920. }
  32921. #endif
  32922. #if 0 /* unused */
  32923. DUK_INTERNAL void duk_tval_incref_allownull(duk_tval *tv) {
  32924. if (tv == NULL) {
  32925. return;
  32926. }
  32927. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  32928. duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
  32929. DUK_ASSERT(h != NULL);
  32930. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32931. DUK_ASSERT_DISABLE(h->h_refcount >= 0);
  32932. DUK_HEAPHDR_PREINC_REFCOUNT(h);
  32933. }
  32934. }
  32935. #endif
  32936. DUK_INTERNAL void duk_tval_decref(duk_hthread *thr, duk_tval *tv) {
  32937. DUK_ASSERT(thr != NULL);
  32938. DUK_ASSERT(tv != NULL);
  32939. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  32940. duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
  32941. DUK_ASSERT(h != NULL);
  32942. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32943. duk_heaphdr_decref(thr, h);
  32944. }
  32945. }
  32946. #if 0 /* unused */
  32947. DUK_INTERNAL void duk_tval_decref_allownull(duk_hthread *thr, duk_tval *tv) {
  32948. DUK_ASSERT(thr != NULL);
  32949. if (tv == NULL) {
  32950. return;
  32951. }
  32952. if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
  32953. duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
  32954. DUK_ASSERT(h != NULL);
  32955. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32956. duk_heaphdr_decref(thr, h);
  32957. }
  32958. }
  32959. #endif
  32960. #if !defined(DUK_USE_FAST_REFCOUNT_DEFAULT)
  32961. DUK_INTERNAL void duk_heaphdr_incref(duk_heaphdr *h) {
  32962. DUK_ASSERT(h != NULL);
  32963. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32964. DUK_ASSERT_DISABLE(DUK_HEAPHDR_GET_REFCOUNT(h) >= 0);
  32965. DUK_HEAPHDR_PREINC_REFCOUNT(h);
  32966. }
  32967. #endif
  32968. #if 0 /* unused */
  32969. DUK_INTERNAL void duk_heaphdr_incref_allownull(duk_heaphdr *h) {
  32970. if (h == NULL) {
  32971. return;
  32972. }
  32973. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32974. DUK_ASSERT_DISABLE(DUK_HEAPHDR_GET_REFCOUNT(h) >= 0);
  32975. DUK_HEAPHDR_PREINC_REFCOUNT(h);
  32976. }
  32977. #endif
  32978. DUK_INTERNAL void duk_heaphdr_decref(duk_hthread *thr, duk_heaphdr *h) {
  32979. DUK_ASSERT(thr != NULL);
  32980. DUK_ASSERT(thr->heap != NULL);
  32981. DUK_ASSERT(h != NULL);
  32982. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32983. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(h) >= 1);
  32984. if (DUK_HEAPHDR_PREDEC_REFCOUNT(h) != 0) {
  32985. return;
  32986. }
  32987. duk_heaphdr_refzero(thr, h);
  32988. }
  32989. DUK_INTERNAL void duk_heaphdr_decref_allownull(duk_hthread *thr, duk_heaphdr *h) {
  32990. DUK_ASSERT(thr != NULL);
  32991. DUK_ASSERT(thr->heap != NULL);
  32992. if (h == NULL) {
  32993. return;
  32994. }
  32995. DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
  32996. DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(h) >= 1);
  32997. if (DUK_HEAPHDR_PREDEC_REFCOUNT(h) != 0) {
  32998. return;
  32999. }
  33000. duk_heaphdr_refzero(thr, h);
  33001. }
  33002. #else
  33003. /* no refcounting */
  33004. #endif /* DUK_USE_REFERENCE_COUNTING */
  33005. #line 1 "duk_heap_stringcache.c"
  33006. /*
  33007. * String cache.
  33008. *
  33009. * Provides a cache to optimize indexed string lookups. The cache keeps
  33010. * track of (byte offset, char offset) states for a fixed number of strings.
  33011. * Otherwise we'd need to scan from either end of the string, as we store
  33012. * strings in (extended) UTF-8.
  33013. */
  33014. /* include removed: duk_internal.h */
  33015. /*
  33016. * Delete references to given hstring from the heap string cache.
  33017. *
  33018. * String cache references are 'weak': they are not counted towards
  33019. * reference counts, nor serve as roots for mark-and-sweep. When an
  33020. * object is about to be freed, such references need to be removed.
  33021. */
  33022. DUK_INTERNAL void duk_heap_strcache_string_remove(duk_heap *heap, duk_hstring *h) {
  33023. duk_small_int_t i;
  33024. for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
  33025. duk_strcache *c = heap->strcache + i;
  33026. if (c->h == h) {
  33027. DUK_DD(DUK_DDPRINT("deleting weak strcache reference to hstring %p from heap %p",
  33028. (void *) h, (void *) heap));
  33029. c->h = NULL;
  33030. /* XXX: the string shouldn't appear twice, but we now loop to the
  33031. * end anyway; if fixed, add a looping assertion to ensure there
  33032. * is no duplicate.
  33033. */
  33034. }
  33035. }
  33036. }
  33037. /*
  33038. * String scanning helpers
  33039. */
  33040. DUK_LOCAL duk_uint8_t *duk__scan_forwards(duk_uint8_t *p, duk_uint8_t *q, duk_uint_fast32_t n) {
  33041. while (n > 0) {
  33042. for (;;) {
  33043. p++;
  33044. if (p >= q) {
  33045. return NULL;
  33046. }
  33047. if ((*p & 0xc0) != 0x80) {
  33048. break;
  33049. }
  33050. }
  33051. n--;
  33052. }
  33053. return p;
  33054. }
  33055. DUK_LOCAL duk_uint8_t *duk__scan_backwards(duk_uint8_t *p, duk_uint8_t *q, duk_uint_fast32_t n) {
  33056. while (n > 0) {
  33057. for (;;) {
  33058. p--;
  33059. if (p < q) {
  33060. return NULL;
  33061. }
  33062. if ((*p & 0xc0) != 0x80) {
  33063. break;
  33064. }
  33065. }
  33066. n--;
  33067. }
  33068. return p;
  33069. }
  33070. /*
  33071. * Convert char offset to byte offset
  33072. *
  33073. * Avoid using the string cache if possible: for ASCII strings byte and
  33074. * char offsets are equal and for short strings direct scanning may be
  33075. * better than using the string cache (which may evict a more important
  33076. * entry).
  33077. *
  33078. * Typing now assumes 32-bit string byte/char offsets (duk_uint_fast32_t).
  33079. * Better typing might be to use duk_size_t.
  33080. */
  33081. DUK_INTERNAL duk_uint_fast32_t duk_heap_strcache_offset_char2byte(duk_hthread *thr, duk_hstring *h, duk_uint_fast32_t char_offset) {
  33082. duk_heap *heap;
  33083. duk_strcache *sce;
  33084. duk_uint_fast32_t byte_offset;
  33085. duk_small_int_t i;
  33086. duk_bool_t use_cache;
  33087. duk_uint_fast32_t dist_start, dist_end, dist_sce;
  33088. duk_uint8_t *p_start;
  33089. duk_uint8_t *p_end;
  33090. duk_uint8_t *p_found;
  33091. if (char_offset > DUK_HSTRING_GET_CHARLEN(h)) {
  33092. goto error;
  33093. }
  33094. /*
  33095. * For ASCII strings, the answer is simple.
  33096. */
  33097. if (DUK_HSTRING_IS_ASCII(h)) {
  33098. /* clen == blen -> pure ascii */
  33099. return char_offset;
  33100. }
  33101. /*
  33102. * For non-ASCII strings, we need to scan forwards or backwards
  33103. * from some starting point. The starting point may be the start
  33104. * or end of the string, or some cached midpoint in the string
  33105. * cache.
  33106. *
  33107. * For "short" strings we simply scan without checking or updating
  33108. * the cache. For longer strings we check and update the cache as
  33109. * necessary, inserting a new cache entry if none exists.
  33110. */
  33111. DUK_DDD(DUK_DDDPRINT("non-ascii string %p, char_offset=%ld, clen=%ld, blen=%ld",
  33112. (void *) h, (long) char_offset,
  33113. (long) DUK_HSTRING_GET_CHARLEN(h),
  33114. (long) DUK_HSTRING_GET_BYTELEN(h)));
  33115. heap = thr->heap;
  33116. sce = NULL;
  33117. use_cache = (DUK_HSTRING_GET_CHARLEN(h) > DUK_HEAP_STRINGCACHE_NOCACHE_LIMIT);
  33118. if (use_cache) {
  33119. #ifdef DUK_USE_DDDPRINT
  33120. DUK_DDD(DUK_DDDPRINT("stringcache before char2byte (using cache):"));
  33121. for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
  33122. duk_strcache *c = heap->strcache + i;
  33123. DUK_DDD(DUK_DDDPRINT(" [%ld] -> h=%p, cidx=%ld, bidx=%ld",
  33124. (long) i, (void *) c->h, (long) c->cidx, (long) c->bidx));
  33125. }
  33126. #endif
  33127. for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
  33128. duk_strcache *c = heap->strcache + i;
  33129. if (c->h == h) {
  33130. sce = c;
  33131. break;
  33132. }
  33133. }
  33134. }
  33135. /*
  33136. * Scan from shortest distance:
  33137. * - start of string
  33138. * - end of string
  33139. * - cache entry (if exists)
  33140. */
  33141. DUK_ASSERT(DUK_HSTRING_GET_CHARLEN(h) >= char_offset);
  33142. dist_start = char_offset;
  33143. dist_end = DUK_HSTRING_GET_CHARLEN(h) - char_offset;
  33144. dist_sce = 0; DUK_UNREF(dist_sce); /* initialize for debug prints, needed if sce==NULL */
  33145. p_start = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h);
  33146. p_end = (duk_uint8_t *) (p_start + DUK_HSTRING_GET_BYTELEN(h));
  33147. p_found = NULL;
  33148. if (sce) {
  33149. if (char_offset >= sce->cidx) {
  33150. dist_sce = char_offset - sce->cidx;
  33151. if ((dist_sce <= dist_start) && (dist_sce <= dist_end)) {
  33152. DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
  33153. "dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
  33154. "scan forwards from sce",
  33155. (long) use_cache, (void *) (sce ? sce->h : NULL),
  33156. (sce ? (long) sce->cidx : (long) -1),
  33157. (sce ? (long) sce->bidx : (long) -1),
  33158. (long) dist_start, (long) dist_end, (long) dist_sce));
  33159. p_found = duk__scan_forwards(p_start + sce->bidx,
  33160. p_end,
  33161. dist_sce);
  33162. goto scan_done;
  33163. }
  33164. } else {
  33165. dist_sce = sce->cidx - char_offset;
  33166. if ((dist_sce <= dist_start) && (dist_sce <= dist_end)) {
  33167. DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
  33168. "dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
  33169. "scan backwards from sce",
  33170. (long) use_cache, (void *) (sce ? sce->h : NULL),
  33171. (sce ? (long) sce->cidx : (long) -1),
  33172. (sce ? (long) sce->bidx : (long) -1),
  33173. (long) dist_start, (long) dist_end, (long) dist_sce));
  33174. p_found = duk__scan_backwards(p_start + sce->bidx,
  33175. p_start,
  33176. dist_sce);
  33177. goto scan_done;
  33178. }
  33179. }
  33180. }
  33181. /* no sce, or sce scan not best */
  33182. if (dist_start <= dist_end) {
  33183. DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
  33184. "dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
  33185. "scan forwards from string start",
  33186. (long) use_cache, (void *) (sce ? sce->h : NULL),
  33187. (sce ? (long) sce->cidx : (long) -1),
  33188. (sce ? (long) sce->bidx : (long) -1),
  33189. (long) dist_start, (long) dist_end, (long) dist_sce));
  33190. p_found = duk__scan_forwards(p_start,
  33191. p_end,
  33192. dist_start);
  33193. } else {
  33194. DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
  33195. "dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
  33196. "scan backwards from string end",
  33197. (long) use_cache, (void *) (sce ? sce->h : NULL),
  33198. (sce ? (long) sce->cidx : (long) -1),
  33199. (sce ? (long) sce->bidx : (long) -1),
  33200. (long) dist_start, (long) dist_end, (long) dist_sce));
  33201. p_found = duk__scan_backwards(p_end,
  33202. p_start,
  33203. dist_end);
  33204. }
  33205. scan_done:
  33206. if (!p_found) {
  33207. /* Scan error: this shouldn't normally happen; it could happen if
  33208. * string is not valid UTF-8 data, and clen/blen are not consistent
  33209. * with the scanning algorithm.
  33210. */
  33211. goto error;
  33212. }
  33213. DUK_ASSERT(p_found >= p_start);
  33214. DUK_ASSERT(p_found <= p_end); /* may be equal */
  33215. byte_offset = (duk_uint32_t) (p_found - p_start);
  33216. DUK_DDD(DUK_DDDPRINT("-> string %p, cidx %ld -> bidx %ld",
  33217. (void *) h, (long) char_offset, (long) byte_offset));
  33218. /*
  33219. * Update cache entry (allocating if necessary), and move the
  33220. * cache entry to the first place (in an "LRU" policy).
  33221. */
  33222. if (use_cache) {
  33223. /* update entry, allocating if necessary */
  33224. if (!sce) {
  33225. sce = heap->strcache + DUK_HEAP_STRCACHE_SIZE - 1; /* take last entry */
  33226. sce->h = h;
  33227. }
  33228. DUK_ASSERT(sce != NULL);
  33229. sce->bidx = (duk_uint32_t) (p_found - p_start);
  33230. sce->cidx = (duk_uint32_t) char_offset;
  33231. /* LRU: move our entry to first */
  33232. if (sce > &heap->strcache[0]) {
  33233. /*
  33234. * A C
  33235. * B A
  33236. * C <- sce ==> B
  33237. * D D
  33238. */
  33239. duk_strcache tmp;
  33240. tmp = *sce;
  33241. DUK_MEMMOVE((void *) (&heap->strcache[1]),
  33242. (void *) (&heap->strcache[0]),
  33243. (size_t) (((char *) sce) - ((char *) &heap->strcache[0])));
  33244. heap->strcache[0] = tmp;
  33245. /* 'sce' points to the wrong entry here, but is no longer used */
  33246. }
  33247. #ifdef DUK_USE_DDDPRINT
  33248. DUK_DDD(DUK_DDDPRINT("stringcache after char2byte (using cache):"));
  33249. for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
  33250. duk_strcache *c = heap->strcache + i;
  33251. DUK_DDD(DUK_DDDPRINT(" [%ld] -> h=%p, cidx=%ld, bidx=%ld",
  33252. (long) i, (void *) c->h, (long) c->cidx, (long) c->bidx));
  33253. }
  33254. #endif
  33255. }
  33256. return byte_offset;
  33257. error:
  33258. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, "string scan error");
  33259. return 0;
  33260. }
  33261. #line 1 "duk_heap_stringtable.c"
  33262. /*
  33263. * Heap stringtable handling, string interning.
  33264. */
  33265. /* include removed: duk_internal.h */
  33266. #if defined(DUK_USE_STRTAB_PROBE)
  33267. #define DUK__HASH_INITIAL(hash,h_size) DUK_STRTAB_HASH_INITIAL((hash),(h_size))
  33268. #define DUK__HASH_PROBE_STEP(hash) DUK_STRTAB_HASH_PROBE_STEP((hash))
  33269. #define DUK__DELETED_MARKER(heap) DUK_STRTAB_DELETED_MARKER((heap))
  33270. #endif
  33271. /*
  33272. * Create a hstring and insert into the heap. The created object
  33273. * is directly garbage collectable with reference count zero.
  33274. *
  33275. * The caller must place the interned string into the stringtable
  33276. * immediately (without chance of a longjmp); otherwise the string
  33277. * is lost.
  33278. */
  33279. DUK_LOCAL
  33280. duk_hstring *duk__alloc_init_hstring(duk_heap *heap,
  33281. const duk_uint8_t *str,
  33282. duk_uint32_t blen,
  33283. duk_uint32_t strhash,
  33284. const duk_uint8_t *extdata) {
  33285. duk_hstring *res = NULL;
  33286. duk_uint8_t *data;
  33287. duk_size_t alloc_size;
  33288. duk_uarridx_t dummy;
  33289. duk_uint32_t clen;
  33290. #if defined(DUK_USE_STRLEN16)
  33291. /* If blen <= 0xffffUL, clen is also guaranteed to be <= 0xffffUL. */
  33292. if (blen > 0xffffUL) {
  33293. DUK_D(DUK_DPRINT("16-bit string blen/clen active and blen over 16 bits, reject intern"));
  33294. return NULL;
  33295. }
  33296. #endif
  33297. if (extdata) {
  33298. alloc_size = (duk_size_t) sizeof(duk_hstring_external);
  33299. res = (duk_hstring *) DUK_ALLOC(heap, alloc_size);
  33300. if (!res) {
  33301. goto alloc_error;
  33302. }
  33303. DUK_MEMZERO(res, sizeof(duk_hstring_external));
  33304. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  33305. DUK_HEAPHDR_STRING_INIT_NULLS(&res->hdr);
  33306. #endif
  33307. DUK_HEAPHDR_SET_TYPE_AND_FLAGS(&res->hdr, DUK_HTYPE_STRING, DUK_HSTRING_FLAG_EXTDATA);
  33308. ((duk_hstring_external *) res)->extdata = extdata;
  33309. } else {
  33310. /* NUL terminate for convenient C access */
  33311. alloc_size = (duk_size_t) (sizeof(duk_hstring) + blen + 1);
  33312. res = (duk_hstring *) DUK_ALLOC(heap, alloc_size);
  33313. if (!res) {
  33314. goto alloc_error;
  33315. }
  33316. DUK_MEMZERO(res, sizeof(duk_hstring));
  33317. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  33318. DUK_HEAPHDR_STRING_INIT_NULLS(&res->hdr);
  33319. #endif
  33320. DUK_HEAPHDR_SET_TYPE_AND_FLAGS(&res->hdr, DUK_HTYPE_STRING, 0);
  33321. data = (duk_uint8_t *) (res + 1);
  33322. DUK_MEMCPY(data, str, blen);
  33323. data[blen] = (duk_uint8_t) 0;
  33324. }
  33325. if (duk_js_to_arrayindex_raw_string(str, blen, &dummy)) {
  33326. DUK_HSTRING_SET_ARRIDX(res);
  33327. }
  33328. /* All strings beginning with 0xff are treated as "internal",
  33329. * even strings interned by the user. This allows user code to
  33330. * create internal properties too, and makes behavior consistent
  33331. * in case user code happens to use a string also used by Duktape
  33332. * (such as string has already been interned and has the 'internal'
  33333. * flag set).
  33334. */
  33335. if (blen > 0 && str[0] == (duk_uint8_t) 0xff) {
  33336. DUK_HSTRING_SET_INTERNAL(res);
  33337. }
  33338. DUK_HSTRING_SET_HASH(res, strhash);
  33339. DUK_HSTRING_SET_BYTELEN(res, blen);
  33340. clen = (duk_uint32_t) duk_unicode_unvalidated_utf8_length(str, (duk_size_t) blen);
  33341. DUK_ASSERT(clen <= blen);
  33342. DUK_HSTRING_SET_CHARLEN(res, clen);
  33343. DUK_DDD(DUK_DDDPRINT("interned string, hash=0x%08lx, blen=%ld, clen=%ld, has_arridx=%ld, has_extdata=%ld",
  33344. (unsigned long) DUK_HSTRING_GET_HASH(res),
  33345. (long) DUK_HSTRING_GET_BYTELEN(res),
  33346. (long) DUK_HSTRING_GET_CHARLEN(res),
  33347. (long) DUK_HSTRING_HAS_ARRIDX(res) ? 1 : 0,
  33348. (long) DUK_HSTRING_HAS_EXTDATA(res) ? 1 : 0));
  33349. return res;
  33350. alloc_error:
  33351. DUK_FREE(heap, res);
  33352. return NULL;
  33353. }
  33354. /*
  33355. * String table algorithm: fixed size string table with array chaining
  33356. *
  33357. * The top level string table has a fixed size, with each slot holding
  33358. * either NULL, string pointer, or pointer to a separately allocated
  33359. * string pointer list.
  33360. *
  33361. * This is good for low memory environments using a pool allocator: the
  33362. * top level allocation has a fixed size and the pointer lists have quite
  33363. * small allocation size, which further matches the typical pool sizes
  33364. * needed by objects, strings, property tables, etc.
  33365. */
  33366. #if defined(DUK_USE_STRTAB_CHAIN)
  33367. #if defined(DUK_USE_HEAPPTR16)
  33368. DUK_LOCAL duk_bool_t duk__insert_hstring_chain(duk_heap *heap, duk_hstring *h) {
  33369. duk_small_uint_t slotidx;
  33370. duk_strtab_entry *e;
  33371. duk_uint16_t *lst;
  33372. duk_uint16_t *new_lst;
  33373. duk_size_t i, n;
  33374. duk_uint16_t null16 = heap->heapptr_null16;
  33375. duk_uint16_t h16 = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) h);
  33376. DUK_ASSERT(heap != NULL);
  33377. DUK_ASSERT(h != NULL);
  33378. slotidx = DUK_HSTRING_GET_HASH(h) % DUK_STRTAB_CHAIN_SIZE;
  33379. DUK_ASSERT(slotidx < DUK_STRTAB_CHAIN_SIZE);
  33380. e = heap->strtable + slotidx;
  33381. if (e->listlen == 0) {
  33382. if (e->u.str16 == null16) {
  33383. e->u.str16 = h16;
  33384. } else {
  33385. /* Now two entries in the same slot, alloc list */
  33386. lst = (duk_uint16_t *) DUK_ALLOC(heap, sizeof(duk_uint16_t) * 2);
  33387. if (lst == NULL) {
  33388. return 1; /* fail */
  33389. }
  33390. lst[0] = e->u.str16;
  33391. lst[1] = h16;
  33392. e->u.strlist16 = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) lst);
  33393. e->listlen = 2;
  33394. }
  33395. } else {
  33396. DUK_ASSERT(e->u.strlist16 != null16);
  33397. lst = (duk_uint16_t *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.strlist16);
  33398. DUK_ASSERT(lst != NULL);
  33399. for (i = 0, n = e->listlen; i < n; i++) {
  33400. if (lst[i] == null16) {
  33401. lst[i] = h16;
  33402. return 0;
  33403. }
  33404. }
  33405. if (e->listlen + 1 == 0) {
  33406. /* Overflow, relevant mainly when listlen is 16 bits. */
  33407. return 1; /* fail */
  33408. }
  33409. new_lst = (duk_uint16_t *) DUK_REALLOC(heap, lst, sizeof(duk_uint16_t) * (e->listlen + 1));
  33410. if (new_lst == NULL) {
  33411. return 1; /* fail */
  33412. }
  33413. new_lst[e->listlen++] = h16;
  33414. e->u.strlist16 = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) new_lst);
  33415. }
  33416. return 0;
  33417. }
  33418. #else /* DUK_USE_HEAPPTR16 */
  33419. DUK_LOCAL duk_bool_t duk__insert_hstring_chain(duk_heap *heap, duk_hstring *h) {
  33420. duk_small_uint_t slotidx;
  33421. duk_strtab_entry *e;
  33422. duk_hstring **lst;
  33423. duk_hstring **new_lst;
  33424. duk_size_t i, n;
  33425. DUK_ASSERT(heap != NULL);
  33426. DUK_ASSERT(h != NULL);
  33427. slotidx = DUK_HSTRING_GET_HASH(h) % DUK_STRTAB_CHAIN_SIZE;
  33428. DUK_ASSERT(slotidx < DUK_STRTAB_CHAIN_SIZE);
  33429. e = heap->strtable + slotidx;
  33430. if (e->listlen == 0) {
  33431. if (e->u.str == NULL) {
  33432. e->u.str = h;
  33433. } else {
  33434. /* Now two entries in the same slot, alloc list */
  33435. lst = (duk_hstring **) DUK_ALLOC(heap, sizeof(duk_hstring *) * 2);
  33436. if (lst == NULL) {
  33437. return 1; /* fail */
  33438. }
  33439. lst[0] = e->u.str;
  33440. lst[1] = h;
  33441. e->u.strlist = lst;
  33442. e->listlen = 2;
  33443. }
  33444. } else {
  33445. DUK_ASSERT(e->u.strlist != NULL);
  33446. lst = e->u.strlist;
  33447. for (i = 0, n = e->listlen; i < n; i++) {
  33448. if (lst[i] == NULL) {
  33449. lst[i] = h;
  33450. return 0;
  33451. }
  33452. }
  33453. if (e->listlen + 1 == 0) {
  33454. /* Overflow, relevant mainly when listlen is 16 bits. */
  33455. return 1; /* fail */
  33456. }
  33457. new_lst = (duk_hstring **) DUK_REALLOC(heap, e->u.strlist, sizeof(duk_hstring *) * (e->listlen + 1));
  33458. if (new_lst == NULL) {
  33459. return 1; /* fail */
  33460. }
  33461. new_lst[e->listlen++] = h;
  33462. e->u.strlist = new_lst;
  33463. }
  33464. return 0;
  33465. }
  33466. #endif /* DUK_USE_HEAPPTR16 */
  33467. #if defined(DUK_USE_HEAPPTR16)
  33468. DUK_LOCAL duk_hstring *duk__find_matching_string_chain(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen, duk_uint32_t strhash) {
  33469. duk_small_uint_t slotidx;
  33470. duk_strtab_entry *e;
  33471. duk_uint16_t *lst;
  33472. duk_size_t i, n;
  33473. duk_uint16_t null16 = heap->heapptr_null16;
  33474. DUK_ASSERT(heap != NULL);
  33475. slotidx = strhash % DUK_STRTAB_CHAIN_SIZE;
  33476. DUK_ASSERT(slotidx < DUK_STRTAB_CHAIN_SIZE);
  33477. e = heap->strtable + slotidx;
  33478. if (e->listlen == 0) {
  33479. if (e->u.str16 != null16) {
  33480. duk_hstring *h = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.str16);
  33481. DUK_ASSERT(h != NULL);
  33482. if (DUK_HSTRING_GET_BYTELEN(h) == blen &&
  33483. DUK_MEMCMP(str, DUK_HSTRING_GET_DATA(h), blen) == 0) {
  33484. return h;
  33485. }
  33486. }
  33487. } else {
  33488. DUK_ASSERT(e->u.strlist16 != null16);
  33489. lst = (duk_uint16_t *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.strlist16);
  33490. DUK_ASSERT(lst != NULL);
  33491. for (i = 0, n = e->listlen; i < n; i++) {
  33492. if (lst[i] != null16) {
  33493. duk_hstring *h = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, lst[i]);
  33494. DUK_ASSERT(h != NULL);
  33495. if (DUK_HSTRING_GET_BYTELEN(h) == blen &&
  33496. DUK_MEMCMP(str, DUK_HSTRING_GET_DATA(h), blen) == 0) {
  33497. return h;
  33498. }
  33499. }
  33500. }
  33501. }
  33502. return NULL;
  33503. }
  33504. #else /* DUK_USE_HEAPPTR16 */
  33505. DUK_LOCAL duk_hstring *duk__find_matching_string_chain(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen, duk_uint32_t strhash) {
  33506. duk_small_uint_t slotidx;
  33507. duk_strtab_entry *e;
  33508. duk_hstring **lst;
  33509. duk_size_t i, n;
  33510. DUK_ASSERT(heap != NULL);
  33511. slotidx = strhash % DUK_STRTAB_CHAIN_SIZE;
  33512. DUK_ASSERT(slotidx < DUK_STRTAB_CHAIN_SIZE);
  33513. e = heap->strtable + slotidx;
  33514. if (e->listlen == 0) {
  33515. if (e->u.str != NULL &&
  33516. DUK_HSTRING_GET_BYTELEN(e->u.str) == blen &&
  33517. DUK_MEMCMP(str, DUK_HSTRING_GET_DATA(e->u.str), blen) == 0) {
  33518. return e->u.str;
  33519. }
  33520. } else {
  33521. DUK_ASSERT(e->u.strlist != NULL);
  33522. lst = e->u.strlist;
  33523. for (i = 0, n = e->listlen; i < n; i++) {
  33524. if (lst[i] != NULL &&
  33525. DUK_HSTRING_GET_BYTELEN(lst[i]) == blen &&
  33526. DUK_MEMCMP(str, DUK_HSTRING_GET_DATA(lst[i]), blen) == 0) {
  33527. return lst[i];
  33528. }
  33529. }
  33530. }
  33531. return NULL;
  33532. }
  33533. #endif /* DUK_USE_HEAPPTR16 */
  33534. #if defined(DUK_USE_HEAPPTR16)
  33535. DUK_LOCAL void duk__remove_matching_hstring_chain(duk_heap *heap, duk_hstring *h) {
  33536. duk_small_uint_t slotidx;
  33537. duk_strtab_entry *e;
  33538. duk_uint16_t *lst;
  33539. duk_size_t i, n;
  33540. duk_uint16_t h16;
  33541. duk_uint16_t null16 = heap->heapptr_null16;
  33542. DUK_ASSERT(heap != NULL);
  33543. DUK_ASSERT(h != NULL);
  33544. slotidx = DUK_HSTRING_GET_HASH(h) % DUK_STRTAB_CHAIN_SIZE;
  33545. DUK_ASSERT(slotidx < DUK_STRTAB_CHAIN_SIZE);
  33546. DUK_ASSERT(h != NULL);
  33547. h16 = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) h);
  33548. e = heap->strtable + slotidx;
  33549. if (e->listlen == 0) {
  33550. if (e->u.str16 == h16) {
  33551. e->u.str16 = null16;
  33552. return;
  33553. }
  33554. } else {
  33555. DUK_ASSERT(e->u.strlist16 != null16);
  33556. lst = (duk_uint16_t *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.strlist16);
  33557. DUK_ASSERT(lst != NULL);
  33558. for (i = 0, n = e->listlen; i < n; i++) {
  33559. if (lst[i] == h16) {
  33560. lst[i] = null16;
  33561. return;
  33562. }
  33563. }
  33564. }
  33565. DUK_D(DUK_DPRINT("failed to find string that should be in stringtable"));
  33566. DUK_UNREACHABLE();
  33567. return;
  33568. }
  33569. #else /* DUK_USE_HEAPPTR16 */
  33570. DUK_LOCAL void duk__remove_matching_hstring_chain(duk_heap *heap, duk_hstring *h) {
  33571. duk_small_uint_t slotidx;
  33572. duk_strtab_entry *e;
  33573. duk_hstring **lst;
  33574. duk_size_t i, n;
  33575. DUK_ASSERT(heap != NULL);
  33576. DUK_ASSERT(h != NULL);
  33577. slotidx = DUK_HSTRING_GET_HASH(h) % DUK_STRTAB_CHAIN_SIZE;
  33578. DUK_ASSERT(slotidx < DUK_STRTAB_CHAIN_SIZE);
  33579. e = heap->strtable + slotidx;
  33580. if (e->listlen == 0) {
  33581. DUK_ASSERT(h != NULL);
  33582. if (e->u.str == h) {
  33583. e->u.str = NULL;
  33584. return;
  33585. }
  33586. } else {
  33587. DUK_ASSERT(e->u.strlist != NULL);
  33588. lst = e->u.strlist;
  33589. for (i = 0, n = e->listlen; i < n; i++) {
  33590. DUK_ASSERT(h != NULL);
  33591. if (lst[i] == h) {
  33592. lst[i] = NULL;
  33593. return;
  33594. }
  33595. }
  33596. }
  33597. DUK_D(DUK_DPRINT("failed to find string that should be in stringtable"));
  33598. DUK_UNREACHABLE();
  33599. return;
  33600. }
  33601. #endif /* DUK_USE_HEAPPTR16 */
  33602. #if defined(DUK_USE_DEBUG)
  33603. DUK_INTERNAL void duk_heap_dump_strtab(duk_heap *heap) {
  33604. duk_strtab_entry *e;
  33605. duk_small_uint_t i;
  33606. duk_size_t j, n, used;
  33607. #if defined(DUK_USE_HEAPPTR16)
  33608. duk_uint16_t *lst;
  33609. duk_uint16_t null16 = heap->heapptr_null16;
  33610. #else
  33611. duk_hstring **lst;
  33612. #endif
  33613. DUK_ASSERT(heap != NULL);
  33614. for (i = 0; i < DUK_STRTAB_CHAIN_SIZE; i++) {
  33615. e = heap->strtable + i;
  33616. if (e->listlen == 0) {
  33617. #if defined(DUK_USE_HEAPPTR16)
  33618. DUK_DD(DUK_DDPRINT("[%03d] -> plain %d", (int) i, (int) (e->u.str16 != null16 ? 1 : 0)));
  33619. #else
  33620. DUK_DD(DUK_DDPRINT("[%03d] -> plain %d", (int) i, (int) (e->u.str ? 1 : 0)));
  33621. #endif
  33622. } else {
  33623. used = 0;
  33624. #if defined(DUK_USE_HEAPPTR16)
  33625. lst = (duk_uint16_t *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.strlist16);
  33626. #else
  33627. lst = e->u.strlist;
  33628. #endif
  33629. DUK_ASSERT(lst != NULL);
  33630. for (j = 0, n = e->listlen; j < n; j++) {
  33631. #if defined(DUK_USE_HEAPPTR16)
  33632. if (lst[j] != null16) {
  33633. #else
  33634. if (lst[j] != NULL) {
  33635. #endif
  33636. used++;
  33637. }
  33638. }
  33639. DUK_DD(DUK_DDPRINT("[%03d] -> array %d/%d", (int) i, (int) used, (int) e->listlen));
  33640. }
  33641. }
  33642. }
  33643. #endif /* DUK_USE_DEBUG */
  33644. #endif /* DUK_USE_STRTAB_CHAIN */
  33645. /*
  33646. * String table algorithm: closed hashing with a probe sequence
  33647. *
  33648. * This is the default algorithm and works fine for environments with
  33649. * minimal memory constraints.
  33650. */
  33651. #if defined(DUK_USE_STRTAB_PROBE)
  33652. /* Count actually used (non-NULL, non-DELETED) entries. */
  33653. DUK_LOCAL duk_int_t duk__count_used_probe(duk_heap *heap) {
  33654. duk_int_t res = 0;
  33655. duk_uint_fast32_t i, n;
  33656. #if defined(DUK_USE_HEAPPTR16)
  33657. duk_uint16_t null16 = heap->heapptr_null16;
  33658. duk_uint16_t deleted16 = heap->heapptr_deleted16;
  33659. #endif
  33660. n = (duk_uint_fast32_t) heap->st_size;
  33661. for (i = 0; i < n; i++) {
  33662. #if defined(DUK_USE_HEAPPTR16)
  33663. if (heap->strtable16[i] != null16 && heap->strtable16[i] != deleted16) {
  33664. #else
  33665. if (heap->strtable[i] != NULL && heap->strtable[i] != DUK__DELETED_MARKER(heap)) {
  33666. #endif
  33667. res++;
  33668. }
  33669. }
  33670. return res;
  33671. }
  33672. #if defined(DUK_USE_HEAPPTR16)
  33673. DUK_LOCAL void duk__insert_hstring_probe(duk_heap *heap, duk_uint16_t *entries16, duk_uint32_t size, duk_uint32_t *p_used, duk_hstring *h) {
  33674. #else
  33675. DUK_LOCAL void duk__insert_hstring_probe(duk_heap *heap, duk_hstring **entries, duk_uint32_t size, duk_uint32_t *p_used, duk_hstring *h) {
  33676. #endif
  33677. duk_uint32_t i;
  33678. duk_uint32_t step;
  33679. #if defined(DUK_USE_HEAPPTR16)
  33680. duk_uint16_t null16 = heap->heapptr_null16;
  33681. duk_uint16_t deleted16 = heap->heapptr_deleted16;
  33682. #endif
  33683. DUK_ASSERT(size > 0);
  33684. i = DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(h), size);
  33685. step = DUK__HASH_PROBE_STEP(DUK_HSTRING_GET_HASH(h));
  33686. for (;;) {
  33687. #if defined(DUK_USE_HEAPPTR16)
  33688. duk_uint16_t e16 = entries16[i];
  33689. #else
  33690. duk_hstring *e = entries[i];
  33691. #endif
  33692. #if defined(DUK_USE_HEAPPTR16)
  33693. /* XXX: could check for e16 == 0 because NULL is guaranteed to
  33694. * encode to zero.
  33695. */
  33696. if (e16 == null16) {
  33697. #else
  33698. if (e == NULL) {
  33699. #endif
  33700. DUK_DDD(DUK_DDDPRINT("insert hit (null): %ld", (long) i));
  33701. #if defined(DUK_USE_HEAPPTR16)
  33702. entries16[i] = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) h);
  33703. #else
  33704. entries[i] = h;
  33705. #endif
  33706. (*p_used)++;
  33707. break;
  33708. #if defined(DUK_USE_HEAPPTR16)
  33709. } else if (e16 == deleted16) {
  33710. #else
  33711. } else if (e == DUK__DELETED_MARKER(heap)) {
  33712. #endif
  33713. /* st_used remains the same, DELETED is counted as used */
  33714. DUK_DDD(DUK_DDDPRINT("insert hit (deleted): %ld", (long) i));
  33715. #if defined(DUK_USE_HEAPPTR16)
  33716. entries16[i] = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) h);
  33717. #else
  33718. entries[i] = h;
  33719. #endif
  33720. break;
  33721. }
  33722. DUK_DDD(DUK_DDDPRINT("insert miss: %ld", (long) i));
  33723. i = (i + step) % size;
  33724. /* looping should never happen */
  33725. DUK_ASSERT(i != DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(h), size));
  33726. }
  33727. }
  33728. #if defined(DUK_USE_HEAPPTR16)
  33729. DUK_LOCAL duk_hstring *duk__find_matching_string_probe(duk_heap *heap, duk_uint16_t *entries16, duk_uint32_t size, const duk_uint8_t *str, duk_uint32_t blen, duk_uint32_t strhash) {
  33730. #else
  33731. DUK_LOCAL duk_hstring *duk__find_matching_string_probe(duk_heap *heap, duk_hstring **entries, duk_uint32_t size, const duk_uint8_t *str, duk_uint32_t blen, duk_uint32_t strhash) {
  33732. #endif
  33733. duk_uint32_t i;
  33734. duk_uint32_t step;
  33735. DUK_ASSERT(size > 0);
  33736. i = DUK__HASH_INITIAL(strhash, size);
  33737. step = DUK__HASH_PROBE_STEP(strhash);
  33738. for (;;) {
  33739. duk_hstring *e;
  33740. #if defined(DUK_USE_HEAPPTR16)
  33741. e = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, entries16[i]);
  33742. #else
  33743. e = entries[i];
  33744. #endif
  33745. if (!e) {
  33746. return NULL;
  33747. }
  33748. if (e != DUK__DELETED_MARKER(heap) && DUK_HSTRING_GET_BYTELEN(e) == blen) {
  33749. if (DUK_MEMCMP(str, DUK_HSTRING_GET_DATA(e), blen) == 0) {
  33750. DUK_DDD(DUK_DDDPRINT("find matching hit: %ld (step %ld, size %ld)",
  33751. (long) i, (long) step, (long) size));
  33752. return e;
  33753. }
  33754. }
  33755. DUK_DDD(DUK_DDDPRINT("find matching miss: %ld (step %ld, size %ld)",
  33756. (long) i, (long) step, (long) size));
  33757. i = (i + step) % size;
  33758. /* looping should never happen */
  33759. DUK_ASSERT(i != DUK__HASH_INITIAL(strhash, size));
  33760. }
  33761. DUK_UNREACHABLE();
  33762. }
  33763. #if defined(DUK_USE_HEAPPTR16)
  33764. DUK_LOCAL void duk__remove_matching_hstring_probe(duk_heap *heap, duk_uint16_t *entries16, duk_uint32_t size, duk_hstring *h) {
  33765. #else
  33766. DUK_LOCAL void duk__remove_matching_hstring_probe(duk_heap *heap, duk_hstring **entries, duk_uint32_t size, duk_hstring *h) {
  33767. #endif
  33768. duk_uint32_t i;
  33769. duk_uint32_t step;
  33770. duk_uint32_t hash;
  33771. #if defined(DUK_USE_HEAPPTR16)
  33772. duk_uint16_t null16 = heap->heapptr_null16;
  33773. duk_uint16_t h16 = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) h);
  33774. #endif
  33775. DUK_ASSERT(size > 0);
  33776. hash = DUK_HSTRING_GET_HASH(h);
  33777. i = DUK__HASH_INITIAL(hash, size);
  33778. step = DUK__HASH_PROBE_STEP(hash);
  33779. for (;;) {
  33780. #if defined(DUK_USE_HEAPPTR16)
  33781. duk_uint16_t e16 = entries16[i];
  33782. #else
  33783. duk_hstring *e = entries[i];
  33784. #endif
  33785. #if defined(DUK_USE_HEAPPTR16)
  33786. if (e16 == null16) {
  33787. #else
  33788. if (!e) {
  33789. #endif
  33790. DUK_UNREACHABLE();
  33791. break;
  33792. }
  33793. #if defined(DUK_USE_HEAPPTR16)
  33794. if (e16 == h16) {
  33795. #else
  33796. if (e == h) {
  33797. #endif
  33798. /* st_used remains the same, DELETED is counted as used */
  33799. DUK_DDD(DUK_DDDPRINT("free matching hit: %ld", (long) i));
  33800. #if defined(DUK_USE_HEAPPTR16)
  33801. entries16[i] = heap->heapptr_deleted16;
  33802. #else
  33803. entries[i] = DUK__DELETED_MARKER(heap);
  33804. #endif
  33805. break;
  33806. }
  33807. DUK_DDD(DUK_DDDPRINT("free matching miss: %ld", (long) i));
  33808. i = (i + step) % size;
  33809. /* looping should never happen */
  33810. DUK_ASSERT(i != DUK__HASH_INITIAL(hash, size));
  33811. }
  33812. }
  33813. DUK_LOCAL duk_bool_t duk__resize_strtab_raw_probe(duk_heap *heap, duk_uint32_t new_size) {
  33814. #ifdef DUK_USE_MARK_AND_SWEEP
  33815. duk_small_uint_t prev_mark_and_sweep_base_flags;
  33816. #endif
  33817. #ifdef DUK_USE_DEBUG
  33818. duk_uint32_t old_used = heap->st_used;
  33819. #endif
  33820. duk_uint32_t old_size = heap->st_size;
  33821. #if defined(DUK_USE_HEAPPTR16)
  33822. duk_uint16_t *old_entries = heap->strtable16;
  33823. duk_uint16_t *new_entries = NULL;
  33824. #else
  33825. duk_hstring **old_entries = heap->strtable;
  33826. duk_hstring **new_entries = NULL;
  33827. #endif
  33828. duk_uint32_t new_used = 0;
  33829. duk_uint32_t i;
  33830. #ifdef DUK_USE_DEBUG
  33831. DUK_UNREF(old_used); /* unused with some debug level combinations */
  33832. #endif
  33833. #ifdef DUK_USE_DDDPRINT
  33834. DUK_DDD(DUK_DDDPRINT("attempt to resize stringtable: %ld entries, %ld bytes, %ld used, %ld%% load -> %ld entries, %ld bytes, %ld used, %ld%% load",
  33835. (long) old_size, (long) (sizeof(duk_hstring *) * old_size), (long) old_used,
  33836. (long) (((double) old_used) / ((double) old_size) * 100.0),
  33837. (long) new_size, (long) (sizeof(duk_hstring *) * new_size), (long) duk__count_used_probe(heap),
  33838. (long) (((double) duk__count_used_probe(heap)) / ((double) new_size) * 100.0)));
  33839. #endif
  33840. DUK_ASSERT(new_size > (duk_uint32_t) duk__count_used_probe(heap)); /* required for rehash to succeed, equality not that useful */
  33841. DUK_ASSERT(old_entries);
  33842. #ifdef DUK_USE_MARK_AND_SWEEP
  33843. DUK_ASSERT((heap->mark_and_sweep_base_flags & DUK_MS_FLAG_NO_STRINGTABLE_RESIZE) == 0);
  33844. #endif
  33845. /*
  33846. * The attempt to allocate may cause a GC. Such a GC must not attempt to resize
  33847. * the stringtable (though it can be swept); finalizer execution and object
  33848. * compaction must also be postponed to avoid the pressure to add strings to the
  33849. * string table.
  33850. */
  33851. #ifdef DUK_USE_MARK_AND_SWEEP
  33852. prev_mark_and_sweep_base_flags = heap->mark_and_sweep_base_flags;
  33853. heap->mark_and_sweep_base_flags |= \
  33854. DUK_MS_FLAG_NO_STRINGTABLE_RESIZE | /* avoid recursive call here */
  33855. DUK_MS_FLAG_NO_FINALIZERS | /* avoid pressure to add/remove strings */
  33856. DUK_MS_FLAG_NO_OBJECT_COMPACTION; /* avoid array abandoning which interns strings */
  33857. #endif
  33858. #if defined(DUK_USE_HEAPPTR16)
  33859. new_entries = (duk_uint16_t *) DUK_ALLOC(heap, sizeof(duk_uint16_t) * new_size);
  33860. #else
  33861. new_entries = (duk_hstring **) DUK_ALLOC(heap, sizeof(duk_hstring *) * new_size);
  33862. #endif
  33863. #ifdef DUK_USE_MARK_AND_SWEEP
  33864. heap->mark_and_sweep_base_flags = prev_mark_and_sweep_base_flags;
  33865. #endif
  33866. if (!new_entries) {
  33867. goto resize_error;
  33868. }
  33869. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  33870. for (i = 0; i < new_size; i++) {
  33871. #if defined(DUK_USE_HEAPPTR16)
  33872. new_entries[i] = heap->heapptr_null16;
  33873. #else
  33874. new_entries[i] = NULL;
  33875. #endif
  33876. }
  33877. #else
  33878. #if defined(DUK_USE_HEAPPTR16)
  33879. /* Relies on NULL encoding to zero. */
  33880. DUK_MEMZERO(new_entries, sizeof(duk_uint16_t) * new_size);
  33881. #else
  33882. DUK_MEMZERO(new_entries, sizeof(duk_hstring *) * new_size);
  33883. #endif
  33884. #endif
  33885. /* Because new_size > duk__count_used_probe(heap), guaranteed to work */
  33886. for (i = 0; i < old_size; i++) {
  33887. duk_hstring *e;
  33888. #if defined(DUK_USE_HEAPPTR16)
  33889. e = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, old_entries[i]);
  33890. #else
  33891. e = old_entries[i];
  33892. #endif
  33893. if (e == NULL || e == DUK__DELETED_MARKER(heap)) {
  33894. continue;
  33895. }
  33896. /* checking for DUK__DELETED_MARKER is not necessary here, but helper does it now */
  33897. duk__insert_hstring_probe(heap, new_entries, new_size, &new_used, e);
  33898. }
  33899. #ifdef DUK_USE_DDPRINT
  33900. DUK_DD(DUK_DDPRINT("resized stringtable: %ld entries, %ld bytes, %ld used, %ld%% load -> %ld entries, %ld bytes, %ld used, %ld%% load",
  33901. (long) old_size, (long) (sizeof(duk_hstring *) * old_size), (long) old_used,
  33902. (long) (((double) old_used) / ((double) old_size) * 100.0),
  33903. (long) new_size, (long) (sizeof(duk_hstring *) * new_size), (long) new_used,
  33904. (long) (((double) new_used) / ((double) new_size) * 100.0)));
  33905. #endif
  33906. #if defined(DUK_USE_HEAPPTR16)
  33907. DUK_FREE(heap, heap->strtable16);
  33908. heap->strtable16 = new_entries;
  33909. #else
  33910. DUK_FREE(heap, heap->strtable);
  33911. heap->strtable = new_entries;
  33912. #endif
  33913. heap->st_size = new_size;
  33914. heap->st_used = new_used; /* may be less, since DELETED entries are NULLed by rehash */
  33915. return 0; /* OK */
  33916. resize_error:
  33917. DUK_FREE(heap, new_entries);
  33918. return 1; /* FAIL */
  33919. }
  33920. DUK_LOCAL duk_bool_t duk__resize_strtab_probe(duk_heap *heap) {
  33921. duk_uint32_t new_size;
  33922. duk_bool_t ret;
  33923. new_size = (duk_uint32_t) duk__count_used_probe(heap);
  33924. if (new_size >= 0x80000000UL) {
  33925. new_size = DUK_STRTAB_HIGHEST_32BIT_PRIME;
  33926. } else {
  33927. new_size = duk_util_get_hash_prime(DUK_STRTAB_GROW_ST_SIZE(new_size));
  33928. new_size = duk_util_get_hash_prime(new_size);
  33929. }
  33930. DUK_ASSERT(new_size > 0);
  33931. /* rehash even if old and new sizes are the same to get rid of
  33932. * DELETED entries.
  33933. */
  33934. ret = duk__resize_strtab_raw_probe(heap, new_size);
  33935. return ret;
  33936. }
  33937. DUK_LOCAL duk_bool_t duk__recheck_strtab_size_probe(duk_heap *heap, duk_uint32_t new_used) {
  33938. duk_uint32_t new_free;
  33939. duk_uint32_t tmp1;
  33940. duk_uint32_t tmp2;
  33941. DUK_ASSERT(new_used <= heap->st_size); /* grow by at most one */
  33942. new_free = heap->st_size - new_used; /* unsigned intentionally */
  33943. /* new_free / size <= 1 / DIV <=> new_free <= size / DIV */
  33944. /* new_used / size <= 1 / DIV <=> new_used <= size / DIV */
  33945. tmp1 = heap->st_size / DUK_STRTAB_MIN_FREE_DIVISOR;
  33946. tmp2 = heap->st_size / DUK_STRTAB_MIN_USED_DIVISOR;
  33947. if (new_free <= tmp1 || new_used <= tmp2) {
  33948. /* load factor too low or high, count actually used entries and resize */
  33949. return duk__resize_strtab_probe(heap);
  33950. } else {
  33951. return 0; /* OK */
  33952. }
  33953. }
  33954. #if defined(DUK_USE_DEBUG)
  33955. DUK_INTERNAL void duk_heap_dump_strtab(duk_heap *heap) {
  33956. duk_uint32_t i;
  33957. duk_hstring *h;
  33958. DUK_ASSERT(heap != NULL);
  33959. #if defined(DUK_USE_HEAPPTR16)
  33960. DUK_ASSERT(heap->strtable16 != NULL);
  33961. #else
  33962. DUK_ASSERT(heap->strtable != NULL);
  33963. #endif
  33964. DUK_UNREF(h);
  33965. for (i = 0; i < heap->st_size; i++) {
  33966. #if defined(DUK_USE_HEAPPTR16)
  33967. h = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->strtable16[i]);
  33968. #else
  33969. h = heap->strtable[i];
  33970. #endif
  33971. DUK_DD(DUK_DDPRINT("[%03d] -> %p", (int) i, (void *) h));
  33972. }
  33973. }
  33974. #endif /* DUK_USE_DEBUG */
  33975. #endif /* DUK_USE_STRTAB_PROBE */
  33976. /*
  33977. * Raw intern and lookup
  33978. */
  33979. DUK_LOCAL duk_hstring *duk__do_intern(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen, duk_uint32_t strhash) {
  33980. duk_hstring *res;
  33981. const duk_uint8_t *extdata;
  33982. #if defined(DUK_USE_STRTAB_PROBE)
  33983. if (duk__recheck_strtab_size_probe(heap, heap->st_used + 1)) {
  33984. return NULL;
  33985. }
  33986. #endif
  33987. /* For manual testing only. */
  33988. #if 0
  33989. {
  33990. duk_size_t i;
  33991. DUK_PRINTF("INTERN: \"");
  33992. for (i = 0; i < blen; i++) {
  33993. duk_uint8_t x = str[i];
  33994. if (x >= 0x20 && x <= 0x7e && x != '"' && x != '\\') {
  33995. DUK_PRINTF("%c", (int) x); /* char: use int cast */
  33996. } else {
  33997. DUK_PRINTF("\\x%02lx", (long) x);
  33998. }
  33999. }
  34000. DUK_PRINTF("\"\n");
  34001. }
  34002. #endif
  34003. #if defined(DUK_USE_HSTRING_EXTDATA) && defined(DUK_USE_EXTSTR_INTERN_CHECK)
  34004. extdata = (const duk_uint8_t *) DUK_USE_EXTSTR_INTERN_CHECK(heap->heap_udata, (void *) str, (duk_size_t) blen);
  34005. #else
  34006. extdata = (const duk_uint8_t *) NULL;
  34007. #endif
  34008. res = duk__alloc_init_hstring(heap, str, blen, strhash, extdata);
  34009. if (!res) {
  34010. return NULL;
  34011. }
  34012. #if defined(DUK_USE_STRTAB_CHAIN)
  34013. if (duk__insert_hstring_chain(heap, res)) {
  34014. /* failed */
  34015. DUK_FREE(heap, res);
  34016. return NULL;
  34017. }
  34018. #elif defined(DUK_USE_STRTAB_PROBE)
  34019. /* guaranteed to succeed */
  34020. duk__insert_hstring_probe(heap,
  34021. #if defined(DUK_USE_HEAPPTR16)
  34022. heap->strtable16,
  34023. #else
  34024. heap->strtable,
  34025. #endif
  34026. heap->st_size,
  34027. &heap->st_used,
  34028. res);
  34029. #else
  34030. #error internal error, invalid strtab options
  34031. #endif
  34032. /* Note: hstring is in heap but has refcount zero and is not strongly reachable.
  34033. * Caller should increase refcount and make the hstring reachable before any
  34034. * operations which require allocation (and possible gc).
  34035. */
  34036. return res;
  34037. }
  34038. DUK_LOCAL duk_hstring *duk__do_lookup(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen, duk_uint32_t *out_strhash) {
  34039. duk_hstring *res;
  34040. DUK_ASSERT(out_strhash);
  34041. *out_strhash = duk_heap_hashstring(heap, str, (duk_size_t) blen);
  34042. #if defined(DUK_USE_STRTAB_CHAIN)
  34043. res = duk__find_matching_string_chain(heap, str, blen, *out_strhash);
  34044. #elif defined(DUK_USE_STRTAB_PROBE)
  34045. res = duk__find_matching_string_probe(heap,
  34046. #if defined(DUK_USE_HEAPPTR16)
  34047. heap->strtable16,
  34048. #else
  34049. heap->strtable,
  34050. #endif
  34051. heap->st_size,
  34052. str,
  34053. blen,
  34054. *out_strhash);
  34055. #else
  34056. #error internal error, invalid strtab options
  34057. #endif
  34058. return res;
  34059. }
  34060. /*
  34061. * Exposed calls
  34062. */
  34063. #if 0 /*unused*/
  34064. DUK_INTERNAL duk_hstring *duk_heap_string_lookup(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen) {
  34065. duk_uint32_t strhash; /* dummy */
  34066. return duk__do_lookup(heap, str, blen, &strhash);
  34067. }
  34068. #endif
  34069. DUK_INTERNAL duk_hstring *duk_heap_string_intern(duk_heap *heap, const duk_uint8_t *str, duk_uint32_t blen) {
  34070. duk_hstring *res;
  34071. duk_uint32_t strhash;
  34072. /* caller is responsible for ensuring this */
  34073. DUK_ASSERT(blen <= DUK_HSTRING_MAX_BYTELEN);
  34074. res = duk__do_lookup(heap, str, blen, &strhash);
  34075. if (res) {
  34076. return res;
  34077. }
  34078. res = duk__do_intern(heap, str, blen, strhash);
  34079. return res; /* may be NULL */
  34080. }
  34081. DUK_INTERNAL duk_hstring *duk_heap_string_intern_checked(duk_hthread *thr, const duk_uint8_t *str, duk_uint32_t blen) {
  34082. duk_hstring *res = duk_heap_string_intern(thr->heap, str, blen);
  34083. if (!res) {
  34084. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, "failed to intern string");
  34085. }
  34086. return res;
  34087. }
  34088. #if 0 /*unused*/
  34089. DUK_INTERNAL duk_hstring *duk_heap_string_lookup_u32(duk_heap *heap, duk_uint32_t val) {
  34090. char buf[DUK_STRTAB_U32_MAX_STRLEN+1];
  34091. DUK_SNPRINTF(buf, sizeof(buf), "%lu", (unsigned long) val);
  34092. buf[sizeof(buf) - 1] = (char) 0;
  34093. DUK_ASSERT(DUK_STRLEN(buf) <= DUK_UINT32_MAX); /* formatted result limited */
  34094. return duk_heap_string_lookup(heap, (const duk_uint8_t *) buf, (duk_uint32_t) DUK_STRLEN(buf));
  34095. }
  34096. #endif
  34097. DUK_INTERNAL duk_hstring *duk_heap_string_intern_u32(duk_heap *heap, duk_uint32_t val) {
  34098. char buf[DUK_STRTAB_U32_MAX_STRLEN+1];
  34099. DUK_SNPRINTF(buf, sizeof(buf), "%lu", (unsigned long) val);
  34100. buf[sizeof(buf) - 1] = (char) 0;
  34101. DUK_ASSERT(DUK_STRLEN(buf) <= DUK_UINT32_MAX); /* formatted result limited */
  34102. return duk_heap_string_intern(heap, (const duk_uint8_t *) buf, (duk_uint32_t) DUK_STRLEN(buf));
  34103. }
  34104. DUK_INTERNAL duk_hstring *duk_heap_string_intern_u32_checked(duk_hthread *thr, duk_uint32_t val) {
  34105. duk_hstring *res = duk_heap_string_intern_u32(thr->heap, val);
  34106. if (!res) {
  34107. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, "failed to intern string");
  34108. }
  34109. return res;
  34110. }
  34111. /* find and remove string from stringtable; caller must free the string itself */
  34112. DUK_INTERNAL void duk_heap_string_remove(duk_heap *heap, duk_hstring *h) {
  34113. DUK_DDD(DUK_DDDPRINT("remove string from stringtable: %!O", (duk_heaphdr *) h));
  34114. #if defined(DUK_USE_STRTAB_CHAIN)
  34115. duk__remove_matching_hstring_chain(heap, h);
  34116. #elif defined(DUK_USE_STRTAB_PROBE)
  34117. duk__remove_matching_hstring_probe(heap,
  34118. #if defined(DUK_USE_HEAPPTR16)
  34119. heap->strtable16,
  34120. #else
  34121. heap->strtable,
  34122. #endif
  34123. heap->st_size,
  34124. h);
  34125. #else
  34126. #error internal error, invalid strtab options
  34127. #endif
  34128. }
  34129. #if defined(DUK_USE_MARK_AND_SWEEP) && defined(DUK_USE_MS_STRINGTABLE_RESIZE)
  34130. DUK_INTERNAL void duk_heap_force_strtab_resize(duk_heap *heap) {
  34131. /* Force a resize so that DELETED entries are eliminated.
  34132. * Another option would be duk__recheck_strtab_size_probe();
  34133. * but since that happens on every intern anyway, this whole
  34134. * check can now be disabled.
  34135. */
  34136. #if defined(DUK_USE_STRTAB_CHAIN)
  34137. DUK_UNREF(heap);
  34138. #elif defined(DUK_USE_STRTAB_PROBE)
  34139. duk__resize_strtab_probe(heap);
  34140. #endif
  34141. }
  34142. #endif
  34143. #if defined(DUK_USE_STRTAB_CHAIN)
  34144. DUK_INTERNAL void duk_heap_free_strtab(duk_heap *heap) {
  34145. /* Free strings in the stringtable and any allocations needed
  34146. * by the stringtable itself.
  34147. */
  34148. duk_uint_fast32_t i, j;
  34149. duk_strtab_entry *e;
  34150. #if defined(DUK_USE_HEAPPTR16)
  34151. duk_uint16_t *lst;
  34152. duk_uint16_t null16 = heap->heapptr_null16;
  34153. #else
  34154. duk_hstring **lst;
  34155. #endif
  34156. duk_hstring *h;
  34157. for (i = 0; i < DUK_STRTAB_CHAIN_SIZE; i++) {
  34158. e = heap->strtable + i;
  34159. if (e->listlen > 0) {
  34160. #if defined(DUK_USE_HEAPPTR16)
  34161. lst = (duk_uint16_t *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.strlist16);
  34162. #else
  34163. lst = e->u.strlist;
  34164. #endif
  34165. DUK_ASSERT(lst != NULL);
  34166. for (j = 0; j < e->listlen; j++) {
  34167. #if defined(DUK_USE_HEAPPTR16)
  34168. h = DUK_USE_HEAPPTR_DEC16(heap->heap_udata, lst[j]);
  34169. lst[j] = null16;
  34170. #else
  34171. h = lst[j];
  34172. lst[j] = NULL;
  34173. #endif
  34174. /* strings may have inner refs (extdata) in some cases */
  34175. if (h != NULL) {
  34176. duk_free_hstring_inner(heap, h);
  34177. DUK_FREE(heap, h);
  34178. }
  34179. }
  34180. #if defined(DUK_USE_HEAPPTR16)
  34181. e->u.strlist16 = null16;
  34182. #else
  34183. e->u.strlist = NULL;
  34184. #endif
  34185. DUK_FREE(heap, lst);
  34186. } else {
  34187. #if defined(DUK_USE_HEAPPTR16)
  34188. h = DUK_USE_HEAPPTR_DEC16(heap->heap_udata, e->u.str16);
  34189. e->u.str16 = null16;
  34190. #else
  34191. h = e->u.str;
  34192. e->u.str = NULL;
  34193. #endif
  34194. if (h != NULL) {
  34195. duk_free_hstring_inner(heap, h);
  34196. DUK_FREE(heap, h);
  34197. }
  34198. }
  34199. e->listlen = 0;
  34200. }
  34201. }
  34202. #endif /* DUK_USE_STRTAB_CHAIN */
  34203. #if defined(DUK_USE_STRTAB_PROBE)
  34204. DUK_INTERNAL void duk_heap_free_strtab(duk_heap *heap) {
  34205. duk_uint_fast32_t i;
  34206. duk_hstring *h;
  34207. #if defined(DUK_USE_HEAPPTR16)
  34208. if (heap->strtable16) {
  34209. #else
  34210. if (heap->strtable) {
  34211. #endif
  34212. for (i = 0; i < (duk_uint_fast32_t) heap->st_size; i++) {
  34213. #if defined(DUK_USE_HEAPPTR16)
  34214. h = (duk_hstring *) DUK_USE_HEAPPTR_DEC16(heap->heap_udata, heap->strtable16[i]);
  34215. #else
  34216. h = heap->strtable[i];
  34217. #endif
  34218. if (h == NULL || h == DUK_STRTAB_DELETED_MARKER(heap)) {
  34219. continue;
  34220. }
  34221. DUK_ASSERT(h != NULL);
  34222. /* strings may have inner refs (extdata) in some cases */
  34223. duk_free_hstring_inner(heap, h);
  34224. DUK_FREE(heap, h);
  34225. #if 0 /* not strictly necessary */
  34226. heap->strtable[i] = NULL;
  34227. #endif
  34228. }
  34229. #if defined(DUK_USE_HEAPPTR16)
  34230. DUK_FREE(heap, heap->strtable16);
  34231. #else
  34232. DUK_FREE(heap, heap->strtable);
  34233. #endif
  34234. #if 0 /* not strictly necessary */
  34235. heap->strtable = NULL;
  34236. #endif
  34237. }
  34238. }
  34239. #endif /* DUK_USE_STRTAB_PROBE */
  34240. /* Undefine local defines */
  34241. #undef DUK__HASH_INITIAL
  34242. #undef DUK__HASH_PROBE_STEP
  34243. #undef DUK__DELETED_MARKER
  34244. #line 1 "duk_hobject_alloc.c"
  34245. /*
  34246. * Hobject allocation.
  34247. *
  34248. * Provides primitive allocation functions for all object types (plain object,
  34249. * compiled function, native function, thread). The object return is not yet
  34250. * in "heap allocated" list and has a refcount of zero, so caller must careful.
  34251. */
  34252. /* include removed: duk_internal.h */
  34253. DUK_LOCAL void duk__init_object_parts(duk_heap *heap, duk_hobject *obj, duk_uint_t hobject_flags) {
  34254. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  34255. DUK_HOBJECT_SET_PROPS(heap, obj, NULL);
  34256. #endif
  34257. /* XXX: macro? sets both heaphdr and object flags */
  34258. obj->hdr.h_flags = hobject_flags;
  34259. DUK_HEAPHDR_SET_TYPE(&obj->hdr, DUK_HTYPE_OBJECT); /* also goes into flags */
  34260. #if defined(DUK_USE_HEAPPTR16)
  34261. /* Zero encoded pointer is required to match NULL */
  34262. DUK_HEAPHDR_SET_NEXT(heap, &obj->hdr, NULL);
  34263. #if defined(DUK_USE_DOUBLE_LINKED_HEAP)
  34264. DUK_HEAPHDR_SET_PREV(heap, &obj->hdr, NULL);
  34265. #endif
  34266. #endif
  34267. DUK_HEAP_INSERT_INTO_HEAP_ALLOCATED(heap, &obj->hdr);
  34268. /*
  34269. * obj->props is intentionally left as NULL, and duk_hobject_props.c must deal
  34270. * with this properly. This is intentional: empty objects consume a minimum
  34271. * amount of memory. Further, an initial allocation might fail and cause
  34272. * 'obj' to "leak" (require a mark-and-sweep) since it is not reachable yet.
  34273. */
  34274. }
  34275. /*
  34276. * Allocate an duk_hobject.
  34277. *
  34278. * The allocated object has no allocation for properties; the caller may
  34279. * want to force a resize if a desired size is known.
  34280. *
  34281. * The allocated object has zero reference count and is not reachable.
  34282. * The caller MUST make the object reachable and increase its reference
  34283. * count before invoking any operation that might require memory allocation.
  34284. */
  34285. DUK_INTERNAL duk_hobject *duk_hobject_alloc(duk_heap *heap, duk_uint_t hobject_flags) {
  34286. duk_hobject *res;
  34287. DUK_ASSERT(heap != NULL);
  34288. /* different memory layout, alloc size, and init */
  34289. DUK_ASSERT((hobject_flags & DUK_HOBJECT_FLAG_COMPILEDFUNCTION) == 0);
  34290. DUK_ASSERT((hobject_flags & DUK_HOBJECT_FLAG_NATIVEFUNCTION) == 0);
  34291. DUK_ASSERT((hobject_flags & DUK_HOBJECT_FLAG_THREAD) == 0);
  34292. res = (duk_hobject *) DUK_ALLOC(heap, sizeof(duk_hobject));
  34293. if (!res) {
  34294. return NULL;
  34295. }
  34296. DUK_MEMZERO(res, sizeof(duk_hobject));
  34297. duk__init_object_parts(heap, res, hobject_flags);
  34298. return res;
  34299. }
  34300. DUK_INTERNAL duk_hcompiledfunction *duk_hcompiledfunction_alloc(duk_heap *heap, duk_uint_t hobject_flags) {
  34301. duk_hcompiledfunction *res;
  34302. res = (duk_hcompiledfunction *) DUK_ALLOC(heap, sizeof(duk_hcompiledfunction));
  34303. if (!res) {
  34304. return NULL;
  34305. }
  34306. DUK_MEMZERO(res, sizeof(duk_hcompiledfunction));
  34307. duk__init_object_parts(heap, &res->obj, hobject_flags);
  34308. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  34309. #ifdef DUK_HEAPPTR16
  34310. /* NULL pointer is required to encode to zero, so memset is enough. */
  34311. #else
  34312. res->data = NULL;
  34313. res->funcs = NULL;
  34314. res->bytecode = NULL;
  34315. #endif
  34316. #endif
  34317. return res;
  34318. }
  34319. DUK_INTERNAL duk_hnativefunction *duk_hnativefunction_alloc(duk_heap *heap, duk_uint_t hobject_flags) {
  34320. duk_hnativefunction *res;
  34321. res = (duk_hnativefunction *) DUK_ALLOC(heap, sizeof(duk_hnativefunction));
  34322. if (!res) {
  34323. return NULL;
  34324. }
  34325. DUK_MEMZERO(res, sizeof(duk_hnativefunction));
  34326. duk__init_object_parts(heap, &res->obj, hobject_flags);
  34327. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  34328. res->func = NULL;
  34329. #endif
  34330. return res;
  34331. }
  34332. /*
  34333. * Allocate a new thread.
  34334. *
  34335. * Leaves the built-ins array uninitialized. The caller must either
  34336. * initialize a new global context or share existing built-ins from
  34337. * another thread.
  34338. */
  34339. DUK_INTERNAL duk_hthread *duk_hthread_alloc(duk_heap *heap, duk_uint_t hobject_flags) {
  34340. duk_hthread *res;
  34341. res = (duk_hthread *) DUK_ALLOC(heap, sizeof(duk_hthread));
  34342. if (!res) {
  34343. return NULL;
  34344. }
  34345. DUK_MEMZERO(res, sizeof(duk_hthread));
  34346. duk__init_object_parts(heap, &res->obj, hobject_flags);
  34347. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  34348. res->heap = NULL;
  34349. res->valstack = NULL;
  34350. res->valstack_end = NULL;
  34351. res->valstack_bottom = NULL;
  34352. res->valstack_top = NULL;
  34353. res->callstack = NULL;
  34354. res->catchstack = NULL;
  34355. res->resumer = NULL;
  34356. res->compile_ctx = NULL,
  34357. res->strs = NULL;
  34358. {
  34359. int i;
  34360. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  34361. res->builtins[i] = NULL;
  34362. }
  34363. }
  34364. #endif
  34365. /* when nothing is running, API calls are in non-strict mode */
  34366. DUK_ASSERT(res->strict == 0);
  34367. res->heap = heap;
  34368. res->valstack_max = DUK_VALSTACK_DEFAULT_MAX;
  34369. res->callstack_max = DUK_CALLSTACK_DEFAULT_MAX;
  34370. res->catchstack_max = DUK_CATCHSTACK_DEFAULT_MAX;
  34371. return res;
  34372. }
  34373. #if 0 /* unused now */
  34374. DUK_INTERNAL duk_hobject *duk_hobject_alloc_checked(duk_hthread *thr, duk_uint_t hobject_flags) {
  34375. duk_hobject *res = duk_hobject_alloc(thr->heap, hobject_flags);
  34376. if (!res) {
  34377. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, "failed to allocate an object");
  34378. }
  34379. return res;
  34380. }
  34381. #endif
  34382. #line 1 "duk_hobject_enum.c"
  34383. /*
  34384. * Hobject enumeration support.
  34385. *
  34386. * Creates an internal enumeration state object to be used e.g. with for-in
  34387. * enumeration. The state object contains a snapshot of target object keys
  34388. * and internal control state for enumeration. Enumerator flags allow caller
  34389. * to e.g. request internal/non-enumerable properties, and to enumerate only
  34390. * "own" properties.
  34391. *
  34392. * Also creates the result value for e.g. Object.keys() based on the same
  34393. * internal structure.
  34394. *
  34395. * This snapshot-based enumeration approach is used to simplify enumeration:
  34396. * non-snapshot-based approaches are difficult to reconcile with mutating
  34397. * the enumeration target, running multiple long-lived enumerators at the
  34398. * same time, garbage collection details, etc. The downside is that the
  34399. * enumerator object is memory inefficient especially for iterating arrays.
  34400. */
  34401. /* include removed: duk_internal.h */
  34402. /* XXX: identify enumeration target with an object index (not top of stack) */
  34403. /* must match exactly the number of internal properties inserted to enumerator */
  34404. #define DUK__ENUM_START_INDEX 2
  34405. /*
  34406. * Helper to sort array index keys. The keys are in the enumeration object
  34407. * entry part, starting from DUK__ENUM_START_INDEX, and the entry part is dense.
  34408. *
  34409. * We use insertion sort because it is simple (leading to compact code,)
  34410. * works nicely in-place, and minimizes operations if data is already sorted
  34411. * or nearly sorted (which is a very common case here). It also minimizes
  34412. * the use of element comparisons in general. This is nice because element
  34413. * comparisons here involve re-parsing the string keys into numbers each
  34414. * time, which is naturally very expensive.
  34415. *
  34416. * Note that the entry part values are all "true", e.g.
  34417. *
  34418. * "1" -> true, "3" -> true, "2" -> true
  34419. *
  34420. * so it suffices to only work in the key part without exchanging any keys,
  34421. * simplifying the sort.
  34422. *
  34423. * http://en.wikipedia.org/wiki/Insertion_sort
  34424. *
  34425. * (Compiles to about 160 bytes now as a stand-alone function.)
  34426. */
  34427. DUK_LOCAL void duk__sort_array_indices(duk_hthread *thr, duk_hobject *h_obj) {
  34428. duk_hstring **keys;
  34429. duk_hstring **p_curr, **p_insert, **p_end;
  34430. duk_hstring *h_curr;
  34431. duk_uarridx_t val_highest, val_curr, val_insert;
  34432. DUK_ASSERT(h_obj != NULL);
  34433. DUK_ASSERT(DUK_HOBJECT_GET_ENEXT(h_obj) >= 2); /* control props */
  34434. DUK_UNREF(thr);
  34435. if (DUK_HOBJECT_GET_ENEXT(h_obj) <= 1 + DUK__ENUM_START_INDEX) {
  34436. return;
  34437. }
  34438. keys = DUK_HOBJECT_E_GET_KEY_BASE(thr->heap, h_obj);
  34439. p_end = keys + DUK_HOBJECT_GET_ENEXT(h_obj);
  34440. keys += DUK__ENUM_START_INDEX;
  34441. DUK_DDD(DUK_DDDPRINT("keys=%p, p_end=%p (after skipping enum props)",
  34442. (void *) keys, (void *) p_end));
  34443. #ifdef DUK_USE_DDDPRINT
  34444. {
  34445. duk_uint_fast32_t i;
  34446. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(h_obj); i++) {
  34447. DUK_DDD(DUK_DDDPRINT("initial: %ld %p -> %!O",
  34448. (long) i,
  34449. (void *) DUK_HOBJECT_E_GET_KEY_PTR(thr->heap, h_obj, i),
  34450. (duk_heaphdr *) DUK_HOBJECT_E_GET_KEY(thr->heap, h_obj, i)));
  34451. }
  34452. }
  34453. #endif
  34454. val_highest = DUK_HSTRING_GET_ARRIDX_SLOW(keys[0]);
  34455. for (p_curr = keys + 1; p_curr < p_end; p_curr++) {
  34456. DUK_ASSERT(*p_curr != NULL);
  34457. val_curr = DUK_HSTRING_GET_ARRIDX_SLOW(*p_curr);
  34458. if (val_curr >= val_highest) {
  34459. DUK_DDD(DUK_DDDPRINT("p_curr=%p, p_end=%p, val_highest=%ld, val_curr=%ld -> "
  34460. "already in correct order, next",
  34461. (void *) p_curr, (void *) p_end, (long) val_highest, (long) val_curr));
  34462. val_highest = val_curr;
  34463. continue;
  34464. }
  34465. DUK_DDD(DUK_DDDPRINT("p_curr=%p, p_end=%p, val_highest=%ld, val_curr=%ld -> "
  34466. "needs to be inserted",
  34467. (void *) p_curr, (void *) p_end, (long) val_highest, (long) val_curr));
  34468. /* Needs to be inserted; scan backwards, since we optimize
  34469. * for the case where elements are nearly in order.
  34470. */
  34471. p_insert = p_curr - 1;
  34472. for (;;) {
  34473. val_insert = DUK_HSTRING_GET_ARRIDX_SLOW(*p_insert);
  34474. if (val_insert < val_curr) {
  34475. DUK_DDD(DUK_DDDPRINT("p_insert=%p, val_insert=%ld, val_curr=%ld -> insert after this",
  34476. (void *) p_insert, (long) val_insert, (long) val_curr));
  34477. p_insert++;
  34478. break;
  34479. }
  34480. if (p_insert == keys) {
  34481. DUK_DDD(DUK_DDDPRINT("p_insert=%p -> out of keys, insert to beginning", (void *) p_insert));
  34482. break;
  34483. }
  34484. DUK_DDD(DUK_DDDPRINT("p_insert=%p, val_insert=%ld, val_curr=%ld -> search backwards",
  34485. (void *) p_insert, (long) val_insert, (long) val_curr));
  34486. p_insert--;
  34487. }
  34488. DUK_DDD(DUK_DDDPRINT("final p_insert=%p", (void *) p_insert));
  34489. /* .-- p_insert .-- p_curr
  34490. * v v
  34491. * | ... | insert | ... | curr
  34492. */
  34493. h_curr = *p_curr;
  34494. DUK_DDD(DUK_DDDPRINT("memmove: dest=%p, src=%p, size=%ld, h_curr=%p",
  34495. (void *) (p_insert + 1), (void *) p_insert,
  34496. (long) (p_curr - p_insert), (void *) h_curr));
  34497. DUK_MEMMOVE((void *) (p_insert + 1),
  34498. (void *) p_insert,
  34499. (size_t) ((p_curr - p_insert) * sizeof(duk_hstring *)));
  34500. *p_insert = h_curr;
  34501. /* keep val_highest */
  34502. }
  34503. #ifdef DUK_USE_DDDPRINT
  34504. {
  34505. duk_uint_fast32_t i;
  34506. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(h_obj); i++) {
  34507. DUK_DDD(DUK_DDDPRINT("final: %ld %p -> %!O",
  34508. (long) i,
  34509. (void *) DUK_HOBJECT_E_GET_KEY_PTR(thr->heap, h_obj, i),
  34510. (duk_heaphdr *) DUK_HOBJECT_E_GET_KEY(thr->heap, h_obj, i)));
  34511. }
  34512. }
  34513. #endif
  34514. }
  34515. /*
  34516. * Create an internal enumerator object E, which has its keys ordered
  34517. * to match desired enumeration ordering. Also initialize internal control
  34518. * properties for enumeration.
  34519. *
  34520. * Note: if an array was used to hold enumeration keys instead, an array
  34521. * scan would be needed to eliminate duplicates found in the prototype chain.
  34522. */
  34523. DUK_INTERNAL void duk_hobject_enumerator_create(duk_context *ctx, duk_small_uint_t enum_flags) {
  34524. duk_hthread *thr = (duk_hthread *) ctx;
  34525. duk_hobject *enum_target;
  34526. duk_hobject *curr;
  34527. duk_hobject *res;
  34528. #if defined(DUK_USE_ES6_PROXY)
  34529. duk_hobject *h_proxy_target;
  34530. duk_hobject *h_proxy_handler;
  34531. duk_hobject *h_trap_result;
  34532. #endif
  34533. duk_uint_fast32_t i, len; /* used for array, stack, and entry indices */
  34534. DUK_ASSERT(ctx != NULL);
  34535. DUK_DDD(DUK_DDDPRINT("create enumerator, stack top: %ld", (long) duk_get_top(ctx)));
  34536. enum_target = duk_require_hobject(ctx, -1);
  34537. DUK_ASSERT(enum_target != NULL);
  34538. duk_push_object_internal(ctx);
  34539. res = duk_require_hobject(ctx, -1);
  34540. DUK_DDD(DUK_DDDPRINT("created internal object"));
  34541. /* [enum_target res] */
  34542. /* Target must be stored so that we can recheck whether or not
  34543. * keys still exist when we enumerate. This is not done if the
  34544. * enumeration result comes from a proxy trap as there is no
  34545. * real object to check against.
  34546. */
  34547. duk_push_hobject(ctx, enum_target);
  34548. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_INT_TARGET);
  34549. /* Initialize index so that we skip internal control keys. */
  34550. duk_push_int(ctx, DUK__ENUM_START_INDEX);
  34551. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_INT_NEXT);
  34552. /*
  34553. * Proxy object handling
  34554. */
  34555. #if defined(DUK_USE_ES6_PROXY)
  34556. if (DUK_LIKELY((enum_flags & DUK_ENUM_NO_PROXY_BEHAVIOR) != 0)) {
  34557. goto skip_proxy;
  34558. }
  34559. if (DUK_LIKELY(!duk_hobject_proxy_check(thr,
  34560. enum_target,
  34561. &h_proxy_target,
  34562. &h_proxy_handler))) {
  34563. goto skip_proxy;
  34564. }
  34565. DUK_DDD(DUK_DDDPRINT("proxy enumeration"));
  34566. duk_push_hobject(ctx, h_proxy_handler);
  34567. if (!duk_get_prop_stridx(ctx, -1, DUK_STRIDX_ENUMERATE)) {
  34568. /* No need to replace the 'enum_target' value in stack, only the
  34569. * enum_target reference. This also ensures that the original
  34570. * enum target is reachable, which keeps the proxy and the proxy
  34571. * target reachable. We do need to replace the internal _Target.
  34572. */
  34573. DUK_DDD(DUK_DDDPRINT("no enumerate trap, enumerate proxy target instead"));
  34574. DUK_DDD(DUK_DDDPRINT("h_proxy_target=%!O", (duk_heaphdr *) h_proxy_target));
  34575. enum_target = h_proxy_target;
  34576. duk_push_hobject(ctx, enum_target); /* -> [ ... enum_target res handler undefined target ] */
  34577. duk_put_prop_stridx(ctx, -4, DUK_STRIDX_INT_TARGET);
  34578. duk_pop_2(ctx); /* -> [ ... enum_target res ] */
  34579. goto skip_proxy;
  34580. }
  34581. /* [ ... enum_target res handler trap ] */
  34582. duk_insert(ctx, -2);
  34583. duk_push_hobject(ctx, h_proxy_target); /* -> [ ... enum_target res trap handler target ] */
  34584. duk_call_method(ctx, 1 /*nargs*/); /* -> [ ... enum_target res trap_result ] */
  34585. h_trap_result = duk_require_hobject(ctx, -1);
  34586. DUK_UNREF(h_trap_result);
  34587. /* Copy trap result keys into the enumerator object. */
  34588. len = (duk_uint_fast32_t) duk_get_length(ctx, -1);
  34589. for (i = 0; i < len; i++) {
  34590. /* XXX: not sure what the correct semantic details are here,
  34591. * e.g. handling of missing values (gaps), handling of non-array
  34592. * trap results, etc.
  34593. *
  34594. * For keys, we simply skip non-string keys which seems to be
  34595. * consistent with how e.g. Object.keys() will process proxy trap
  34596. * results (ES6 draft, Section 19.1.2.14).
  34597. */
  34598. if (duk_get_prop_index(ctx, -1, i) && duk_is_string(ctx, -1)) {
  34599. /* [ ... enum_target res trap_result val ] */
  34600. duk_push_true(ctx);
  34601. /* [ ... enum_target res trap_result val true ] */
  34602. duk_put_prop(ctx, -4);
  34603. } else {
  34604. duk_pop(ctx);
  34605. }
  34606. }
  34607. /* [ ... enum_target res trap_result ] */
  34608. duk_pop(ctx);
  34609. duk_remove(ctx, -2);
  34610. /* [ ... res ] */
  34611. /* The internal _Target property is kept pointing to the original
  34612. * enumeration target (the proxy object), so that the enumerator
  34613. * 'next' operation can read property values if so requested. The
  34614. * fact that the _Target is a proxy disables key existence check
  34615. * during enumeration.
  34616. */
  34617. DUK_DDD(DUK_DDDPRINT("proxy enumeration, final res: %!O", (duk_heaphdr *) res));
  34618. goto compact_and_return;
  34619. skip_proxy:
  34620. #endif /* DUK_USE_ES6_PROXY */
  34621. curr = enum_target;
  34622. while (curr) {
  34623. /*
  34624. * Virtual properties.
  34625. *
  34626. * String and buffer indices are virtual and always enumerable,
  34627. * 'length' is virtual and non-enumerable. Array and arguments
  34628. * object props have special behavior but are concrete.
  34629. */
  34630. if (DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(curr) ||
  34631. DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(curr)) {
  34632. /* String and buffer enumeration behavior is identical now,
  34633. * so use shared handler.
  34634. */
  34635. if (DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(curr)) {
  34636. duk_hstring *h_val;
  34637. h_val = duk_hobject_get_internal_value_string(thr->heap, curr);
  34638. DUK_ASSERT(h_val != NULL); /* string objects must not created without internal value */
  34639. len = (duk_uint_fast32_t) DUK_HSTRING_GET_CHARLEN(h_val);
  34640. } else {
  34641. duk_hbuffer *h_val;
  34642. DUK_ASSERT(DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(curr));
  34643. h_val = duk_hobject_get_internal_value_buffer(thr->heap, curr);
  34644. DUK_ASSERT(h_val != NULL); /* buffer objects must not created without internal value */
  34645. len = (duk_uint_fast32_t) DUK_HBUFFER_GET_SIZE(h_val);
  34646. }
  34647. for (i = 0; i < len; i++) {
  34648. duk_hstring *k;
  34649. k = duk_heap_string_intern_u32_checked(thr, i);
  34650. DUK_ASSERT(k);
  34651. duk_push_hstring(ctx, k);
  34652. duk_push_true(ctx);
  34653. /* [enum_target res key true] */
  34654. duk_put_prop(ctx, -3);
  34655. /* [enum_target res] */
  34656. }
  34657. /* 'length' property is not enumerable, but is included if
  34658. * non-enumerable properties are requested.
  34659. */
  34660. if (enum_flags & DUK_ENUM_INCLUDE_NONENUMERABLE) {
  34661. duk_push_hstring_stridx(ctx, DUK_STRIDX_LENGTH);
  34662. duk_push_true(ctx);
  34663. duk_put_prop(ctx, -3);
  34664. }
  34665. } else if (DUK_HOBJECT_HAS_EXOTIC_DUKFUNC(curr)) {
  34666. if (enum_flags & DUK_ENUM_INCLUDE_NONENUMERABLE) {
  34667. duk_push_hstring_stridx(ctx, DUK_STRIDX_LENGTH);
  34668. duk_push_true(ctx);
  34669. duk_put_prop(ctx, -3);
  34670. }
  34671. }
  34672. /*
  34673. * Array part
  34674. *
  34675. * Note: ordering between array and entry part must match 'abandon array'
  34676. * behavior in duk_hobject_props.c: key order after an array is abandoned
  34677. * must be the same.
  34678. */
  34679. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ASIZE(curr); i++) {
  34680. duk_hstring *k;
  34681. duk_tval *tv;
  34682. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, curr, i);
  34683. if (DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  34684. continue;
  34685. }
  34686. k = duk_heap_string_intern_u32_checked(thr, i);
  34687. DUK_ASSERT(k);
  34688. duk_push_hstring(ctx, k);
  34689. duk_push_true(ctx);
  34690. /* [enum_target res key true] */
  34691. duk_put_prop(ctx, -3);
  34692. /* [enum_target res] */
  34693. }
  34694. /*
  34695. * Entries part
  34696. */
  34697. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(curr); i++) {
  34698. duk_hstring *k;
  34699. k = DUK_HOBJECT_E_GET_KEY(thr->heap, curr, i);
  34700. if (!k) {
  34701. continue;
  34702. }
  34703. if (!DUK_HOBJECT_E_SLOT_IS_ENUMERABLE(thr->heap, curr, i) &&
  34704. !(enum_flags & DUK_ENUM_INCLUDE_NONENUMERABLE)) {
  34705. continue;
  34706. }
  34707. if (DUK_HSTRING_HAS_INTERNAL(k) &&
  34708. !(enum_flags & DUK_ENUM_INCLUDE_INTERNAL)) {
  34709. continue;
  34710. }
  34711. if ((enum_flags & DUK_ENUM_ARRAY_INDICES_ONLY) &&
  34712. (DUK_HSTRING_GET_ARRIDX_SLOW(k) == DUK_HSTRING_NO_ARRAY_INDEX)) {
  34713. continue;
  34714. }
  34715. DUK_ASSERT(DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, curr, i) ||
  34716. !DUK_TVAL_IS_UNDEFINED_UNUSED(&DUK_HOBJECT_E_GET_VALUE_PTR(thr->heap, curr, i)->v));
  34717. duk_push_hstring(ctx, k);
  34718. duk_push_true(ctx);
  34719. /* [enum_target res key true] */
  34720. duk_put_prop(ctx, -3);
  34721. /* [enum_target res] */
  34722. }
  34723. if (enum_flags & DUK_ENUM_OWN_PROPERTIES_ONLY) {
  34724. break;
  34725. }
  34726. curr = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, curr);
  34727. }
  34728. /* [enum_target res] */
  34729. duk_remove(ctx, -2);
  34730. /* [res] */
  34731. if ((enum_flags & (DUK_ENUM_ARRAY_INDICES_ONLY | DUK_ENUM_SORT_ARRAY_INDICES)) ==
  34732. (DUK_ENUM_ARRAY_INDICES_ONLY | DUK_ENUM_SORT_ARRAY_INDICES)) {
  34733. /*
  34734. * Some E5/E5.1 algorithms require that array indices are iterated
  34735. * in a strictly ascending order. This is the case for e.g.
  34736. * Array.prototype.forEach() and JSON.stringify() PropertyList
  34737. * handling.
  34738. *
  34739. * To ensure this property for arrays with an array part (and
  34740. * arbitrary objects too, since e.g. forEach() can be applied
  34741. * to an array), the caller can request that we sort the keys
  34742. * here.
  34743. */
  34744. /* XXX: avoid this at least when enum_target is an Array, it has an
  34745. * array part, and no ancestor properties were included? Not worth
  34746. * it for JSON, but maybe worth it for forEach().
  34747. */
  34748. /* XXX: may need a 'length' filter for forEach()
  34749. */
  34750. DUK_DDD(DUK_DDDPRINT("sort array indices by caller request"));
  34751. duk__sort_array_indices(thr, res);
  34752. }
  34753. #if defined(DUK_USE_ES6_PROXY)
  34754. compact_and_return:
  34755. #endif
  34756. /* compact; no need to seal because object is internal */
  34757. duk_hobject_compact_props(thr, res);
  34758. DUK_DDD(DUK_DDDPRINT("created enumerator object: %!iT", (duk_tval *) duk_get_tval(ctx, -1)));
  34759. }
  34760. /*
  34761. * Returns non-zero if a key and/or value was enumerated, and:
  34762. *
  34763. * [enum] -> [key] (get_value == 0)
  34764. * [enum] -> [key value] (get_value == 1)
  34765. *
  34766. * Returns zero without pushing anything on the stack otherwise.
  34767. */
  34768. DUK_INTERNAL duk_bool_t duk_hobject_enumerator_next(duk_context *ctx, duk_bool_t get_value) {
  34769. duk_hthread *thr = (duk_hthread *) ctx;
  34770. duk_hobject *e;
  34771. duk_hobject *enum_target;
  34772. duk_hstring *res = NULL;
  34773. duk_uint_fast32_t idx;
  34774. duk_bool_t check_existence;
  34775. DUK_ASSERT(ctx != NULL);
  34776. /* [... enum] */
  34777. e = duk_require_hobject(ctx, -1);
  34778. /* XXX use get tval ptr, more efficient */
  34779. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_NEXT);
  34780. idx = (duk_uint_fast32_t) duk_require_uint(ctx, -1);
  34781. duk_pop(ctx);
  34782. DUK_DDD(DUK_DDDPRINT("enumeration: index is: %ld", (long) idx));
  34783. /* Enumeration keys are checked against the enumeration target (to see
  34784. * that they still exist). In the proxy enumeration case _Target will
  34785. * be the proxy, and checking key existence against the proxy is not
  34786. * required (or sensible, as the keys may be fully virtual).
  34787. */
  34788. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_TARGET);
  34789. enum_target = duk_require_hobject(ctx, -1);
  34790. DUK_ASSERT(enum_target != NULL);
  34791. #if defined(DUK_USE_ES6_PROXY)
  34792. check_existence = (!DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(enum_target));
  34793. #else
  34794. check_existence = 1;
  34795. #endif
  34796. duk_pop(ctx); /* still reachable */
  34797. DUK_DDD(DUK_DDDPRINT("getting next enum value, enum_target=%!iO, enumerator=%!iT",
  34798. (duk_heaphdr *) enum_target, (duk_tval *) duk_get_tval(ctx, -1)));
  34799. /* no array part */
  34800. for (;;) {
  34801. duk_hstring *k;
  34802. if (idx >= DUK_HOBJECT_GET_ENEXT(e)) {
  34803. DUK_DDD(DUK_DDDPRINT("enumeration: ran out of elements"));
  34804. break;
  34805. }
  34806. /* we know these because enum objects are internally created */
  34807. k = DUK_HOBJECT_E_GET_KEY(thr->heap, e, idx);
  34808. DUK_ASSERT(k != NULL);
  34809. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, e, idx));
  34810. DUK_ASSERT(!DUK_TVAL_IS_UNDEFINED_UNUSED(&DUK_HOBJECT_E_GET_VALUE(thr->heap, e, idx).v));
  34811. idx++;
  34812. /* recheck that the property still exists */
  34813. if (check_existence && !duk_hobject_hasprop_raw(thr, enum_target, k)) {
  34814. DUK_DDD(DUK_DDDPRINT("property deleted during enumeration, skip"));
  34815. continue;
  34816. }
  34817. DUK_DDD(DUK_DDDPRINT("enumeration: found element, key: %!O", (duk_heaphdr *) k));
  34818. res = k;
  34819. break;
  34820. }
  34821. DUK_DDD(DUK_DDDPRINT("enumeration: updating next index to %ld", (long) idx));
  34822. duk_push_u32(ctx, (duk_uint32_t) idx);
  34823. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_INT_NEXT);
  34824. /* [... enum] */
  34825. if (res) {
  34826. duk_push_hstring(ctx, res);
  34827. if (get_value) {
  34828. duk_push_hobject(ctx, enum_target);
  34829. duk_dup(ctx, -2); /* -> [... enum key enum_target key] */
  34830. duk_get_prop(ctx, -2); /* -> [... enum key enum_target val] */
  34831. duk_remove(ctx, -2); /* -> [... enum key val] */
  34832. duk_remove(ctx, -3); /* -> [... key val] */
  34833. } else {
  34834. duk_remove(ctx, -2); /* -> [... key] */
  34835. }
  34836. return 1;
  34837. } else {
  34838. duk_pop(ctx); /* -> [...] */
  34839. return 0;
  34840. }
  34841. }
  34842. /*
  34843. * Get enumerated keys in an Ecmascript array. Matches Object.keys() behavior
  34844. * described in E5 Section 15.2.3.14.
  34845. */
  34846. DUK_INTERNAL duk_ret_t duk_hobject_get_enumerated_keys(duk_context *ctx, duk_small_uint_t enum_flags) {
  34847. duk_hthread *thr = (duk_hthread *) ctx;
  34848. duk_hobject *e;
  34849. duk_uint_fast32_t i;
  34850. duk_uint_fast32_t idx;
  34851. DUK_ASSERT(ctx != NULL);
  34852. DUK_ASSERT(duk_get_hobject(ctx, -1) != NULL);
  34853. DUK_UNREF(thr);
  34854. /* Create a temporary enumerator to get the (non-duplicated) key list;
  34855. * the enumerator state is initialized without being needed, but that
  34856. * has little impact.
  34857. */
  34858. duk_hobject_enumerator_create(ctx, enum_flags);
  34859. duk_push_array(ctx);
  34860. /* [enum_target enum res] */
  34861. e = duk_require_hobject(ctx, -2);
  34862. DUK_ASSERT(e != NULL);
  34863. idx = 0;
  34864. for (i = DUK__ENUM_START_INDEX; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(e); i++) {
  34865. duk_hstring *k;
  34866. k = DUK_HOBJECT_E_GET_KEY(thr->heap, e, i);
  34867. DUK_ASSERT(k); /* enumerator must have no keys deleted */
  34868. /* [enum_target enum res] */
  34869. duk_push_hstring(ctx, k);
  34870. duk_put_prop_index(ctx, -2, idx);
  34871. idx++;
  34872. }
  34873. /* [enum_target enum res] */
  34874. duk_remove(ctx, -2);
  34875. /* [enum_target res] */
  34876. return 1; /* return 1 to allow callers to tail call */
  34877. }
  34878. #line 1 "duk_hobject_finalizer.c"
  34879. /*
  34880. * Run an duk_hobject finalizer. Used for both reference counting
  34881. * and mark-and-sweep algorithms. Must never throw an error.
  34882. *
  34883. * There is no return value. Any return value or error thrown by
  34884. * the finalizer is ignored (although errors are debug logged).
  34885. *
  34886. * Notes:
  34887. *
  34888. * - The thread used for calling the finalizer is the same as the
  34889. * 'thr' argument. This may need to change later.
  34890. *
  34891. * - The finalizer thread 'top' assertions are there because it is
  34892. * critical that strict stack policy is observed (i.e. no cruft
  34893. * left on the finalizer stack).
  34894. */
  34895. /* include removed: duk_internal.h */
  34896. DUK_LOCAL duk_ret_t duk__finalize_helper(duk_context *ctx) {
  34897. DUK_ASSERT(ctx != NULL);
  34898. DUK_DDD(DUK_DDDPRINT("protected finalization helper running"));
  34899. /* [... obj] */
  34900. /* XXX: Finalizer lookup should traverse the prototype chain (to allow
  34901. * inherited finalizers) but should not invoke accessors or proxy object
  34902. * behavior. At the moment this lookup will invoke proxy behavior, so
  34903. * caller must ensure that this function is not called if the target is
  34904. * a Proxy.
  34905. */
  34906. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_FINALIZER); /* -> [... obj finalizer] */
  34907. if (!duk_is_callable(ctx, -1)) {
  34908. DUK_DDD(DUK_DDDPRINT("-> no finalizer or finalizer not callable"));
  34909. return 0;
  34910. }
  34911. duk_dup(ctx, -2); /* -> [... obj finalizer obj] */
  34912. DUK_DDD(DUK_DDDPRINT("-> finalizer found, calling finalizer"));
  34913. duk_call(ctx, 1); /* -> [... obj retval] */
  34914. DUK_DDD(DUK_DDDPRINT("finalizer finished successfully"));
  34915. return 0;
  34916. /* Note: we rely on duk_safe_call() to fix up the stack for the caller,
  34917. * so we don't need to pop stuff here. There is no return value;
  34918. * caller determines rescued status based on object refcount.
  34919. */
  34920. }
  34921. DUK_INTERNAL void duk_hobject_run_finalizer(duk_hthread *thr, duk_hobject *obj) {
  34922. duk_context *ctx = (duk_context *) thr;
  34923. duk_ret_t rc;
  34924. #ifdef DUK_USE_ASSERTIONS
  34925. duk_idx_t entry_top;
  34926. #endif
  34927. DUK_DDD(DUK_DDDPRINT("running object finalizer for object: %p", (void *) obj));
  34928. DUK_ASSERT(thr != NULL);
  34929. DUK_ASSERT(ctx != NULL);
  34930. DUK_ASSERT(obj != NULL);
  34931. DUK_ASSERT_VALSTACK_SPACE(thr, 1);
  34932. #ifdef DUK_USE_ASSERTIONS
  34933. entry_top = duk_get_top(ctx);
  34934. #endif
  34935. /*
  34936. * Get and call the finalizer. All of this must be wrapped
  34937. * in a protected call, because even getting the finalizer
  34938. * may trigger an error (getter may throw one, for instance).
  34939. */
  34940. /* XXX: use a NULL error handler for the finalizer call? */
  34941. DUK_DDD(DUK_DDDPRINT("-> finalizer found, calling wrapped finalize helper"));
  34942. duk_push_hobject(ctx, obj); /* this also increases refcount by one */
  34943. rc = duk_safe_call(ctx, duk__finalize_helper, 0 /*nargs*/, 1 /*nrets*/); /* -> [... obj retval/error] */
  34944. DUK_ASSERT_TOP(ctx, entry_top + 2); /* duk_safe_call discipline */
  34945. if (rc != DUK_EXEC_SUCCESS) {
  34946. /* Note: we ask for one return value from duk_safe_call to get this
  34947. * error debugging here.
  34948. */
  34949. DUK_D(DUK_DPRINT("wrapped finalizer call failed for object %p (ignored); error: %!T",
  34950. (void *) obj, (duk_tval *) duk_get_tval(ctx, -1)));
  34951. }
  34952. duk_pop_2(ctx); /* -> [...] */
  34953. DUK_ASSERT_TOP(ctx, entry_top);
  34954. }
  34955. #line 1 "duk_hobject_misc.c"
  34956. /*
  34957. * Misc support functions
  34958. */
  34959. /* include removed: duk_internal.h */
  34960. DUK_INTERNAL duk_bool_t duk_hobject_prototype_chain_contains(duk_hthread *thr, duk_hobject *h, duk_hobject *p, duk_bool_t ignore_loop) {
  34961. duk_uint_t sanity;
  34962. DUK_ASSERT(thr != NULL);
  34963. DUK_ASSERT(h != NULL);
  34964. /* allow 'p' to be NULL; then the result is always false */
  34965. sanity = DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY;
  34966. do {
  34967. if (h == p) {
  34968. return 1;
  34969. }
  34970. if (sanity-- == 0) {
  34971. if (ignore_loop) {
  34972. break;
  34973. } else {
  34974. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_PROTOTYPE_CHAIN_LIMIT);
  34975. }
  34976. }
  34977. h = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h);
  34978. } while (h);
  34979. return 0;
  34980. }
  34981. DUK_INTERNAL void duk_hobject_set_prototype(duk_hthread *thr, duk_hobject *h, duk_hobject *p) {
  34982. #ifdef DUK_USE_REFERENCE_COUNTING
  34983. duk_hobject *tmp;
  34984. DUK_ASSERT(h);
  34985. tmp = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h);
  34986. DUK_HOBJECT_SET_PROTOTYPE(thr->heap, h, p);
  34987. DUK_HOBJECT_INCREF_ALLOWNULL(thr, p); /* avoid problems if p == h->prototype */
  34988. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  34989. #else
  34990. DUK_ASSERT(h);
  34991. DUK_UNREF(thr);
  34992. DUK_HOBJECT_SET_PROTOTYPE(thr->heap, h, p);
  34993. #endif
  34994. }
  34995. #line 1 "duk_hobject_pc2line.c"
  34996. /*
  34997. * Helpers for creating and querying pc2line debug data, which
  34998. * converts a bytecode program counter to a source line number.
  34999. *
  35000. * The run-time pc2line data is bit-packed, and documented in:
  35001. *
  35002. * doc/function-objects.txt
  35003. */
  35004. /* include removed: duk_internal.h */
  35005. #if defined(DUK_USE_PC2LINE)
  35006. /* Generate pc2line data for an instruction sequence, leaving a buffer on stack top. */
  35007. DUK_INTERNAL void duk_hobject_pc2line_pack(duk_hthread *thr, duk_compiler_instr *instrs, duk_uint_fast32_t length) {
  35008. duk_context *ctx = (duk_context *) thr;
  35009. duk_hbuffer_dynamic *h_buf;
  35010. duk_bitencoder_ctx be_ctx_alloc;
  35011. duk_bitencoder_ctx *be_ctx = &be_ctx_alloc;
  35012. duk_uint32_t *hdr;
  35013. duk_size_t new_size;
  35014. duk_uint_fast32_t num_header_entries;
  35015. duk_uint_fast32_t curr_offset;
  35016. duk_int_fast32_t curr_line, next_line, diff_line;
  35017. duk_uint_fast32_t curr_pc;
  35018. duk_uint_fast32_t hdr_index;
  35019. DUK_ASSERT(length <= DUK_COMPILER_MAX_BYTECODE_LENGTH);
  35020. /* XXX: add proper spare handling to dynamic buffer, to minimize
  35021. * reallocs; currently there is no spare at all.
  35022. */
  35023. num_header_entries = (length + DUK_PC2LINE_SKIP - 1) / DUK_PC2LINE_SKIP;
  35024. curr_offset = (duk_uint_fast32_t) (sizeof(duk_uint32_t) + num_header_entries * sizeof(duk_uint32_t) * 2);
  35025. duk_push_dynamic_buffer(ctx, (duk_size_t) curr_offset);
  35026. h_buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  35027. DUK_ASSERT(h_buf != NULL);
  35028. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(h_buf));
  35029. hdr = (duk_uint32_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, h_buf);
  35030. DUK_ASSERT(hdr != NULL);
  35031. hdr[0] = (duk_uint32_t) length; /* valid pc range is [0, length[ */
  35032. curr_pc = 0U;
  35033. while (curr_pc < length) {
  35034. new_size = (duk_size_t) (curr_offset + DUK_PC2LINE_MAX_DIFF_LENGTH);
  35035. duk_hbuffer_resize(thr, h_buf, new_size, new_size);
  35036. hdr = (duk_uint32_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, h_buf);
  35037. DUK_ASSERT(hdr != NULL);
  35038. DUK_ASSERT(curr_pc < length);
  35039. hdr_index = 1 + (curr_pc / DUK_PC2LINE_SKIP) * 2;
  35040. curr_line = (duk_int_fast32_t) instrs[curr_pc].line;
  35041. hdr[hdr_index + 0] = (duk_uint32_t) curr_line;
  35042. hdr[hdr_index + 1] = (duk_uint32_t) curr_offset;
  35043. #if 0
  35044. DUK_DDD(DUK_DDDPRINT("hdr[%ld]: pc=%ld line=%ld offset=%ld",
  35045. (long) (curr_pc / DUK_PC2LINE_SKIP),
  35046. (long) curr_pc,
  35047. (long) hdr[hdr_index + 0],
  35048. (long) hdr[hdr_index + 1]));
  35049. #endif
  35050. DUK_MEMZERO(be_ctx, sizeof(*be_ctx));
  35051. be_ctx->data = ((duk_uint8_t *) hdr) + curr_offset;
  35052. be_ctx->length = (duk_size_t) DUK_PC2LINE_MAX_DIFF_LENGTH;
  35053. for (;;) {
  35054. curr_pc++;
  35055. if ( ((curr_pc % DUK_PC2LINE_SKIP) == 0) || /* end of diff run */
  35056. (curr_pc >= length) ) { /* end of bytecode */
  35057. break;
  35058. }
  35059. DUK_ASSERT(curr_pc < length);
  35060. next_line = (duk_int32_t) instrs[curr_pc].line;
  35061. diff_line = next_line - curr_line;
  35062. #if 0
  35063. DUK_DDD(DUK_DDDPRINT("curr_line=%ld, next_line=%ld -> diff_line=%ld",
  35064. (long) curr_line, (long) next_line, (long) diff_line));
  35065. #endif
  35066. if (diff_line == 0) {
  35067. /* 0 */
  35068. duk_be_encode(be_ctx, 0, 1);
  35069. } else if (diff_line >= 1 && diff_line <= 4) {
  35070. /* 1 0 <2 bits> */
  35071. duk_be_encode(be_ctx, (0x02 << 2) + (diff_line - 1), 4);
  35072. } else if (diff_line >= -0x80 && diff_line <= 0x7f) {
  35073. /* 1 1 0 <8 bits> */
  35074. DUK_ASSERT(diff_line + 0x80 >= 0 && diff_line + 0x80 <= 0xff);
  35075. duk_be_encode(be_ctx, (0x06 << 8) + (diff_line + 0x80), 11);
  35076. } else {
  35077. /* 1 1 1 <32 bits>
  35078. * Encode in two parts to avoid bitencode 24-bit limitation
  35079. */
  35080. duk_be_encode(be_ctx, (0x07 << 16) + ((next_line >> 16) & 0xffffU), 19);
  35081. duk_be_encode(be_ctx, next_line & 0xffffU, 16);
  35082. }
  35083. curr_line = next_line;
  35084. }
  35085. duk_be_finish(be_ctx);
  35086. DUK_ASSERT(!be_ctx->truncated);
  35087. /* be_ctx->offset == length of encoded bitstream */
  35088. curr_offset += (duk_uint_fast32_t) be_ctx->offset;
  35089. }
  35090. /* compact */
  35091. new_size = (duk_size_t) curr_offset;
  35092. duk_hbuffer_resize(thr, h_buf, new_size, new_size);
  35093. (void) duk_to_fixed_buffer(ctx, -1, NULL);
  35094. DUK_DDD(DUK_DDDPRINT("final pc2line data: pc_limit=%ld, length=%ld, %lf bits/opcode --> %!ixT",
  35095. (long) length, (long) new_size, (double) new_size * 8.0 / (double) length,
  35096. (duk_tval *) duk_get_tval(ctx, -1)));
  35097. }
  35098. /* PC is unsigned. If caller does PC arithmetic and gets a negative result,
  35099. * it will map to a large PC which is out of bounds and causes a zero to be
  35100. * returned.
  35101. */
  35102. DUK_LOCAL duk_uint_fast32_t duk__hobject_pc2line_query_raw(duk_hthread *thr, duk_hbuffer_fixed *buf, duk_uint_fast32_t pc) {
  35103. duk_bitdecoder_ctx bd_ctx_alloc;
  35104. duk_bitdecoder_ctx *bd_ctx = &bd_ctx_alloc;
  35105. duk_uint32_t *hdr;
  35106. duk_uint_fast32_t start_offset;
  35107. duk_uint_fast32_t pc_limit;
  35108. duk_uint_fast32_t hdr_index;
  35109. duk_uint_fast32_t pc_base;
  35110. duk_uint_fast32_t n;
  35111. duk_uint_fast32_t curr_line;
  35112. DUK_ASSERT(buf != NULL);
  35113. DUK_ASSERT(!DUK_HBUFFER_HAS_DYNAMIC((duk_hbuffer *) buf));
  35114. DUK_UNREF(thr);
  35115. /*
  35116. * Use the index in the header to find the right starting point
  35117. */
  35118. hdr_index = pc / DUK_PC2LINE_SKIP;
  35119. pc_base = hdr_index * DUK_PC2LINE_SKIP;
  35120. n = pc - pc_base;
  35121. if (DUK_HBUFFER_FIXED_GET_SIZE(buf) <= sizeof(duk_uint32_t)) {
  35122. DUK_DD(DUK_DDPRINT("pc2line lookup failed: buffer is smaller than minimal header"));
  35123. goto error;
  35124. }
  35125. hdr = (duk_uint32_t *) DUK_HBUFFER_FIXED_GET_DATA_PTR(thr->heap, buf);
  35126. pc_limit = hdr[0];
  35127. if (pc >= pc_limit) {
  35128. /* Note: pc is unsigned and cannot be negative */
  35129. DUK_DD(DUK_DDPRINT("pc2line lookup failed: pc out of bounds (pc=%ld, limit=%ld)",
  35130. (long) pc, (long) pc_limit));
  35131. goto error;
  35132. }
  35133. curr_line = hdr[1 + hdr_index * 2];
  35134. start_offset = hdr[1 + hdr_index * 2 + 1];
  35135. if ((duk_size_t) start_offset > DUK_HBUFFER_FIXED_GET_SIZE(buf)) {
  35136. DUK_DD(DUK_DDPRINT("pc2line lookup failed: start_offset out of bounds (start_offset=%ld, buffer_size=%ld)",
  35137. (long) start_offset, (long) DUK_HBUFFER_GET_SIZE((duk_hbuffer *) buf)));
  35138. goto error;
  35139. }
  35140. /*
  35141. * Iterate the bitstream (line diffs) until PC is reached
  35142. */
  35143. DUK_MEMZERO(bd_ctx, sizeof(*bd_ctx));
  35144. bd_ctx->data = ((duk_uint8_t *) hdr) + start_offset;
  35145. bd_ctx->length = (duk_size_t) (DUK_HBUFFER_FIXED_GET_SIZE(buf) - start_offset);
  35146. #if 0
  35147. DUK_DDD(DUK_DDDPRINT("pc2line lookup: pc=%ld -> hdr_index=%ld, pc_base=%ld, n=%ld, start_offset=%ld",
  35148. (long) pc, (long) hdr_index, (long) pc_base, (long) n, (long) start_offset));
  35149. #endif
  35150. while (n > 0) {
  35151. #if 0
  35152. DUK_DDD(DUK_DDDPRINT("lookup: n=%ld, curr_line=%ld", (long) n, (long) curr_line));
  35153. #endif
  35154. if (duk_bd_decode_flag(bd_ctx)) {
  35155. if (duk_bd_decode_flag(bd_ctx)) {
  35156. if (duk_bd_decode_flag(bd_ctx)) {
  35157. /* 1 1 1 <32 bits> */
  35158. duk_uint_fast32_t t;
  35159. t = duk_bd_decode(bd_ctx, 16); /* workaround: max nbits = 24 now */
  35160. t = (t << 16) + duk_bd_decode(bd_ctx, 16);
  35161. curr_line = t;
  35162. } else {
  35163. /* 1 1 0 <8 bits> */
  35164. duk_uint_fast32_t t;
  35165. t = duk_bd_decode(bd_ctx, 8);
  35166. curr_line = curr_line + t - 0x80;
  35167. }
  35168. } else {
  35169. /* 1 0 <2 bits> */
  35170. duk_uint_fast32_t t;
  35171. t = duk_bd_decode(bd_ctx, 2);
  35172. curr_line = curr_line + t + 1;
  35173. }
  35174. } else {
  35175. /* 0: no change */
  35176. }
  35177. n--;
  35178. }
  35179. DUK_DDD(DUK_DDDPRINT("pc2line lookup result: pc %ld -> line %ld", (long) pc, (long) curr_line));
  35180. return curr_line;
  35181. error:
  35182. DUK_D(DUK_DPRINT("pc2line conversion failed for pc=%ld", (long) pc));
  35183. return 0;
  35184. }
  35185. DUK_INTERNAL duk_uint_fast32_t duk_hobject_pc2line_query(duk_context *ctx, duk_idx_t idx_func, duk_uint_fast32_t pc) {
  35186. duk_hbuffer_fixed *pc2line;
  35187. duk_uint_fast32_t line;
  35188. /* XXX: now that pc2line is used by the debugger quite heavily in
  35189. * checked execution, this should be optimized to avoid value stack
  35190. * and perhaps also implement some form of pc2line caching (see
  35191. * future work in debugger.rst).
  35192. */
  35193. duk_get_prop_stridx(ctx, idx_func, DUK_STRIDX_INT_PC2LINE);
  35194. pc2line = (duk_hbuffer_fixed *) duk_get_hbuffer(ctx, -1);
  35195. if (pc2line != NULL) {
  35196. DUK_ASSERT(!DUK_HBUFFER_HAS_DYNAMIC((duk_hbuffer *) pc2line));
  35197. line = duk__hobject_pc2line_query_raw((duk_hthread *) ctx, pc2line, (duk_uint_fast32_t) pc);
  35198. } else {
  35199. line = 0;
  35200. }
  35201. duk_pop(ctx);
  35202. return line;
  35203. }
  35204. #endif /* DUK_USE_PC2LINE */
  35205. #line 1 "duk_hobject_props.c"
  35206. /*
  35207. * Hobject property set/get functionality.
  35208. *
  35209. * This is very central functionality for size, performance, and compliance.
  35210. * It is also rather intricate; see hobject-algorithms.txt for discussion on
  35211. * the algorithms and memory-management.txt for discussion on refcounts and
  35212. * side effect issues.
  35213. *
  35214. * Notes:
  35215. *
  35216. * - It might be tempting to assert "refcount nonzero" for objects
  35217. * being operated on, but that's not always correct: objects with
  35218. * a zero refcount may be operated on by the refcount implementation
  35219. * (finalization) for instance. Hence, no refcount assertions are made.
  35220. *
  35221. * - Many operations (memory allocation, identifier operations, etc)
  35222. * may cause arbitrary side effects (e.g. through GC and finalization).
  35223. * These side effects may invalidate duk_tval pointers which point to
  35224. * areas subject to reallocation (like value stack). Heap objects
  35225. * themselves have stable pointers. Holding heap object pointers or
  35226. * duk_tval copies is not problematic with respect to side effects;
  35227. * care must be taken when holding and using argument duk_tval pointers.
  35228. *
  35229. * - If a finalizer is executed, it may operate on the the same object
  35230. * we're currently dealing with. For instance, the finalizer might
  35231. * delete a certain property which has already been looked up and
  35232. * confirmed to exist. Ideally finalizers would be disabled if GC
  35233. * happens during property access. At the moment property table realloc
  35234. * disables finalizers, and all DECREFs may cause arbitrary changes so
  35235. * handle DECREF carefully.
  35236. *
  35237. * - The order of operations for a DECREF matters. When DECREF is executed,
  35238. * the entire object graph must be consistent; note that a refzero may
  35239. * lead to a mark-and-sweep through a refcount finalizer.
  35240. */
  35241. /*
  35242. * XXX: array indices are mostly typed as duk_uint32_t here; duk_uarridx_t
  35243. * might be more appropriate.
  35244. */
  35245. /*
  35246. * XXX: duk_uint_fast32_t should probably be used in many places here.
  35247. */
  35248. /* include removed: duk_internal.h */
  35249. /*
  35250. * Local defines
  35251. */
  35252. #define DUK__NO_ARRAY_INDEX DUK_HSTRING_NO_ARRAY_INDEX
  35253. /* hash probe sequence */
  35254. #define DUK__HASH_INITIAL(hash,h_size) DUK_HOBJECT_HASH_INITIAL((hash),(h_size))
  35255. #define DUK__HASH_PROBE_STEP(hash) DUK_HOBJECT_HASH_PROBE_STEP((hash))
  35256. /* marker values for hash part */
  35257. #define DUK__HASH_UNUSED DUK_HOBJECT_HASHIDX_UNUSED
  35258. #define DUK__HASH_DELETED DUK_HOBJECT_HASHIDX_DELETED
  35259. /* valstack space that suffices for all local calls, including recursion
  35260. * of other than Duktape calls (getters etc)
  35261. */
  35262. #define DUK__VALSTACK_SPACE 10
  35263. /* valstack space allocated especially for proxy lookup which does a
  35264. * recursive property lookup
  35265. */
  35266. #define DUK__VALSTACK_PROXY_LOOKUP 20
  35267. /*
  35268. * Local prototypes
  35269. */
  35270. #define DUK__DESC_FLAG_PUSH_VALUE (1 << 0) /* push value to stack */
  35271. #define DUK__DESC_FLAG_IGNORE_PROTOLOOP (1 << 1) /* don't throw for prototype loop */
  35272. DUK_LOCAL_DECL duk_bool_t duk__check_arguments_map_for_get(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *temp_desc);
  35273. DUK_LOCAL_DECL void duk__check_arguments_map_for_put(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *temp_desc, duk_bool_t throw_flag);
  35274. DUK_LOCAL_DECL void duk__check_arguments_map_for_delete(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *temp_desc);
  35275. DUK_LOCAL_DECL duk_bool_t duk__handle_put_array_length_smaller(duk_hthread *thr, duk_hobject *obj, duk_uint32_t old_len, duk_uint32_t new_len, duk_bool_t force_flag, duk_uint32_t *out_result_len);
  35276. DUK_LOCAL_DECL duk_bool_t duk__handle_put_array_length(duk_hthread *thr, duk_hobject *obj);
  35277. DUK_LOCAL_DECL duk_bool_t duk__get_property_desc(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *out_desc, duk_small_uint_t flags);
  35278. DUK_LOCAL_DECL duk_bool_t duk__get_own_property_desc_raw(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_uint32_t arr_idx, duk_propdesc *out_desc, duk_small_uint_t flags);
  35279. DUK_LOCAL_DECL duk_bool_t duk__get_own_property_desc(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *out_desc, duk_small_uint_t flags);
  35280. /*
  35281. * Misc helpers
  35282. */
  35283. /* Convert a duk_tval number (caller checks) to a 32-bit index. Returns
  35284. * DUK__NO_ARRAY_INDEX if the number is not whole or not a valid array
  35285. * index.
  35286. */
  35287. /* XXX: for fastints, could use a variant which assumes a double duk_tval
  35288. * (and doesn't need to check for fastint again).
  35289. */
  35290. DUK_LOCAL duk_uint32_t duk__tval_number_to_arr_idx(duk_tval *tv) {
  35291. duk_double_t dbl;
  35292. duk_uint32_t idx;
  35293. DUK_ASSERT(tv != NULL);
  35294. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  35295. dbl = DUK_TVAL_GET_NUMBER(tv);
  35296. idx = (duk_uint32_t) dbl;
  35297. if ((duk_double_t) idx == dbl) {
  35298. /* Is whole and within 32 bit range. If the value happens to be 0xFFFFFFFF,
  35299. * it's not a valid array index but will then match DUK__NO_ARRAY_INDEX.
  35300. */
  35301. return idx;
  35302. }
  35303. return DUK__NO_ARRAY_INDEX;
  35304. }
  35305. #if defined(DUK_USE_FASTINT)
  35306. /* Convert a duk_tval fastint (caller checks) to a 32-bit index. */
  35307. DUK_LOCAL duk_uint32_t duk__tval_fastint_to_arr_idx(duk_tval *tv) {
  35308. duk_int64_t t;
  35309. DUK_ASSERT(tv != NULL);
  35310. DUK_ASSERT(DUK_TVAL_IS_FASTINT(tv));
  35311. t = DUK_TVAL_GET_FASTINT(tv);
  35312. if ((t & ~0xffffffffULL) != 0) {
  35313. /* Catches >0x100000000 and negative values. */
  35314. return DUK__NO_ARRAY_INDEX;
  35315. }
  35316. /* If the value happens to be 0xFFFFFFFF, it's not a valid array index
  35317. * but will then match DUK__NO_ARRAY_INDEX.
  35318. */
  35319. return (duk_uint32_t) t;
  35320. }
  35321. #endif /* DUK_USE_FASTINT */
  35322. /* Push an arbitrary duk_tval to the stack, coerce it to string, and return
  35323. * both a duk_hstring pointer and an array index (or DUK__NO_ARRAY_INDEX).
  35324. */
  35325. DUK_LOCAL duk_uint32_t duk__push_tval_to_hstring_arr_idx(duk_context *ctx, duk_tval *tv, duk_hstring **out_h) {
  35326. duk_uint32_t arr_idx;
  35327. duk_hstring *h;
  35328. DUK_ASSERT(ctx != NULL);
  35329. DUK_ASSERT(tv != NULL);
  35330. DUK_ASSERT(out_h != NULL);
  35331. duk_push_tval(ctx, tv);
  35332. duk_to_string(ctx, -1);
  35333. h = duk_get_hstring(ctx, -1);
  35334. DUK_ASSERT(h != NULL);
  35335. *out_h = h;
  35336. arr_idx = DUK_HSTRING_GET_ARRIDX_FAST(h);
  35337. return arr_idx;
  35338. }
  35339. /* String is an own (virtual) property of a lightfunc. */
  35340. DUK_LOCAL duk_bool_t duk__key_is_lightfunc_ownprop(duk_hthread *thr, duk_hstring *key) {
  35341. return (key == DUK_HTHREAD_STRING_LENGTH(thr) ||
  35342. key == DUK_HTHREAD_STRING_NAME(thr));
  35343. }
  35344. /*
  35345. * Helpers for managing property storage size
  35346. */
  35347. /* Get default hash part size for a certain entry part size. */
  35348. #if defined(DUK_USE_HOBJECT_HASH_PART)
  35349. DUK_LOCAL duk_uint32_t duk__get_default_h_size(duk_uint32_t e_size) {
  35350. DUK_ASSERT(e_size <= DUK_HOBJECT_MAX_PROPERTIES);
  35351. if (e_size >= DUK_HOBJECT_E_USE_HASH_LIMIT) {
  35352. duk_uint32_t res;
  35353. /* result: hash_prime(floor(1.2 * e_size)) */
  35354. res = duk_util_get_hash_prime(e_size + e_size / DUK_HOBJECT_H_SIZE_DIVISOR);
  35355. /* if fails, e_size will be zero = not an issue, except performance-wise */
  35356. DUK_ASSERT(res == 0 || res > e_size);
  35357. return res;
  35358. } else {
  35359. return 0;
  35360. }
  35361. }
  35362. #endif /* USE_PROP_HASH_PART */
  35363. /* Get minimum entry part growth for a certain size. */
  35364. DUK_LOCAL duk_uint32_t duk__get_min_grow_e(duk_uint32_t e_size) {
  35365. duk_uint32_t res;
  35366. DUK_ASSERT(e_size <= DUK_HOBJECT_MAX_PROPERTIES);
  35367. res = (e_size + DUK_HOBJECT_E_MIN_GROW_ADD) / DUK_HOBJECT_E_MIN_GROW_DIVISOR;
  35368. DUK_ASSERT(res >= 1); /* important for callers */
  35369. return res;
  35370. }
  35371. /* Get minimum array part growth for a certain size. */
  35372. DUK_LOCAL duk_uint32_t duk__get_min_grow_a(duk_uint32_t a_size) {
  35373. duk_uint32_t res;
  35374. DUK_ASSERT((duk_size_t) a_size <= DUK_HOBJECT_MAX_PROPERTIES);
  35375. res = (a_size + DUK_HOBJECT_A_MIN_GROW_ADD) / DUK_HOBJECT_A_MIN_GROW_DIVISOR;
  35376. DUK_ASSERT(res >= 1); /* important for callers */
  35377. return res;
  35378. }
  35379. /* Count actually used entry part entries (non-NULL keys). */
  35380. DUK_LOCAL duk_uint32_t duk__count_used_e_keys(duk_hthread *thr, duk_hobject *obj) {
  35381. duk_uint_fast32_t i;
  35382. duk_uint_fast32_t n = 0;
  35383. duk_hstring **e;
  35384. DUK_ASSERT(obj != NULL);
  35385. DUK_UNREF(thr);
  35386. e = DUK_HOBJECT_E_GET_KEY_BASE(thr->heap, obj);
  35387. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(obj); i++) {
  35388. if (*e++) {
  35389. n++;
  35390. }
  35391. }
  35392. return (duk_uint32_t) n;
  35393. }
  35394. /* Count actually used array part entries and array minimum size.
  35395. * NOTE: 'out_min_size' can be computed much faster by starting from the
  35396. * end and breaking out early when finding first used entry, but this is
  35397. * not needed now.
  35398. */
  35399. DUK_LOCAL void duk__compute_a_stats(duk_hthread *thr, duk_hobject *obj, duk_uint32_t *out_used, duk_uint32_t *out_min_size) {
  35400. duk_uint_fast32_t i;
  35401. duk_uint_fast32_t used = 0;
  35402. duk_uint_fast32_t highest_idx = (duk_uint_fast32_t) -1; /* see below */
  35403. duk_tval *a;
  35404. DUK_ASSERT(obj != NULL);
  35405. DUK_ASSERT(out_used != NULL);
  35406. DUK_ASSERT(out_min_size != NULL);
  35407. DUK_UNREF(thr);
  35408. a = DUK_HOBJECT_A_GET_BASE(thr->heap, obj);
  35409. for (i = 0; i < DUK_HOBJECT_GET_ASIZE(obj); i++) {
  35410. duk_tval *tv = a++;
  35411. if (!DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  35412. used++;
  35413. highest_idx = i;
  35414. }
  35415. }
  35416. /* Initial value for highest_idx is -1 coerced to unsigned. This
  35417. * is a bit odd, but (highest_idx + 1) will then wrap to 0 below
  35418. * for out_min_size as intended.
  35419. */
  35420. *out_used = used;
  35421. *out_min_size = highest_idx + 1; /* 0 if no used entries */
  35422. }
  35423. /* Check array density and indicate whether or not the array part should be abandoned. */
  35424. DUK_LOCAL duk_bool_t duk__abandon_array_density_check(duk_uint32_t a_used, duk_uint32_t a_size) {
  35425. /*
  35426. * Array abandon check; abandon if:
  35427. *
  35428. * new_used / new_size < limit
  35429. * new_used < limit * new_size || limit is 3 bits fixed point
  35430. * new_used < limit' / 8 * new_size || *8
  35431. * 8*new_used < limit' * new_size || :8
  35432. * new_used < limit' * (new_size / 8)
  35433. *
  35434. * Here, new_used = a_used, new_size = a_size.
  35435. *
  35436. * Note: some callers use approximate values for a_used and/or a_size
  35437. * (e.g. dropping a '+1' term). This doesn't affect the usefulness
  35438. * of the check, but may confuse debugging.
  35439. */
  35440. return (a_used < DUK_HOBJECT_A_ABANDON_LIMIT * (a_size >> 3));
  35441. }
  35442. /* Fast check for extending array: check whether or not a slow density check is required. */
  35443. DUK_LOCAL duk_bool_t duk__abandon_array_slow_check_required(duk_uint32_t arr_idx, duk_uint32_t old_size) {
  35444. /*
  35445. * In a fast check we assume old_size equals old_used (i.e., existing
  35446. * array is fully dense).
  35447. *
  35448. * Slow check if:
  35449. *
  35450. * (new_size - old_size) / old_size > limit
  35451. * new_size - old_size > limit * old_size
  35452. * new_size > (1 + limit) * old_size || limit' is 3 bits fixed point
  35453. * new_size > (1 + (limit' / 8)) * old_size || * 8
  35454. * 8 * new_size > (8 + limit') * old_size || : 8
  35455. * new_size > (8 + limit') * (old_size / 8)
  35456. * new_size > limit'' * (old_size / 8) || limit'' = 9 -> max 25% increase
  35457. * arr_idx + 1 > limit'' * (old_size / 8)
  35458. *
  35459. * This check doesn't work well for small values, so old_size is rounded
  35460. * up for the check (and the '+ 1' of arr_idx can be ignored in practice):
  35461. *
  35462. * arr_idx > limit'' * ((old_size + 7) / 8)
  35463. */
  35464. return (arr_idx > DUK_HOBJECT_A_FAST_RESIZE_LIMIT * ((old_size + 7) >> 3));
  35465. }
  35466. /*
  35467. * Proxy helpers
  35468. */
  35469. #if defined(DUK_USE_ES6_PROXY)
  35470. DUK_INTERNAL duk_bool_t duk_hobject_proxy_check(duk_hthread *thr, duk_hobject *obj, duk_hobject **out_target, duk_hobject **out_handler) {
  35471. duk_tval *tv_target;
  35472. duk_tval *tv_handler;
  35473. duk_hobject *h_target;
  35474. duk_hobject *h_handler;
  35475. DUK_ASSERT(thr != NULL);
  35476. DUK_ASSERT(obj != NULL);
  35477. DUK_ASSERT(out_target != NULL);
  35478. DUK_ASSERT(out_handler != NULL);
  35479. /* Caller doesn't need to check exotic proxy behavior (but does so for
  35480. * some fast paths).
  35481. */
  35482. if (DUK_LIKELY(!DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(obj))) {
  35483. return 0;
  35484. }
  35485. tv_handler = duk_hobject_find_existing_entry_tval_ptr(thr->heap, obj, DUK_HTHREAD_STRING_INT_HANDLER(thr));
  35486. if (!tv_handler) {
  35487. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REVOKED);
  35488. return 0;
  35489. }
  35490. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv_handler));
  35491. h_handler = DUK_TVAL_GET_OBJECT(tv_handler);
  35492. DUK_ASSERT(h_handler != NULL);
  35493. *out_handler = h_handler;
  35494. tv_handler = NULL; /* avoid issues with relocation */
  35495. tv_target = duk_hobject_find_existing_entry_tval_ptr(thr->heap, obj, DUK_HTHREAD_STRING_INT_TARGET(thr));
  35496. if (!tv_target) {
  35497. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REVOKED);
  35498. return 0;
  35499. }
  35500. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv_target));
  35501. h_target = DUK_TVAL_GET_OBJECT(tv_target);
  35502. DUK_ASSERT(h_target != NULL);
  35503. *out_target = h_target;
  35504. tv_target = NULL; /* avoid issues with relocation */
  35505. return 1;
  35506. }
  35507. #endif
  35508. #if defined(DUK_USE_ES6_PROXY)
  35509. DUK_LOCAL duk_bool_t duk__proxy_check_prop(duk_hthread *thr, duk_hobject *obj, duk_small_uint_t stridx_trap, duk_tval *tv_key, duk_hobject **out_target) {
  35510. duk_context *ctx = (duk_context *) thr;
  35511. duk_hobject *h_handler;
  35512. DUK_ASSERT(thr != NULL);
  35513. DUK_ASSERT(obj != NULL);
  35514. DUK_ASSERT(tv_key != NULL);
  35515. DUK_ASSERT(out_target != NULL);
  35516. if (!duk_hobject_proxy_check(thr, obj, out_target, &h_handler)) {
  35517. return 0;
  35518. }
  35519. DUK_ASSERT(*out_target != NULL);
  35520. DUK_ASSERT(h_handler != NULL);
  35521. /* XXX: At the moment Duktape accesses internal keys like _Finalizer using a
  35522. * normal property set/get which would allow a proxy handler to interfere with
  35523. * such behavior and to get access to internal key strings. This is not a problem
  35524. * as such because internal key strings can be created in other ways too (e.g.
  35525. * through buffers). The best fix is to change Duktape internal lookups to
  35526. * skip proxy behavior. Until that, internal property accesses bypass the
  35527. * proxy and are applied to the target (as if the handler did not exist).
  35528. * This has some side effects, see test-bi-proxy-internal-keys.js.
  35529. */
  35530. if (DUK_TVAL_IS_STRING(tv_key)) {
  35531. duk_hstring *h_key = (duk_hstring *) DUK_TVAL_GET_STRING(tv_key);
  35532. DUK_ASSERT(h_key != NULL);
  35533. if (DUK_HSTRING_HAS_INTERNAL(h_key)) {
  35534. DUK_DDD(DUK_DDDPRINT("internal key, skip proxy handler and apply to target"));
  35535. return 0;
  35536. }
  35537. }
  35538. /* The handler is looked up with a normal property lookup; it may be an
  35539. * accessor or the handler object itself may be a proxy object. If the
  35540. * handler is a proxy, we need to extend the valstack as we make a
  35541. * recursive proxy check without a function call in between (in fact
  35542. * there is no limit to the potential recursion here).
  35543. *
  35544. * (For sanity, proxy creation rejects another proxy object as either
  35545. * the handler or the target at the moment so recursive proxy cases
  35546. * are not realized now.)
  35547. */
  35548. /* XXX: C recursion limit if proxies are allowed as handler/target values */
  35549. duk_require_stack(ctx, DUK__VALSTACK_PROXY_LOOKUP);
  35550. duk_push_hobject(ctx, h_handler);
  35551. if (duk_get_prop_stridx(ctx, -1, stridx_trap)) {
  35552. /* -> [ ... handler trap ] */
  35553. duk_insert(ctx, -2); /* -> [ ... trap handler ] */
  35554. /* stack prepped for func call: [ ... trap handler ] */
  35555. return 1;
  35556. } else {
  35557. duk_pop_2(ctx);
  35558. return 0;
  35559. }
  35560. }
  35561. #endif /* DUK_USE_ES6_PROXY */
  35562. /*
  35563. * Reallocate property allocation, moving properties to the new allocation.
  35564. *
  35565. * Includes key compaction, rehashing, and can also optionally abandoning
  35566. * the array part, 'migrating' array entries into the beginning of the
  35567. * new entry part. Arguments are not validated here, so e.g. new_h_size
  35568. * MUST be a valid prime.
  35569. *
  35570. * There is no support for in-place reallocation or just compacting keys
  35571. * without resizing the property allocation. This is intentional to keep
  35572. * code size minimal.
  35573. *
  35574. * The implementation is relatively straightforward, except for the array
  35575. * abandonment process. Array abandonment requires that new string keys
  35576. * are interned, which may trigger GC. All keys interned so far must be
  35577. * reachable for GC at all times; valstack is used for that now.
  35578. *
  35579. * Also, a GC triggered during this reallocation process must not interfere
  35580. * with the object being resized. This is currently controlled by using
  35581. * heap->mark_and_sweep_base_flags to indicate that no finalizers will be
  35582. * executed (as they can affect ANY object) and no objects are compacted
  35583. * (it would suffice to protect this particular object only, though).
  35584. *
  35585. * Note: a non-checked variant would be nice but is a bit tricky to
  35586. * implement for the array abandonment process. It's easy for
  35587. * everything else.
  35588. *
  35589. * Note: because we need to potentially resize the valstack (as part
  35590. * of abandoning the array part), any tval pointers to the valstack
  35591. * will become invalid after this call.
  35592. */
  35593. DUK_LOCAL
  35594. void duk__realloc_props(duk_hthread *thr,
  35595. duk_hobject *obj,
  35596. duk_uint32_t new_e_size,
  35597. duk_uint32_t new_a_size,
  35598. duk_uint32_t new_h_size,
  35599. duk_bool_t abandon_array) {
  35600. duk_context *ctx = (duk_context *) thr;
  35601. #ifdef DUK_USE_MARK_AND_SWEEP
  35602. duk_small_uint_t prev_mark_and_sweep_base_flags;
  35603. #endif
  35604. duk_uint32_t new_alloc_size;
  35605. duk_uint32_t new_e_size_adjusted;
  35606. duk_uint8_t *new_p;
  35607. duk_hstring **new_e_k;
  35608. duk_propvalue *new_e_pv;
  35609. duk_uint8_t *new_e_f;
  35610. duk_tval *new_a;
  35611. duk_uint32_t *new_h;
  35612. duk_uint32_t new_e_next;
  35613. duk_uint_fast32_t i;
  35614. DUK_ASSERT(thr != NULL);
  35615. DUK_ASSERT(ctx != NULL);
  35616. DUK_ASSERT(obj != NULL);
  35617. DUK_ASSERT(!abandon_array || new_a_size == 0); /* if abandon_array, new_a_size must be 0 */
  35618. DUK_ASSERT(DUK_HOBJECT_GET_PROPS(thr->heap, obj) != NULL || (DUK_HOBJECT_GET_ESIZE(obj) == 0 && DUK_HOBJECT_GET_ASIZE(obj) == 0));
  35619. DUK_ASSERT(new_h_size == 0 || new_h_size >= new_e_size); /* required to guarantee success of rehashing,
  35620. * intentionally use unadjusted new_e_size
  35621. */
  35622. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  35623. /*
  35624. * Pre resize assertions.
  35625. */
  35626. #ifdef DUK_USE_ASSERTIONS
  35627. /* XXX: pre-checks (such as no duplicate keys) */
  35628. #endif
  35629. /*
  35630. * For property layout 1, tweak e_size to ensure that the whole entry
  35631. * part (key + val + flags) is a suitable multiple for alignment
  35632. * (platform specific).
  35633. *
  35634. * Property layout 2 does not require this tweaking and is preferred
  35635. * on low RAM platforms requiring alignment.
  35636. */
  35637. #if defined(DUK_USE_HOBJECT_LAYOUT_2) || defined(DUK_USE_HOBJECT_LAYOUT_3)
  35638. DUK_DDD(DUK_DDDPRINT("using layout 2 or 3, no need to pad e_size: %ld", (long) new_e_size));
  35639. new_e_size_adjusted = new_e_size;
  35640. #elif defined(DUK_USE_HOBJECT_LAYOUT_1) && (DUK_HOBJECT_ALIGN_TARGET == 1)
  35641. DUK_DDD(DUK_DDDPRINT("using layout 1, but no need to pad e_size: %ld", (long) new_e_size));
  35642. new_e_size_adjusted = new_e_size;
  35643. #elif defined(DUK_USE_HOBJECT_LAYOUT_1) && ((DUK_HOBJECT_ALIGN_TARGET == 4) || (DUK_HOBJECT_ALIGN_TARGET == 8))
  35644. new_e_size_adjusted = (new_e_size + DUK_HOBJECT_ALIGN_TARGET - 1) & (~(DUK_HOBJECT_ALIGN_TARGET - 1));
  35645. DUK_DDD(DUK_DDDPRINT("using layout 1, and alignment target is %ld, adjusted e_size: %ld -> %ld",
  35646. (long) DUK_HOBJECT_ALIGN_TARGET, (long) new_e_size, (long) new_e_size_adjusted));
  35647. DUK_ASSERT(new_e_size_adjusted >= new_e_size);
  35648. #else
  35649. #error invalid hobject layout defines
  35650. #endif
  35651. /*
  35652. * Debug logging after adjustment.
  35653. */
  35654. DUK_DDD(DUK_DDDPRINT("attempt to resize hobject %p props (%ld -> %ld bytes), from {p=%p,e_size=%ld,e_next=%ld,a_size=%ld,h_size=%ld} to "
  35655. "{e_size=%ld,a_size=%ld,h_size=%ld}, abandon_array=%ld, unadjusted new_e_size=%ld",
  35656. (void *) obj,
  35657. (long) DUK_HOBJECT_P_COMPUTE_SIZE(DUK_HOBJECT_GET_ESIZE(obj),
  35658. DUK_HOBJECT_GET_ASIZE(obj),
  35659. DUK_HOBJECT_GET_HSIZE(obj)),
  35660. (long) DUK_HOBJECT_P_COMPUTE_SIZE(new_e_size_adjusted, new_a_size, new_h_size),
  35661. (void *) DUK_HOBJECT_GET_PROPS(thr->heap, obj),
  35662. (long) DUK_HOBJECT_GET_ESIZE(obj),
  35663. (long) DUK_HOBJECT_GET_ENEXT(obj),
  35664. (long) DUK_HOBJECT_GET_ASIZE(obj),
  35665. (long) DUK_HOBJECT_GET_HSIZE(obj),
  35666. (long) new_e_size_adjusted,
  35667. (long) new_a_size,
  35668. (long) new_h_size,
  35669. (long) abandon_array,
  35670. (long) new_e_size));
  35671. /*
  35672. * Property count check. This is the only point where we ensure that
  35673. * we don't get more (allocated) property space that we can handle.
  35674. * There aren't hard limits as such, but some algorithms fail (e.g.
  35675. * finding next higher prime, selecting hash part size) if we get too
  35676. * close to the 4G property limit.
  35677. *
  35678. * Since this works based on allocation size (not actually used size),
  35679. * the limit is a bit approximate but good enough in practice.
  35680. */
  35681. if (new_e_size_adjusted + new_a_size > DUK_HOBJECT_MAX_PROPERTIES) {
  35682. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_OBJECT_PROPERTY_LIMIT);
  35683. }
  35684. /*
  35685. * Compute new alloc size and alloc new area.
  35686. *
  35687. * The new area is allocated as a dynamic buffer and placed into the
  35688. * valstack for reachability. The actual buffer is then detached at
  35689. * the end.
  35690. *
  35691. * Note: heap_mark_and_sweep_base_flags are altered here to ensure
  35692. * no-one touches this object while we're resizing and rehashing it.
  35693. * The flags must be reset on every exit path after it. Finalizers
  35694. * and compaction is prevented currently for all objects while it
  35695. * would be enough to restrict it only for the current object.
  35696. */
  35697. #ifdef DUK_USE_MARK_AND_SWEEP
  35698. prev_mark_and_sweep_base_flags = thr->heap->mark_and_sweep_base_flags;
  35699. thr->heap->mark_and_sweep_base_flags |=
  35700. DUK_MS_FLAG_NO_FINALIZERS | /* avoid attempts to add/remove object keys */
  35701. DUK_MS_FLAG_NO_OBJECT_COMPACTION; /* avoid attempt to compact the current object */
  35702. #endif
  35703. new_alloc_size = DUK_HOBJECT_P_COMPUTE_SIZE(new_e_size_adjusted, new_a_size, new_h_size);
  35704. DUK_DDD(DUK_DDDPRINT("new hobject allocation size is %ld", (long) new_alloc_size));
  35705. if (new_alloc_size == 0) {
  35706. /* for zero size, don't push anything on valstack */
  35707. DUK_ASSERT(new_e_size_adjusted == 0);
  35708. DUK_ASSERT(new_a_size == 0);
  35709. DUK_ASSERT(new_h_size == 0);
  35710. new_p = NULL;
  35711. } else {
  35712. /* This may trigger mark-and-sweep with arbitrary side effects,
  35713. * including an attempted resize of the object we're resizing,
  35714. * executing a finalizer which may add or remove properties of
  35715. * the object we're resizing etc.
  35716. */
  35717. /* Note: buffer is dynamic so that we can 'steal' the actual
  35718. * allocation later.
  35719. */
  35720. new_p = (duk_uint8_t *) duk_push_dynamic_buffer(ctx, new_alloc_size); /* errors out if out of memory */
  35721. DUK_ASSERT(new_p != NULL); /* since new_alloc_size > 0 */
  35722. }
  35723. /* Set up pointers to the new property area: this is hidden behind a macro
  35724. * because it is memory layout specific.
  35725. */
  35726. DUK_HOBJECT_P_SET_REALLOC_PTRS(new_p, new_e_k, new_e_pv, new_e_f, new_a, new_h,
  35727. new_e_size_adjusted, new_a_size, new_h_size);
  35728. DUK_UNREF(new_h); /* happens when hash part dropped */
  35729. new_e_next = 0;
  35730. /* if new_p == NULL, all of these pointers are NULL */
  35731. DUK_ASSERT((new_p != NULL) ||
  35732. (new_e_k == NULL && new_e_pv == NULL && new_e_f == NULL &&
  35733. new_a == NULL && new_h == NULL));
  35734. DUK_DDD(DUK_DDDPRINT("new alloc size %ld, new_e_k=%p, new_e_pv=%p, new_e_f=%p, new_a=%p, new_h=%p",
  35735. (long) new_alloc_size, (void *) new_e_k, (void *) new_e_pv, (void *) new_e_f,
  35736. (void *) new_a, (void *) new_h));
  35737. /*
  35738. * Migrate array to start of entries if requested.
  35739. *
  35740. * Note: from an enumeration perspective the order of entry keys matters.
  35741. * Array keys should appear wherever they appeared before the array abandon
  35742. * operation.
  35743. */
  35744. if (abandon_array) {
  35745. /*
  35746. * Note: assuming new_a_size == 0, and that entry part contains
  35747. * no conflicting keys, refcounts do not need to be adjusted for
  35748. * the values, as they remain exactly the same.
  35749. *
  35750. * The keys, however, need to be interned, incref'd, and be
  35751. * reachable for GC. Any intern attempt may trigger a GC and
  35752. * claim any non-reachable strings, so every key must be reachable
  35753. * at all times.
  35754. *
  35755. * A longjmp must not occur here, as the new_p allocation would
  35756. * be freed without these keys being decref'd, hence the messy
  35757. * decref handling if intern fails.
  35758. */
  35759. DUK_ASSERT(new_a_size == 0);
  35760. for (i = 0; i < DUK_HOBJECT_GET_ASIZE(obj); i++) {
  35761. duk_tval *tv1;
  35762. duk_tval *tv2;
  35763. duk_hstring *key;
  35764. DUK_ASSERT(DUK_HOBJECT_GET_PROPS(thr->heap, obj) != NULL);
  35765. tv1 = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, i);
  35766. if (DUK_TVAL_IS_UNDEFINED_UNUSED(tv1)) {
  35767. continue;
  35768. }
  35769. DUK_ASSERT(new_p != NULL && new_e_k != NULL &&
  35770. new_e_pv != NULL && new_e_f != NULL);
  35771. /*
  35772. * Intern key via the valstack to ensure reachability behaves
  35773. * properly. We must avoid longjmp's here so use non-checked
  35774. * primitives.
  35775. *
  35776. * Note: duk_check_stack() potentially reallocs the valstack,
  35777. * invalidating any duk_tval pointers to valstack. Callers
  35778. * must be careful.
  35779. */
  35780. /* never shrinks; auto-adds DUK_VALSTACK_INTERNAL_EXTRA, which is generous */
  35781. if (!duk_check_stack(ctx, 1)) {
  35782. goto abandon_error;
  35783. }
  35784. DUK_ASSERT_VALSTACK_SPACE(thr, 1);
  35785. key = duk_heap_string_intern_u32(thr->heap, i);
  35786. if (!key) {
  35787. goto abandon_error;
  35788. }
  35789. duk_push_hstring(ctx, key); /* keep key reachable for GC etc; guaranteed not to fail */
  35790. /* key is now reachable in the valstack */
  35791. DUK_HSTRING_INCREF(thr, key); /* second incref for the entry reference */
  35792. new_e_k[new_e_next] = key;
  35793. tv2 = &new_e_pv[new_e_next].v; /* array entries are all plain values */
  35794. DUK_TVAL_SET_TVAL(tv2, tv1);
  35795. new_e_f[new_e_next] = DUK_PROPDESC_FLAG_WRITABLE |
  35796. DUK_PROPDESC_FLAG_ENUMERABLE |
  35797. DUK_PROPDESC_FLAG_CONFIGURABLE;
  35798. new_e_next++;
  35799. /* Note: new_e_next matches pushed temp key count, and nothing can
  35800. * fail above between the push and this point.
  35801. */
  35802. }
  35803. DUK_DDD(DUK_DDDPRINT("abandon array: pop %ld key temps from valstack", (long) new_e_next));
  35804. duk_pop_n(ctx, new_e_next);
  35805. }
  35806. /*
  35807. * Copy keys and values in the entry part (compacting them at the same time).
  35808. */
  35809. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(obj); i++) {
  35810. duk_hstring *key;
  35811. DUK_ASSERT(DUK_HOBJECT_GET_PROPS(thr->heap, obj) != NULL);
  35812. key = DUK_HOBJECT_E_GET_KEY(thr->heap, obj, i);
  35813. if (!key) {
  35814. continue;
  35815. }
  35816. DUK_ASSERT(new_p != NULL && new_e_k != NULL &&
  35817. new_e_pv != NULL && new_e_f != NULL);
  35818. new_e_k[new_e_next] = key;
  35819. new_e_pv[new_e_next] = DUK_HOBJECT_E_GET_VALUE(thr->heap, obj, i);
  35820. new_e_f[new_e_next] = DUK_HOBJECT_E_GET_FLAGS(thr->heap, obj, i);
  35821. new_e_next++;
  35822. }
  35823. /* the entries [new_e_next, new_e_size_adjusted[ are left uninitialized on purpose (ok, not gc reachable) */
  35824. /*
  35825. * Copy array elements to new array part.
  35826. */
  35827. if (new_a_size > DUK_HOBJECT_GET_ASIZE(obj)) {
  35828. /* copy existing entries as is */
  35829. DUK_ASSERT(new_p != NULL && new_a != NULL);
  35830. if (DUK_HOBJECT_GET_ASIZE(obj) > 0) {
  35831. /* Avoid zero copy with an invalid pointer. If obj->p is NULL,
  35832. * the 'new_a' pointer will be invalid which is not allowed even
  35833. * when copy size is zero.
  35834. */
  35835. DUK_ASSERT(DUK_HOBJECT_GET_PROPS(thr->heap, obj) != NULL);
  35836. DUK_ASSERT(DUK_HOBJECT_GET_ASIZE(obj) > 0);
  35837. DUK_MEMCPY((void *) new_a, (void *) DUK_HOBJECT_A_GET_BASE(thr->heap, obj), sizeof(duk_tval) * DUK_HOBJECT_GET_ASIZE(obj));
  35838. }
  35839. /* fill new entries with -unused- (required, gc reachable) */
  35840. for (i = DUK_HOBJECT_GET_ASIZE(obj); i < new_a_size; i++) {
  35841. duk_tval *tv = &new_a[i];
  35842. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  35843. }
  35844. } else {
  35845. #ifdef DUK_USE_ASSERTIONS
  35846. /* caller must have decref'd values above new_a_size (if that is necessary) */
  35847. if (!abandon_array) {
  35848. for (i = new_a_size; i < DUK_HOBJECT_GET_ASIZE(obj); i++) {
  35849. duk_tval *tv;
  35850. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, i);
  35851. /* current assertion is quite strong: decref's and set to unused */
  35852. DUK_ASSERT(DUK_TVAL_IS_UNDEFINED_UNUSED(tv));
  35853. }
  35854. }
  35855. #endif
  35856. if (new_a_size > 0) {
  35857. /* Avoid zero copy with an invalid pointer. If obj->p is NULL,
  35858. * the 'new_a' pointer will be invalid which is not allowed even
  35859. * when copy size is zero.
  35860. */
  35861. DUK_ASSERT(DUK_HOBJECT_GET_PROPS(thr->heap, obj) != NULL);
  35862. DUK_ASSERT(new_a_size > 0);
  35863. DUK_MEMCPY((void *) new_a, (void *) DUK_HOBJECT_A_GET_BASE(thr->heap, obj), sizeof(duk_tval) * new_a_size);
  35864. }
  35865. }
  35866. /*
  35867. * Rebuild the hash part always from scratch (guaranteed to finish).
  35868. *
  35869. * Any resize of hash part requires rehashing. In addition, by rehashing
  35870. * get rid of any elements marked deleted (DUK__HASH_DELETED) which is critical
  35871. * to ensuring the hash part never fills up.
  35872. */
  35873. #if defined(DUK_USE_HOBJECT_HASH_PART)
  35874. if (DUK_UNLIKELY(new_h_size > 0)) {
  35875. DUK_ASSERT(new_h != NULL);
  35876. /* fill new_h with u32 0xff = UNUSED */
  35877. DUK_ASSERT(DUK_HOBJECT_GET_PROPS(thr->heap, obj) != NULL);
  35878. DUK_ASSERT(new_h_size > 0);
  35879. DUK_MEMSET(new_h, 0xff, sizeof(duk_uint32_t) * new_h_size);
  35880. DUK_ASSERT(new_e_next <= new_h_size); /* equality not actually possible */
  35881. for (i = 0; i < new_e_next; i++) {
  35882. duk_hstring *key = new_e_k[i];
  35883. duk_uint32_t j, step;
  35884. DUK_ASSERT(key != NULL);
  35885. j = DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(key), new_h_size);
  35886. step = DUK__HASH_PROBE_STEP(DUK_HSTRING_GET_HASH(key));
  35887. for (;;) {
  35888. DUK_ASSERT(new_h[j] != DUK__HASH_DELETED); /* should never happen */
  35889. if (new_h[j] == DUK__HASH_UNUSED) {
  35890. DUK_DDD(DUK_DDDPRINT("rebuild hit %ld -> %ld", (long) j, (long) i));
  35891. new_h[j] = i;
  35892. break;
  35893. }
  35894. DUK_DDD(DUK_DDDPRINT("rebuild miss %ld, step %ld", (long) j, (long) step));
  35895. j = (j + step) % new_h_size;
  35896. /* guaranteed to finish */
  35897. DUK_ASSERT(j != (duk_uint32_t) DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(key), new_h_size));
  35898. }
  35899. }
  35900. } else {
  35901. DUK_DDD(DUK_DDDPRINT("no hash part, no rehash"));
  35902. }
  35903. #endif /* DUK_USE_HOBJECT_HASH_PART */
  35904. /*
  35905. * Nice debug log.
  35906. */
  35907. DUK_DD(DUK_DDPRINT("resized hobject %p props (%ld -> %ld bytes), from {p=%p,e_size=%ld,e_next=%ld,a_size=%ld,h_size=%ld} to "
  35908. "{p=%p,e_size=%ld,e_next=%ld,a_size=%ld,h_size=%ld}, abandon_array=%ld, unadjusted new_e_size=%ld",
  35909. (void *) obj,
  35910. (long) DUK_HOBJECT_P_COMPUTE_SIZE(DUK_HOBJECT_GET_ESIZE(obj),
  35911. DUK_HOBJECT_GET_ASIZE(obj),
  35912. DUK_HOBJECT_GET_HSIZE(obj)),
  35913. (long) new_alloc_size,
  35914. (void *) DUK_HOBJECT_GET_PROPS(thr->heap, obj),
  35915. (long) DUK_HOBJECT_GET_ESIZE(obj),
  35916. (long) DUK_HOBJECT_GET_ENEXT(obj),
  35917. (long) DUK_HOBJECT_GET_ASIZE(obj),
  35918. (long) DUK_HOBJECT_GET_HSIZE(obj),
  35919. (void *) new_p,
  35920. (long) new_e_size_adjusted,
  35921. (long) new_e_next,
  35922. (long) new_a_size,
  35923. (long) new_h_size,
  35924. (long) abandon_array,
  35925. (long) new_e_size));
  35926. /*
  35927. * All done, switch properties ('p') allocation to new one.
  35928. */
  35929. DUK_FREE(thr->heap, DUK_HOBJECT_GET_PROPS(thr->heap, obj)); /* NULL obj->p is OK */
  35930. DUK_HOBJECT_SET_PROPS(thr->heap, obj, new_p);
  35931. DUK_HOBJECT_SET_ESIZE(obj, new_e_size_adjusted);
  35932. DUK_HOBJECT_SET_ENEXT(obj, new_e_next);
  35933. DUK_HOBJECT_SET_ASIZE(obj, new_a_size);
  35934. DUK_HOBJECT_SET_HSIZE(obj, new_h_size);
  35935. if (new_p) {
  35936. /*
  35937. * Detach actual buffer from dynamic buffer in valstack, and
  35938. * pop it from the stack.
  35939. *
  35940. * XXX: the buffer object is certainly not reachable at this point,
  35941. * so it would be nice to free it forcibly even with only
  35942. * mark-and-sweep enabled. Not a big issue though.
  35943. */
  35944. duk_hbuffer_dynamic *buf;
  35945. DUK_ASSERT(new_alloc_size > 0);
  35946. DUK_ASSERT(duk_is_buffer(ctx, -1));
  35947. buf = (duk_hbuffer_dynamic *) duk_require_hbuffer(ctx, -1);
  35948. DUK_ASSERT(buf != NULL);
  35949. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(buf));
  35950. DUK_HBUFFER_DYNAMIC_SET_DATA_PTR_NULL(thr->heap, buf);
  35951. DUK_HBUFFER_DYNAMIC_SET_SIZE(buf, 0); /* these size resets are not strictly necessary, but nice for consistency */
  35952. DUK_HBUFFER_DYNAMIC_SET_ALLOC_SIZE(buf, 0);
  35953. duk_pop(ctx);
  35954. } else {
  35955. DUK_ASSERT(new_alloc_size == 0);
  35956. /* no need to pop, nothing was pushed */
  35957. }
  35958. /* clear array part flag only after switching */
  35959. if (abandon_array) {
  35960. DUK_HOBJECT_CLEAR_ARRAY_PART(obj);
  35961. }
  35962. DUK_DDD(DUK_DDDPRINT("resize result: %!O", (duk_heaphdr *) obj));
  35963. #ifdef DUK_USE_MARK_AND_SWEEP
  35964. thr->heap->mark_and_sweep_base_flags = prev_mark_and_sweep_base_flags;
  35965. #endif
  35966. /*
  35967. * Post resize assertions.
  35968. */
  35969. #ifdef DUK_USE_ASSERTIONS
  35970. /* XXX: post-checks (such as no duplicate keys) */
  35971. #endif
  35972. return;
  35973. /*
  35974. * Abandon array failed, need to decref keys already inserted
  35975. * into the beginning of new_e_k before unwinding valstack.
  35976. */
  35977. abandon_error:
  35978. DUK_D(DUK_DPRINT("hobject resize failed during abandon array, decref keys"));
  35979. i = new_e_next;
  35980. while (i > 0) {
  35981. i--;
  35982. DUK_ASSERT(new_e_k != NULL);
  35983. DUK_ASSERT(new_e_k[i] != NULL);
  35984. DUK_HSTRING_DECREF(thr, new_e_k[i]);
  35985. }
  35986. #ifdef DUK_USE_MARK_AND_SWEEP
  35987. thr->heap->mark_and_sweep_base_flags = prev_mark_and_sweep_base_flags;
  35988. #endif
  35989. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_OBJECT_RESIZE_FAILED);
  35990. }
  35991. /*
  35992. * Helpers to resize properties allocation on specific needs.
  35993. */
  35994. /* Grow entry part allocation for one additional entry. */
  35995. DUK_LOCAL void duk__grow_props_for_new_entry_item(duk_hthread *thr, duk_hobject *obj) {
  35996. duk_uint32_t old_e_used; /* actually used, non-NULL entries */
  35997. duk_uint32_t new_e_size;
  35998. duk_uint32_t new_a_size;
  35999. duk_uint32_t new_h_size;
  36000. DUK_ASSERT(thr != NULL);
  36001. DUK_ASSERT(obj != NULL);
  36002. /* Duktape 0.11.0 and prior tried to optimize the resize by not
  36003. * counting the number of actually used keys prior to the resize.
  36004. * This worked mostly well but also caused weird leak-like behavior
  36005. * as in: test-bug-object-prop-alloc-unbounded.js. So, now we count
  36006. * the keys explicitly to compute the new entry part size.
  36007. */
  36008. old_e_used = duk__count_used_e_keys(thr, obj);
  36009. new_e_size = old_e_used + duk__get_min_grow_e(old_e_used);
  36010. #if defined(DUK_USE_HOBJECT_HASH_PART)
  36011. new_h_size = duk__get_default_h_size(new_e_size);
  36012. #else
  36013. new_h_size = 0;
  36014. #endif
  36015. new_a_size = DUK_HOBJECT_GET_ASIZE(obj);
  36016. DUK_ASSERT(new_e_size >= old_e_used + 1); /* duk__get_min_grow_e() is always >= 1 */
  36017. duk__realloc_props(thr, obj, new_e_size, new_a_size, new_h_size, 0);
  36018. }
  36019. /* Grow array part for a new highest array index. */
  36020. DUK_LOCAL void duk__grow_props_for_array_item(duk_hthread *thr, duk_hobject *obj, duk_uint32_t highest_arr_idx) {
  36021. duk_uint32_t new_e_size;
  36022. duk_uint32_t new_a_size;
  36023. duk_uint32_t new_h_size;
  36024. DUK_ASSERT(thr != NULL);
  36025. DUK_ASSERT(obj != NULL);
  36026. DUK_ASSERT(highest_arr_idx >= DUK_HOBJECT_GET_ASIZE(obj));
  36027. /* minimum new length is highest_arr_idx + 1 */
  36028. new_e_size = DUK_HOBJECT_GET_ESIZE(obj);
  36029. new_h_size = DUK_HOBJECT_GET_HSIZE(obj);
  36030. new_a_size = highest_arr_idx + duk__get_min_grow_a(highest_arr_idx);
  36031. DUK_ASSERT(new_a_size >= highest_arr_idx + 1); /* duk__get_min_grow_a() is always >= 1 */
  36032. duk__realloc_props(thr, obj, new_e_size, new_a_size, new_h_size, 0);
  36033. }
  36034. /* Abandon array part, moving array entries into entries part.
  36035. * This requires a props resize, which is a heavy operation.
  36036. * We also compact the entries part while we're at it, although
  36037. * this is not strictly required.
  36038. */
  36039. DUK_LOCAL void duk__abandon_array_checked(duk_hthread *thr, duk_hobject *obj) {
  36040. duk_uint32_t new_e_size;
  36041. duk_uint32_t new_a_size;
  36042. duk_uint32_t new_h_size;
  36043. duk_uint32_t e_used; /* actually used, non-NULL keys */
  36044. duk_uint32_t a_used;
  36045. duk_uint32_t a_size;
  36046. DUK_ASSERT(thr != NULL);
  36047. DUK_ASSERT(obj != NULL);
  36048. e_used = duk__count_used_e_keys(thr, obj);
  36049. duk__compute_a_stats(thr, obj, &a_used, &a_size);
  36050. /*
  36051. * Must guarantee all actually used array entries will fit into
  36052. * new entry part. Add one growth step to ensure we don't run out
  36053. * of space right away.
  36054. */
  36055. new_e_size = e_used + a_used;
  36056. new_e_size = new_e_size + duk__get_min_grow_e(new_e_size);
  36057. new_a_size = 0;
  36058. #if defined(DUK_USE_HOBJECT_HASH_PART)
  36059. new_h_size = duk__get_default_h_size(new_e_size);
  36060. #else
  36061. new_h_size = 0;
  36062. #endif
  36063. DUK_DD(DUK_DDPRINT("abandon array part for hobject %p, "
  36064. "array stats before: e_used=%ld, a_used=%ld, a_size=%ld; "
  36065. "resize to e_size=%ld, a_size=%ld, h_size=%ld",
  36066. (void *) obj, (long) e_used, (long) a_used, (long) a_size,
  36067. (long) new_e_size, (long) new_a_size, (long) new_h_size));
  36068. duk__realloc_props(thr, obj, new_e_size, new_a_size, new_h_size, 1);
  36069. }
  36070. /*
  36071. * Compact an object. Minimizes allocation size for objects which are
  36072. * not likely to be extended. This is useful for internal and non-
  36073. * extensible objects, but can also be called for non-extensible objects.
  36074. * May abandon the array part if it is computed to be too sparse.
  36075. *
  36076. * This call is relatively expensive, as it needs to scan both the
  36077. * entries and the array part.
  36078. *
  36079. * The call may fail due to allocation error.
  36080. */
  36081. DUK_INTERNAL void duk_hobject_compact_props(duk_hthread *thr, duk_hobject *obj) {
  36082. duk_uint32_t e_size; /* currently used -> new size */
  36083. duk_uint32_t a_size; /* currently required */
  36084. duk_uint32_t a_used; /* actually used */
  36085. duk_uint32_t h_size;
  36086. duk_bool_t abandon_array;
  36087. DUK_ASSERT(thr != NULL);
  36088. DUK_ASSERT(obj != NULL);
  36089. e_size = duk__count_used_e_keys(thr, obj);
  36090. duk__compute_a_stats(thr, obj, &a_used, &a_size);
  36091. DUK_DD(DUK_DDPRINT("compacting hobject, used e keys %ld, used a keys %ld, min a size %ld, "
  36092. "resized array density would be: %ld/%ld = %lf",
  36093. (long) e_size, (long) a_used, (long) a_size,
  36094. (long) a_used, (long) a_size,
  36095. (double) a_used / (double) a_size));
  36096. if (duk__abandon_array_density_check(a_used, a_size)) {
  36097. DUK_DD(DUK_DDPRINT("decided to abandon array during compaction, a_used=%ld, a_size=%ld",
  36098. (long) a_used, (long) a_size));
  36099. abandon_array = 1;
  36100. e_size += a_used;
  36101. a_size = 0;
  36102. } else {
  36103. DUK_DD(DUK_DDPRINT("decided to keep array during compaction"));
  36104. abandon_array = 0;
  36105. }
  36106. #if defined(DUK_USE_HOBJECT_HASH_PART)
  36107. if (e_size >= DUK_HOBJECT_E_USE_HASH_LIMIT) {
  36108. h_size = duk__get_default_h_size(e_size);
  36109. } else {
  36110. h_size = 0;
  36111. }
  36112. #else
  36113. h_size = 0;
  36114. #endif
  36115. DUK_DD(DUK_DDPRINT("compacting hobject -> new e_size %ld, new a_size=%ld, new h_size=%ld, abandon_array=%ld",
  36116. (long) e_size, (long) a_size, (long) h_size, (long) abandon_array));
  36117. duk__realloc_props(thr, obj, e_size, a_size, h_size, abandon_array);
  36118. }
  36119. /*
  36120. * Find an existing key from entry part either by linear scan or by
  36121. * using the hash index (if it exists).
  36122. *
  36123. * Sets entry index (and possibly the hash index) to output variables,
  36124. * which allows the caller to update the entry and hash entries in-place.
  36125. * If entry is not found, both values are set to -1. If entry is found
  36126. * but there is no hash part, h_idx is set to -1.
  36127. */
  36128. DUK_INTERNAL void duk_hobject_find_existing_entry(duk_heap *heap, duk_hobject *obj, duk_hstring *key, duk_int_t *e_idx, duk_int_t *h_idx) {
  36129. DUK_ASSERT(obj != NULL);
  36130. DUK_ASSERT(key != NULL);
  36131. DUK_ASSERT(e_idx != NULL);
  36132. DUK_ASSERT(h_idx != NULL);
  36133. DUK_UNREF(heap);
  36134. if (DUK_LIKELY(DUK_HOBJECT_GET_HSIZE(obj) == 0))
  36135. {
  36136. /* Linear scan: more likely because most objects are small.
  36137. * This is an important fast path.
  36138. *
  36139. * XXX: this might be worth inlining for property lookups.
  36140. */
  36141. duk_uint_fast32_t i;
  36142. duk_uint_fast32_t n;
  36143. duk_hstring **h_keys_base;
  36144. DUK_DDD(DUK_DDDPRINT("duk_hobject_find_existing_entry() using linear scan for lookup"));
  36145. h_keys_base = DUK_HOBJECT_E_GET_KEY_BASE(heap, obj);
  36146. n = DUK_HOBJECT_GET_ENEXT(obj);
  36147. for (i = 0; i < n; i++) {
  36148. if (h_keys_base[i] == key) {
  36149. *e_idx = i;
  36150. *h_idx = -1;
  36151. return;
  36152. }
  36153. }
  36154. }
  36155. #if defined(DUK_USE_HOBJECT_HASH_PART)
  36156. else
  36157. {
  36158. /* hash lookup */
  36159. duk_uint32_t n;
  36160. duk_uint32_t i, step;
  36161. duk_uint32_t *h_base;
  36162. DUK_DDD(DUK_DDDPRINT("duk_hobject_find_existing_entry() using hash part for lookup"));
  36163. h_base = DUK_HOBJECT_H_GET_BASE(heap, obj);
  36164. n = DUK_HOBJECT_GET_HSIZE(obj);
  36165. i = DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(key), n);
  36166. step = DUK__HASH_PROBE_STEP(DUK_HSTRING_GET_HASH(key));
  36167. for (;;) {
  36168. duk_uint32_t t;
  36169. DUK_ASSERT_DISABLE(i >= 0); /* unsigned */
  36170. DUK_ASSERT(i < DUK_HOBJECT_GET_HSIZE(obj));
  36171. t = h_base[i];
  36172. DUK_ASSERT(t == DUK__HASH_UNUSED || t == DUK__HASH_DELETED ||
  36173. (t < DUK_HOBJECT_GET_ESIZE(obj))); /* t >= 0 always true, unsigned */
  36174. if (t == DUK__HASH_UNUSED) {
  36175. break;
  36176. } else if (t == DUK__HASH_DELETED) {
  36177. DUK_DDD(DUK_DDDPRINT("lookup miss (deleted) i=%ld, t=%ld",
  36178. (long) i, (long) t));
  36179. } else {
  36180. DUK_ASSERT(t < DUK_HOBJECT_GET_ESIZE(obj));
  36181. if (DUK_HOBJECT_E_GET_KEY(heap, obj, t) == key) {
  36182. DUK_DDD(DUK_DDDPRINT("lookup hit i=%ld, t=%ld -> key %p",
  36183. (long) i, (long) t, (void *) key));
  36184. *e_idx = t;
  36185. *h_idx = i;
  36186. return;
  36187. }
  36188. DUK_DDD(DUK_DDDPRINT("lookup miss i=%ld, t=%ld",
  36189. (long) i, (long) t));
  36190. }
  36191. i = (i + step) % n;
  36192. /* guaranteed to finish, as hash is never full */
  36193. DUK_ASSERT(i != (duk_uint32_t) DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(key), n));
  36194. }
  36195. }
  36196. #endif /* DUK_USE_HOBJECT_HASH_PART */
  36197. /* not found */
  36198. *e_idx = -1;
  36199. *h_idx = -1;
  36200. }
  36201. /* For internal use: get non-accessor entry value */
  36202. DUK_INTERNAL duk_tval *duk_hobject_find_existing_entry_tval_ptr(duk_heap *heap, duk_hobject *obj, duk_hstring *key) {
  36203. duk_int_t e_idx;
  36204. duk_int_t h_idx;
  36205. DUK_ASSERT(obj != NULL);
  36206. DUK_ASSERT(key != NULL);
  36207. DUK_UNREF(heap);
  36208. duk_hobject_find_existing_entry(heap, obj, key, &e_idx, &h_idx);
  36209. if (e_idx >= 0 && !DUK_HOBJECT_E_SLOT_IS_ACCESSOR(heap, obj, e_idx)) {
  36210. return DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(heap, obj, e_idx);
  36211. } else {
  36212. return NULL;
  36213. }
  36214. }
  36215. /* For internal use: get non-accessor entry value and attributes */
  36216. DUK_INTERNAL duk_tval *duk_hobject_find_existing_entry_tval_ptr_and_attrs(duk_heap *heap, duk_hobject *obj, duk_hstring *key, duk_int_t *out_attrs) {
  36217. duk_int_t e_idx;
  36218. duk_int_t h_idx;
  36219. DUK_ASSERT(obj != NULL);
  36220. DUK_ASSERT(key != NULL);
  36221. DUK_ASSERT(out_attrs != NULL);
  36222. DUK_UNREF(heap);
  36223. duk_hobject_find_existing_entry(heap, obj, key, &e_idx, &h_idx);
  36224. if (e_idx >= 0 && !DUK_HOBJECT_E_SLOT_IS_ACCESSOR(heap, obj, e_idx)) {
  36225. *out_attrs = DUK_HOBJECT_E_GET_FLAGS(heap, obj, e_idx);
  36226. return DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(heap, obj, e_idx);
  36227. } else {
  36228. *out_attrs = 0;
  36229. return NULL;
  36230. }
  36231. }
  36232. /* For internal use: get array part value */
  36233. DUK_INTERNAL duk_tval *duk_hobject_find_existing_array_entry_tval_ptr(duk_heap *heap, duk_hobject *obj, duk_uarridx_t i) {
  36234. duk_tval *tv;
  36235. DUK_ASSERT(obj != NULL);
  36236. DUK_UNREF(heap);
  36237. if (!DUK_HOBJECT_HAS_ARRAY_PART(obj)) {
  36238. return NULL;
  36239. }
  36240. if (i >= DUK_HOBJECT_GET_ASIZE(obj)) {
  36241. return NULL;
  36242. }
  36243. tv = DUK_HOBJECT_A_GET_VALUE_PTR(heap, obj, i);
  36244. return tv;
  36245. }
  36246. /*
  36247. * Allocate and initialize a new entry, resizing the properties allocation
  36248. * if necessary. Returns entry index (e_idx) or throws an error if alloc fails.
  36249. *
  36250. * Sets the key of the entry (increasing the key's refcount), and updates
  36251. * the hash part if it exists. Caller must set value and flags, and update
  36252. * the entry value refcount. A decref for the previous value is not necessary.
  36253. */
  36254. DUK_LOCAL duk_bool_t duk__alloc_entry_checked(duk_hthread *thr, duk_hobject *obj, duk_hstring *key) {
  36255. duk_uint32_t idx;
  36256. DUK_ASSERT(thr != NULL);
  36257. DUK_ASSERT(obj != NULL);
  36258. DUK_ASSERT(key != NULL);
  36259. DUK_ASSERT(DUK_HOBJECT_GET_ENEXT(obj) <= DUK_HOBJECT_GET_ESIZE(obj));
  36260. #ifdef DUK_USE_ASSERTIONS
  36261. /* key must not already exist in entry part */
  36262. {
  36263. duk_uint_fast32_t i;
  36264. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(obj); i++) {
  36265. DUK_ASSERT(DUK_HOBJECT_E_GET_KEY(thr->heap, obj, i) != key);
  36266. }
  36267. }
  36268. #endif
  36269. if (DUK_HOBJECT_GET_ENEXT(obj) >= DUK_HOBJECT_GET_ESIZE(obj)) {
  36270. /* only need to guarantee 1 more slot, but allocation growth is in chunks */
  36271. DUK_DDD(DUK_DDDPRINT("entry part full, allocate space for one more entry"));
  36272. duk__grow_props_for_new_entry_item(thr, obj);
  36273. }
  36274. DUK_ASSERT(DUK_HOBJECT_GET_ENEXT(obj) < DUK_HOBJECT_GET_ESIZE(obj));
  36275. idx = DUK_HOBJECT_POSTINC_ENEXT(obj);
  36276. /* previous value is assumed to be garbage, so don't touch it */
  36277. DUK_HOBJECT_E_SET_KEY(thr->heap, obj, idx, key);
  36278. DUK_HSTRING_INCREF(thr, key);
  36279. #if defined(DUK_USE_HOBJECT_HASH_PART)
  36280. if (DUK_UNLIKELY(DUK_HOBJECT_GET_HSIZE(obj) > 0)) {
  36281. duk_uint32_t n;
  36282. duk_uint32_t i, step;
  36283. duk_uint32_t *h_base = DUK_HOBJECT_H_GET_BASE(thr->heap, obj);
  36284. n = DUK_HOBJECT_GET_HSIZE(obj);
  36285. i = DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(key), n);
  36286. step = DUK__HASH_PROBE_STEP(DUK_HSTRING_GET_HASH(key));
  36287. for (;;) {
  36288. duk_uint32_t t = h_base[i];
  36289. if (t == DUK__HASH_UNUSED || t == DUK__HASH_DELETED) {
  36290. DUK_DDD(DUK_DDDPRINT("duk__alloc_entry_checked() inserted key into hash part, %ld -> %ld",
  36291. (long) i, (long) idx));
  36292. DUK_ASSERT_DISABLE(i >= 0); /* unsigned */
  36293. DUK_ASSERT(i < DUK_HOBJECT_GET_HSIZE(obj));
  36294. DUK_ASSERT_DISABLE(idx >= 0);
  36295. DUK_ASSERT(idx < DUK_HOBJECT_GET_ESIZE(obj));
  36296. h_base[i] = idx;
  36297. break;
  36298. }
  36299. DUK_DDD(DUK_DDDPRINT("duk__alloc_entry_checked() miss %ld", (long) i));
  36300. i = (i + step) % n;
  36301. /* guaranteed to find an empty slot */
  36302. DUK_ASSERT(i != (duk_uint32_t) DUK__HASH_INITIAL(DUK_HSTRING_GET_HASH(key), DUK_HOBJECT_GET_HSIZE(obj)));
  36303. }
  36304. }
  36305. #endif /* DUK_USE_HOBJECT_HASH_PART */
  36306. /* Note: we could return the hash index here too, but it's not
  36307. * needed right now.
  36308. */
  36309. DUK_ASSERT_DISABLE(idx >= 0);
  36310. DUK_ASSERT(idx < DUK_HOBJECT_GET_ESIZE(obj));
  36311. DUK_ASSERT(idx < DUK_HOBJECT_GET_ENEXT(obj));
  36312. return idx;
  36313. }
  36314. /*
  36315. * Object internal value
  36316. *
  36317. * Returned value is guaranteed to be reachable / incref'd, caller does not need
  36318. * to incref OR decref. No proxies or accessors are invoked, no prototype walk.
  36319. */
  36320. DUK_INTERNAL duk_bool_t duk_hobject_get_internal_value(duk_heap *heap, duk_hobject *obj, duk_tval *tv_out) {
  36321. duk_int_t e_idx;
  36322. duk_int_t h_idx;
  36323. DUK_ASSERT(heap != NULL);
  36324. DUK_ASSERT(obj != NULL);
  36325. DUK_ASSERT(tv_out != NULL);
  36326. DUK_TVAL_SET_UNDEFINED_UNUSED(tv_out);
  36327. /* always in entry part, no need to look up parents etc */
  36328. duk_hobject_find_existing_entry(heap, obj, DUK_HEAP_STRING_INT_VALUE(heap), &e_idx, &h_idx);
  36329. if (e_idx >= 0) {
  36330. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(heap, obj, e_idx));
  36331. DUK_TVAL_SET_TVAL(tv_out, DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(heap, obj, e_idx));
  36332. return 1;
  36333. }
  36334. return 0;
  36335. }
  36336. DUK_INTERNAL duk_hstring *duk_hobject_get_internal_value_string(duk_heap *heap, duk_hobject *obj) {
  36337. duk_tval tv;
  36338. DUK_ASSERT(heap != NULL);
  36339. DUK_ASSERT(obj != NULL);
  36340. if (duk_hobject_get_internal_value(heap, obj, &tv)) {
  36341. duk_hstring *h;
  36342. DUK_ASSERT(DUK_TVAL_IS_STRING(&tv));
  36343. h = DUK_TVAL_GET_STRING(&tv);
  36344. return h;
  36345. }
  36346. return NULL;
  36347. }
  36348. DUK_INTERNAL duk_hbuffer *duk_hobject_get_internal_value_buffer(duk_heap *heap, duk_hobject *obj) {
  36349. duk_tval tv;
  36350. DUK_ASSERT(heap != NULL);
  36351. DUK_ASSERT(obj != NULL);
  36352. if (duk_hobject_get_internal_value(heap, obj, &tv)) {
  36353. duk_hbuffer *h;
  36354. DUK_ASSERT(DUK_TVAL_IS_BUFFER(&tv));
  36355. h = DUK_TVAL_GET_BUFFER(&tv);
  36356. return h;
  36357. }
  36358. return NULL;
  36359. }
  36360. /*
  36361. * Arguments handling helpers (argument map mainly).
  36362. *
  36363. * An arguments object has exotic behavior for some numeric indices.
  36364. * Accesses may translate to identifier operations which may have
  36365. * arbitrary side effects (potentially invalidating any duk_tval
  36366. * pointers).
  36367. */
  36368. /* Lookup 'key' from arguments internal 'map', perform a variable lookup
  36369. * if mapped, and leave the result on top of stack (and return non-zero).
  36370. * Used in E5 Section 10.6 algorithms [[Get]] and [[GetOwnProperty]].
  36371. */
  36372. DUK_LOCAL
  36373. duk_bool_t duk__lookup_arguments_map(duk_hthread *thr,
  36374. duk_hobject *obj,
  36375. duk_hstring *key,
  36376. duk_propdesc *temp_desc,
  36377. duk_hobject **out_map,
  36378. duk_hobject **out_varenv) {
  36379. duk_context *ctx = (duk_context *) thr;
  36380. duk_hobject *map;
  36381. duk_hobject *varenv;
  36382. duk_bool_t rc;
  36383. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36384. DUK_DDD(DUK_DDDPRINT("arguments map lookup: thr=%p, obj=%p, key=%p, temp_desc=%p "
  36385. "(obj -> %!O, key -> %!O)",
  36386. (void *) thr, (void *) obj, (void *) key, (void *) temp_desc,
  36387. (duk_heaphdr *) obj, (duk_heaphdr *) key));
  36388. if (!duk__get_own_property_desc(thr, obj, DUK_HTHREAD_STRING_INT_MAP(thr), temp_desc, DUK__DESC_FLAG_PUSH_VALUE)) {
  36389. DUK_DDD(DUK_DDDPRINT("-> no 'map'"));
  36390. return 0;
  36391. }
  36392. map = duk_require_hobject(ctx, -1);
  36393. DUK_ASSERT(map != NULL);
  36394. duk_pop(ctx); /* map is reachable through obj */
  36395. if (!duk__get_own_property_desc(thr, map, key, temp_desc, DUK__DESC_FLAG_PUSH_VALUE)) {
  36396. DUK_DDD(DUK_DDDPRINT("-> 'map' exists, but key not in map"));
  36397. return 0;
  36398. }
  36399. /* [... varname] */
  36400. DUK_DDD(DUK_DDDPRINT("-> 'map' exists, and contains key, key is mapped to argument/variable binding %!T",
  36401. (duk_tval *) duk_get_tval(ctx, -1)));
  36402. DUK_ASSERT(duk_is_string(ctx, -1)); /* guaranteed when building arguments */
  36403. /* get varenv for varname (callee's declarative lexical environment) */
  36404. rc = duk__get_own_property_desc(thr, obj, DUK_HTHREAD_STRING_INT_VARENV(thr), temp_desc, DUK__DESC_FLAG_PUSH_VALUE);
  36405. DUK_UNREF(rc);
  36406. DUK_ASSERT(rc != 0); /* arguments MUST have an initialized lexical environment reference */
  36407. varenv = duk_require_hobject(ctx, -1);
  36408. DUK_ASSERT(varenv != NULL);
  36409. duk_pop(ctx); /* varenv remains reachable through 'obj' */
  36410. DUK_DDD(DUK_DDDPRINT("arguments varenv is: %!dO", (duk_heaphdr *) varenv));
  36411. /* success: leave varname in stack */
  36412. *out_map = map;
  36413. *out_varenv = varenv;
  36414. return 1; /* [... varname] */
  36415. }
  36416. /* Lookup 'key' from arguments internal 'map', and leave replacement value
  36417. * on stack top if mapped (and return non-zero).
  36418. * Used in E5 Section 10.6 algorithm for [[GetOwnProperty]] (used by [[Get]]).
  36419. */
  36420. DUK_LOCAL duk_bool_t duk__check_arguments_map_for_get(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *temp_desc) {
  36421. duk_context *ctx = (duk_context *) thr;
  36422. duk_hobject *map;
  36423. duk_hobject *varenv;
  36424. duk_hstring *varname;
  36425. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36426. if (!duk__lookup_arguments_map(thr, obj, key, temp_desc, &map, &varenv)) {
  36427. DUK_DDD(DUK_DDDPRINT("arguments: key not mapped, no exotic get behavior"));
  36428. return 0;
  36429. }
  36430. /* [... varname] */
  36431. varname = duk_require_hstring(ctx, -1);
  36432. DUK_ASSERT(varname != NULL);
  36433. duk_pop(ctx); /* varname is still reachable */
  36434. DUK_DDD(DUK_DDDPRINT("arguments object automatic getvar for a bound variable; "
  36435. "key=%!O, varname=%!O",
  36436. (duk_heaphdr *) key,
  36437. (duk_heaphdr *) varname));
  36438. (void) duk_js_getvar_envrec(thr, varenv, varname, 1 /*throw*/);
  36439. /* [... value this_binding] */
  36440. duk_pop(ctx);
  36441. /* leave result on stack top */
  36442. return 1;
  36443. }
  36444. /* Lookup 'key' from arguments internal 'map', perform a variable write if mapped.
  36445. * Used in E5 Section 10.6 algorithm for [[DefineOwnProperty]] (used by [[Put]]).
  36446. * Assumes stack top contains 'put' value (which is NOT popped).
  36447. */
  36448. DUK_LOCAL void duk__check_arguments_map_for_put(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *temp_desc, duk_bool_t throw_flag) {
  36449. duk_context *ctx = (duk_context *) thr;
  36450. duk_hobject *map;
  36451. duk_hobject *varenv;
  36452. duk_hstring *varname;
  36453. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36454. if (!duk__lookup_arguments_map(thr, obj, key, temp_desc, &map, &varenv)) {
  36455. DUK_DDD(DUK_DDDPRINT("arguments: key not mapped, no exotic put behavior"));
  36456. return;
  36457. }
  36458. /* [... put_value varname] */
  36459. varname = duk_require_hstring(ctx, -1);
  36460. DUK_ASSERT(varname != NULL);
  36461. duk_pop(ctx); /* varname is still reachable */
  36462. DUK_DDD(DUK_DDDPRINT("arguments object automatic putvar for a bound variable; "
  36463. "key=%!O, varname=%!O, value=%!T",
  36464. (duk_heaphdr *) key,
  36465. (duk_heaphdr *) varname,
  36466. (duk_tval *) duk_require_tval(ctx, -1)));
  36467. /* [... put_value] */
  36468. /*
  36469. * Note: although arguments object variable mappings are only established
  36470. * for non-strict functions (and a call to a non-strict function created
  36471. * the arguments object in question), an inner strict function may be doing
  36472. * the actual property write. Hence the throw_flag applied here comes from
  36473. * the property write call.
  36474. */
  36475. duk_js_putvar_envrec(thr, varenv, varname, duk_require_tval(ctx, -1), throw_flag);
  36476. /* [... put_value] */
  36477. }
  36478. /* Lookup 'key' from arguments internal 'map', delete mapping if found.
  36479. * Used in E5 Section 10.6 algorithm for [[Delete]]. Note that the
  36480. * variable/argument itself (where the map points) is not deleted.
  36481. */
  36482. DUK_LOCAL void duk__check_arguments_map_for_delete(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *temp_desc) {
  36483. duk_context *ctx = (duk_context *) thr;
  36484. duk_hobject *map;
  36485. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36486. if (!duk__get_own_property_desc(thr, obj, DUK_HTHREAD_STRING_INT_MAP(thr), temp_desc, DUK__DESC_FLAG_PUSH_VALUE)) {
  36487. DUK_DDD(DUK_DDDPRINT("arguments: key not mapped, no exotic delete behavior"));
  36488. return;
  36489. }
  36490. map = duk_require_hobject(ctx, -1);
  36491. DUK_ASSERT(map != NULL);
  36492. duk_pop(ctx); /* map is reachable through obj */
  36493. DUK_DDD(DUK_DDDPRINT("-> have 'map', delete key %!O from map (if exists)); ignore result",
  36494. (duk_heaphdr *) key));
  36495. /* Note: no recursion issue, we can trust 'map' to behave */
  36496. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_BEHAVIOR(map));
  36497. DUK_DDD(DUK_DDDPRINT("map before deletion: %!O", (duk_heaphdr *) map));
  36498. (void) duk_hobject_delprop_raw(thr, map, key, 0); /* ignore result */
  36499. DUK_DDD(DUK_DDDPRINT("map after deletion: %!O", (duk_heaphdr *) map));
  36500. }
  36501. /*
  36502. * Ecmascript compliant [[GetOwnProperty]](P), for internal use only.
  36503. *
  36504. * If property is found:
  36505. * - Fills descriptor fields to 'out_desc'
  36506. * - If DUK__DESC_FLAG_PUSH_VALUE is set, pushes a value related to the
  36507. * property onto the stack ('undefined' for accessor properties).
  36508. * - Returns non-zero
  36509. *
  36510. * If property is not found:
  36511. * - 'out_desc' is left in untouched state (possibly garbage)
  36512. * - Nothing is pushed onto the stack (not even with DUK__DESC_FLAG_PUSH_VALUE
  36513. * set)
  36514. * - Returns zero
  36515. *
  36516. * Notes:
  36517. *
  36518. * - Getting a property descriptor may cause an allocation (and hence
  36519. * GC) to take place, hence reachability and refcount of all related
  36520. * values matter. Reallocation of value stack, properties, etc may
  36521. * invalidate many duk_tval pointers (concretely, those which reside
  36522. * in memory areas subject to reallocation). However, heap object
  36523. * pointers are never affected (heap objects have stable pointers).
  36524. *
  36525. * - The value of a plain property is always reachable and has a non-zero
  36526. * reference count.
  36527. *
  36528. * - The value of a virtual property is not necessarily reachable from
  36529. * elsewhere and may have a refcount of zero. Hence we push it onto
  36530. * the valstack for the caller, which ensures it remains reachable
  36531. * while it is needed.
  36532. *
  36533. * - There are no virtual accessor properties. Hence, all getters and
  36534. * setters are always related to concretely stored properties, which
  36535. * ensures that the get/set functions in the resulting descriptor are
  36536. * reachable and have non-zero refcounts. Should there be virtual
  36537. * accessor properties later, this would need to change.
  36538. */
  36539. DUK_LOCAL duk_bool_t duk__get_own_property_desc_raw(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_uint32_t arr_idx, duk_propdesc *out_desc, duk_small_uint_t flags) {
  36540. duk_context *ctx = (duk_context *) thr;
  36541. duk_tval *tv;
  36542. DUK_DDD(DUK_DDDPRINT("duk__get_own_property_desc: thr=%p, obj=%p, key=%p, out_desc=%p, flags=%lx, "
  36543. "arr_idx=%ld (obj -> %!O, key -> %!O)",
  36544. (void *) thr, (void *) obj, (void *) key, (void *) out_desc,
  36545. (long) flags, (long) arr_idx,
  36546. (duk_heaphdr *) obj, (duk_heaphdr *) key));
  36547. DUK_ASSERT(ctx != NULL);
  36548. DUK_ASSERT(thr != NULL);
  36549. DUK_ASSERT(thr->heap != NULL);
  36550. DUK_ASSERT(obj != NULL);
  36551. DUK_ASSERT(key != NULL);
  36552. DUK_ASSERT(out_desc != NULL);
  36553. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36554. /* XXX: optimize this filling behavior later */
  36555. out_desc->flags = 0;
  36556. out_desc->get = NULL;
  36557. out_desc->set = NULL;
  36558. out_desc->e_idx = -1;
  36559. out_desc->h_idx = -1;
  36560. out_desc->a_idx = -1;
  36561. /*
  36562. * Array part
  36563. */
  36564. if (DUK_HOBJECT_HAS_ARRAY_PART(obj) && arr_idx != DUK__NO_ARRAY_INDEX) {
  36565. if (arr_idx < DUK_HOBJECT_GET_ASIZE(obj)) {
  36566. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, arr_idx);
  36567. if (!DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  36568. DUK_DDD(DUK_DDDPRINT("-> found in array part"));
  36569. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36570. duk_push_tval(ctx, tv);
  36571. }
  36572. /* implicit attributes */
  36573. out_desc->flags = DUK_PROPDESC_FLAG_WRITABLE |
  36574. DUK_PROPDESC_FLAG_CONFIGURABLE |
  36575. DUK_PROPDESC_FLAG_ENUMERABLE;
  36576. out_desc->a_idx = arr_idx;
  36577. goto prop_found;
  36578. }
  36579. }
  36580. /* assume array part is comprehensive (contains all array indexed elements
  36581. * or none of them); hence no need to check the entries part here.
  36582. */
  36583. DUK_DDD(DUK_DDDPRINT("-> not found as a concrete property (has array part, "
  36584. "should be there if present)"));
  36585. goto prop_not_found_concrete;
  36586. }
  36587. /*
  36588. * Entries part
  36589. */
  36590. duk_hobject_find_existing_entry(thr->heap, obj, key, &out_desc->e_idx, &out_desc->h_idx);
  36591. if (out_desc->e_idx >= 0) {
  36592. duk_int_t e_idx = out_desc->e_idx;
  36593. out_desc->flags = DUK_HOBJECT_E_GET_FLAGS(thr->heap, obj, e_idx);
  36594. if (out_desc->flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  36595. DUK_DDD(DUK_DDDPRINT("-> found accessor property in entry part"));
  36596. out_desc->get = DUK_HOBJECT_E_GET_VALUE_GETTER(thr->heap, obj, e_idx);
  36597. out_desc->set = DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, obj, e_idx);
  36598. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36599. /* a dummy undefined value is pushed to make valstack
  36600. * behavior uniform for caller
  36601. */
  36602. duk_push_undefined(ctx);
  36603. }
  36604. } else {
  36605. DUK_DDD(DUK_DDDPRINT("-> found plain property in entry part"));
  36606. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, e_idx);
  36607. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36608. duk_push_tval(ctx, tv);
  36609. }
  36610. }
  36611. goto prop_found;
  36612. }
  36613. /*
  36614. * Not found as a concrete property, check whether a String object
  36615. * virtual property matches.
  36616. */
  36617. prop_not_found_concrete:
  36618. if (DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(obj)) {
  36619. DUK_DDD(DUK_DDDPRINT("string object exotic property get for key: %!O, arr_idx: %ld",
  36620. (duk_heaphdr *) key, (long) arr_idx));
  36621. if (arr_idx != DUK__NO_ARRAY_INDEX) {
  36622. duk_hstring *h_val;
  36623. DUK_DDD(DUK_DDDPRINT("array index exists"));
  36624. h_val = duk_hobject_get_internal_value_string(thr->heap, obj);
  36625. DUK_ASSERT(h_val);
  36626. if (arr_idx < DUK_HSTRING_GET_CHARLEN(h_val)) {
  36627. DUK_DDD(DUK_DDDPRINT("-> found, array index inside string"));
  36628. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36629. duk_push_hstring(ctx, h_val);
  36630. duk_substring(ctx, -1, arr_idx, arr_idx + 1); /* [str] -> [substr] */
  36631. }
  36632. out_desc->flags = DUK_PROPDESC_FLAG_ENUMERABLE | /* E5 Section 15.5.5.2 */
  36633. DUK_PROPDESC_FLAG_VIRTUAL;
  36634. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj));
  36635. return 1; /* cannot be e.g. arguments exotic, since exotic 'traits' are mutually exclusive */
  36636. } else {
  36637. /* index is above internal string length -> property is fully normal */
  36638. DUK_DDD(DUK_DDDPRINT("array index outside string -> normal property"));
  36639. }
  36640. } else if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  36641. duk_hstring *h_val;
  36642. DUK_DDD(DUK_DDDPRINT("-> found, key is 'length', length exotic behavior"));
  36643. h_val = duk_hobject_get_internal_value_string(thr->heap, obj);
  36644. DUK_ASSERT(h_val != NULL);
  36645. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36646. duk_push_uint(ctx, (duk_uint_t) DUK_HSTRING_GET_CHARLEN(h_val));
  36647. }
  36648. out_desc->flags = DUK_PROPDESC_FLAG_VIRTUAL; /* E5 Section 15.5.5.1 */
  36649. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj));
  36650. return 1; /* cannot be arguments exotic */
  36651. }
  36652. } else if (DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(obj)) {
  36653. DUK_DDD(DUK_DDDPRINT("buffer object exotic property get for key: %!O, arr_idx: %ld",
  36654. (duk_heaphdr *) key, (long) arr_idx));
  36655. if (arr_idx != DUK__NO_ARRAY_INDEX) {
  36656. duk_hbuffer *h_val;
  36657. DUK_DDD(DUK_DDDPRINT("array index exists"));
  36658. h_val = duk_hobject_get_internal_value_buffer(thr->heap, obj);
  36659. DUK_ASSERT(h_val);
  36660. /* SCANBUILD: h_val is known to be non-NULL but scan-build cannot
  36661. * know it, so it produces NULL pointer dereference warnings for
  36662. * 'h_val'.
  36663. */
  36664. if (arr_idx < DUK_HBUFFER_GET_SIZE(h_val)) {
  36665. DUK_DDD(DUK_DDDPRINT("-> found, array index inside buffer"));
  36666. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36667. duk_push_int(ctx, ((duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h_val))[arr_idx]);
  36668. }
  36669. out_desc->flags = DUK_PROPDESC_FLAG_WRITABLE |
  36670. DUK_PROPDESC_FLAG_ENUMERABLE |
  36671. DUK_PROPDESC_FLAG_VIRTUAL;
  36672. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj));
  36673. return 1; /* cannot be e.g. arguments exotic, since exotic 'traits' are mutually exclusive */
  36674. } else {
  36675. /* index is above internal buffer length -> property is fully normal */
  36676. DUK_DDD(DUK_DDDPRINT("array index outside buffer -> normal property"));
  36677. }
  36678. } else if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  36679. duk_hbuffer *h_val;
  36680. DUK_DDD(DUK_DDDPRINT("-> found, key is 'length', length exotic behavior"));
  36681. /* XXX: buffer length should be writable and have exotic behavior
  36682. * like arrays. For now, make it read-only and use explicit methods
  36683. * to operate on buffer length.
  36684. */
  36685. h_val = duk_hobject_get_internal_value_buffer(thr->heap, obj);
  36686. DUK_ASSERT(h_val != NULL);
  36687. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36688. duk_push_uint(ctx, (duk_uint_t) DUK_HBUFFER_GET_SIZE(h_val));
  36689. }
  36690. out_desc->flags = DUK_PROPDESC_FLAG_VIRTUAL;
  36691. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj));
  36692. return 1; /* cannot be arguments exotic */
  36693. }
  36694. } else if (DUK_HOBJECT_HAS_EXOTIC_DUKFUNC(obj)) {
  36695. DUK_DDD(DUK_DDDPRINT("duktape/c object exotic property get for key: %!O, arr_idx: %ld",
  36696. (duk_heaphdr *) key, (long) arr_idx));
  36697. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  36698. DUK_DDD(DUK_DDDPRINT("-> found, key is 'length', length exotic behavior"));
  36699. if (flags & DUK__DESC_FLAG_PUSH_VALUE) {
  36700. duk_int16_t func_nargs = ((duk_hnativefunction *) obj)->nargs;
  36701. duk_push_int(ctx, func_nargs == DUK_HNATIVEFUNCTION_NARGS_VARARGS ? 0 : func_nargs);
  36702. }
  36703. out_desc->flags = DUK_PROPDESC_FLAG_VIRTUAL; /* not enumerable */
  36704. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj));
  36705. return 1; /* cannot be arguments exotic */
  36706. }
  36707. }
  36708. /* Array properties have exotic behavior but they are concrete,
  36709. * so no special handling here.
  36710. *
  36711. * Arguments exotic behavior (E5 Section 10.6, [[GetOwnProperty]]
  36712. * is only relevant as a post-check implemented below; hence no
  36713. * check here.
  36714. */
  36715. /*
  36716. * Not found as concrete or virtual
  36717. */
  36718. DUK_DDD(DUK_DDDPRINT("-> not found (virtual, entry part, or array part)"));
  36719. return 0;
  36720. /*
  36721. * Found
  36722. *
  36723. * Arguments object has exotic post-processing, see E5 Section 10.6,
  36724. * description of [[GetOwnProperty]] variant for arguments.
  36725. */
  36726. prop_found:
  36727. DUK_DDD(DUK_DDDPRINT("-> property found, checking for arguments exotic post-behavior"));
  36728. /* Notes:
  36729. * - only numbered indices are relevant, so arr_idx fast reject is good
  36730. * (this is valid unless there are more than 4**32-1 arguments).
  36731. * - since variable lookup has no side effects, this can be skipped if
  36732. * DUK__DESC_FLAG_PUSH_VALUE is not set.
  36733. */
  36734. if (DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj) &&
  36735. arr_idx != DUK__NO_ARRAY_INDEX &&
  36736. (flags & DUK__DESC_FLAG_PUSH_VALUE)) {
  36737. duk_propdesc temp_desc;
  36738. /* Magically bound variable cannot be an accessor. However,
  36739. * there may be an accessor property (or a plain property) in
  36740. * place with magic behavior removed. This happens e.g. when
  36741. * a magic property is redefined with defineProperty().
  36742. * Cannot assert for "not accessor" here.
  36743. */
  36744. /* replaces top of stack with new value if necessary */
  36745. DUK_ASSERT((flags & DUK__DESC_FLAG_PUSH_VALUE) != 0);
  36746. if (duk__check_arguments_map_for_get(thr, obj, key, &temp_desc)) {
  36747. DUK_DDD(DUK_DDDPRINT("-> arguments exotic behavior overrides result: %!T -> %!T",
  36748. (duk_tval *) duk_get_tval(ctx, -2),
  36749. (duk_tval *) duk_get_tval(ctx, -1)));
  36750. /* [... old_result result] -> [... result] */
  36751. duk_remove(ctx, -2);
  36752. }
  36753. }
  36754. return 1;
  36755. }
  36756. DUK_LOCAL duk_bool_t duk__get_own_property_desc(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *out_desc, duk_small_uint_t flags) {
  36757. DUK_ASSERT(thr != NULL);
  36758. DUK_ASSERT(obj != NULL);
  36759. DUK_ASSERT(key != NULL);
  36760. DUK_ASSERT(out_desc != NULL);
  36761. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36762. return duk__get_own_property_desc_raw(thr, obj, key, DUK_HSTRING_GET_ARRIDX_SLOW(key), out_desc, flags);
  36763. }
  36764. /*
  36765. * Ecmascript compliant [[GetProperty]](P), for internal use only.
  36766. *
  36767. * If property is found:
  36768. * - Fills descriptor fields to 'out_desc'
  36769. * - If DUK__DESC_FLAG_PUSH_VALUE is set, pushes a value related to the
  36770. * property onto the stack ('undefined' for accessor properties).
  36771. * - Returns non-zero
  36772. *
  36773. * If property is not found:
  36774. * - 'out_desc' is left in untouched state (possibly garbage)
  36775. * - Nothing is pushed onto the stack (not even with DUK__DESC_FLAG_PUSH_VALUE
  36776. * set)
  36777. * - Returns zero
  36778. *
  36779. * May cause arbitrary side effects and invalidate (most) duk_tval
  36780. * pointers.
  36781. */
  36782. DUK_LOCAL duk_bool_t duk__get_property_desc(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_propdesc *out_desc, duk_small_uint_t flags) {
  36783. duk_hobject *curr;
  36784. duk_uint32_t arr_idx;
  36785. duk_uint_t sanity;
  36786. DUK_ASSERT(thr != NULL);
  36787. DUK_ASSERT(thr->heap != NULL);
  36788. DUK_ASSERT(obj != NULL);
  36789. DUK_ASSERT(key != NULL);
  36790. DUK_ASSERT(out_desc != NULL);
  36791. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36792. arr_idx = DUK_HSTRING_GET_ARRIDX_FAST(key);
  36793. DUK_DDD(DUK_DDDPRINT("duk__get_property_desc: thr=%p, obj=%p, key=%p, out_desc=%p, flags=%lx, "
  36794. "arr_idx=%ld (obj -> %!O, key -> %!O)",
  36795. (void *) thr, (void *) obj, (void *) key, (void *) out_desc,
  36796. (long) flags, (long) arr_idx,
  36797. (duk_heaphdr *) obj, (duk_heaphdr *) key));
  36798. curr = obj;
  36799. DUK_ASSERT(curr != NULL);
  36800. sanity = DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY;
  36801. do {
  36802. if (duk__get_own_property_desc_raw(thr, curr, key, arr_idx, out_desc, flags)) {
  36803. /* stack contains value (if requested), 'out_desc' is set */
  36804. return 1;
  36805. }
  36806. /* not found in 'curr', next in prototype chain; impose max depth */
  36807. if (sanity-- == 0) {
  36808. if (flags & DUK__DESC_FLAG_IGNORE_PROTOLOOP) {
  36809. /* treat like property not found */
  36810. break;
  36811. } else {
  36812. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_PROTOTYPE_CHAIN_LIMIT);
  36813. }
  36814. }
  36815. curr = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, curr);
  36816. } while (curr);
  36817. /* out_desc is left untouched (possibly garbage), caller must use return
  36818. * value to determine whether out_desc can be looked up
  36819. */
  36820. return 0;
  36821. }
  36822. /*
  36823. * Shallow fast path checks for accessing array elements with numeric
  36824. * indices. The goal is to try to avoid coercing an array index to an
  36825. * (interned) string for the most common lookups, in particular, for
  36826. * standard Array objects.
  36827. *
  36828. * Interning is avoided but only for a very narrow set of cases:
  36829. * - Object has array part, index is within array allocation, and
  36830. * value is not unused (= key exists)
  36831. * - Object has no interfering exotic behavior (e.g. arguments or
  36832. * string object exotic behaviors interfere, array exotic
  36833. * behavior does not).
  36834. *
  36835. * Current shortcoming: if key does not exist (even if it is within
  36836. * the array allocation range) a slow path lookup with interning is
  36837. * always required. This can probably be fixed so that there is a
  36838. * quick fast path for non-existent elements as well, at least for
  36839. * standard Array objects.
  36840. */
  36841. #if 0 /* XXX: unused now */
  36842. DUK_LOCAL duk_tval *duk__shallow_fast_path_array_check_u32(duk_hobject *obj, duk_uint32_t key_idx) {
  36843. duk_tval *tv;
  36844. if ((!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj)) &&
  36845. (!DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(obj)) &&
  36846. (!DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(obj)) &&
  36847. (!DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(obj)) &&
  36848. (DUK_HOBJECT_HAS_ARRAY_PART(obj)) &&
  36849. (key_idx < obj->a_size)) {
  36850. /* technically required to check, but obj->a_size check covers this */
  36851. DUK_ASSERT(key_idx != 0xffffffffUL);
  36852. DUK_DDD(DUK_DDDPRINT("fast path attempt (key is an array index, no exotic "
  36853. "string/arguments/buffer behavior, object has array part, key "
  36854. "inside array size)"));
  36855. DUK_ASSERT(obj->a_size > 0); /* true even for key_idx == 0 */
  36856. tv = DUK_HOBJECT_A_GET_VALUE_PTR(obj, key_idx);
  36857. if (!DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  36858. DUK_DDD(DUK_DDDPRINT("-> fast path successful"));
  36859. return tv;
  36860. }
  36861. /*
  36862. * Not found, fall back to slow path.
  36863. *
  36864. * Note: this approach has the unfortunate side effect that accesses
  36865. * to undefined entries (or entries outside valid array range) cause
  36866. * a string intern operation.
  36867. */
  36868. DUK_DDD(DUK_DDDPRINT("fast path attempt failed, fall back to slow path"));
  36869. }
  36870. return NULL;
  36871. }
  36872. #endif
  36873. DUK_LOCAL duk_tval *duk__shallow_fast_path_array_check_tval(duk_hthread *thr, duk_hobject *obj, duk_tval *key_tv) {
  36874. duk_tval *tv;
  36875. duk_uint32_t idx;
  36876. DUK_UNREF(thr);
  36877. if (!(DUK_HOBJECT_HAS_ARRAY_PART(obj) &&
  36878. !DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj) &&
  36879. !DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(obj) &&
  36880. !DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(obj) &&
  36881. !DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(obj))) {
  36882. /* Must have array part and no conflicting exotic behaviors.
  36883. * Doesn't need to have array special behavior, e.g. Arguments
  36884. * object has array part.
  36885. */
  36886. return NULL;
  36887. }
  36888. /* Arrays never have other exotic behaviors. */
  36889. DUK_DDD(DUK_DDDPRINT("fast path attempt (no exotic string/arguments/buffer "
  36890. "behavior, object has array part)"));
  36891. #if defined(DUK_USE_FASTINT)
  36892. if (DUK_TVAL_IS_FASTINT(key_tv)) {
  36893. idx = duk__tval_fastint_to_arr_idx(key_tv);
  36894. } else
  36895. #endif
  36896. if (DUK_TVAL_IS_NUMBER(key_tv)) {
  36897. idx = duk__tval_number_to_arr_idx(key_tv);
  36898. } else {
  36899. DUK_DDD(DUK_DDDPRINT("key is not a number"));
  36900. return NULL;
  36901. }
  36902. if (idx != DUK__NO_ARRAY_INDEX) {
  36903. /* Note: idx is not necessarily a valid array index (0xffffffffUL is not valid) */
  36904. DUK_ASSERT_DISABLE(idx >= 0); /* disabled because idx is duk_uint32_t so always true */
  36905. DUK_ASSERT_DISABLE(idx <= 0xffffffffUL); /* same */
  36906. if (idx < DUK_HOBJECT_GET_ASIZE(obj)) {
  36907. /* technically required to check, but obj->a_size check covers this */
  36908. DUK_ASSERT(idx != 0xffffffffUL);
  36909. /* XXX: for array instances we could take a shortcut here and assume
  36910. * Array.prototype doesn't contain an array index property.
  36911. */
  36912. DUK_DDD(DUK_DDDPRINT("key is a valid array index and inside array part"));
  36913. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, idx);
  36914. if (!DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  36915. DUK_DDD(DUK_DDDPRINT("-> fast path successful"));
  36916. return tv;
  36917. }
  36918. } else {
  36919. DUK_DDD(DUK_DDDPRINT("key is outside array part"));
  36920. }
  36921. } else {
  36922. DUK_DDD(DUK_DDDPRINT("key is not a valid array index"));
  36923. }
  36924. /*
  36925. * Not found in array part, use slow path.
  36926. */
  36927. DUK_DDD(DUK_DDDPRINT("fast path attempt failed, fall back to slow path"));
  36928. return NULL;
  36929. }
  36930. /*
  36931. * GETPROP: Ecmascript property read.
  36932. */
  36933. DUK_INTERNAL duk_bool_t duk_hobject_getprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key) {
  36934. duk_context *ctx = (duk_context *) thr;
  36935. duk_tval tv_obj_copy;
  36936. duk_tval tv_key_copy;
  36937. duk_hobject *curr = NULL;
  36938. duk_hstring *key = NULL;
  36939. duk_uint32_t arr_idx = DUK__NO_ARRAY_INDEX;
  36940. duk_propdesc desc;
  36941. duk_uint_t sanity;
  36942. DUK_DDD(DUK_DDDPRINT("getprop: thr=%p, obj=%p, key=%p (obj -> %!T, key -> %!T)",
  36943. (void *) thr, (void *) tv_obj, (void *) tv_key,
  36944. (duk_tval *) tv_obj, (duk_tval *) tv_key));
  36945. DUK_ASSERT(ctx != NULL);
  36946. DUK_ASSERT(thr != NULL);
  36947. DUK_ASSERT(thr->heap != NULL);
  36948. DUK_ASSERT(tv_obj != NULL);
  36949. DUK_ASSERT(tv_key != NULL);
  36950. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  36951. /*
  36952. * Make a copy of tv_obj, tv_key, and tv_val to avoid any issues of
  36953. * them being invalidated by a valstack resize.
  36954. *
  36955. * XXX: this is now an overkill for many fast paths. Rework this
  36956. * to be faster (although switching to a valstack discipline might
  36957. * be a better solution overall).
  36958. */
  36959. DUK_TVAL_SET_TVAL(&tv_obj_copy, tv_obj);
  36960. DUK_TVAL_SET_TVAL(&tv_key_copy, tv_key);
  36961. tv_obj = &tv_obj_copy;
  36962. tv_key = &tv_key_copy;
  36963. /*
  36964. * Coercion and fast path processing
  36965. */
  36966. switch (DUK_TVAL_GET_TAG(tv_obj)) {
  36967. case DUK_TAG_UNDEFINED:
  36968. case DUK_TAG_NULL: {
  36969. /* Note: unconditional throw */
  36970. DUK_DDD(DUK_DDDPRINT("base object is undefined or null -> reject"));
  36971. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INVALID_BASE);
  36972. return 0;
  36973. }
  36974. case DUK_TAG_BOOLEAN: {
  36975. DUK_DDD(DUK_DDDPRINT("base object is a boolean, start lookup from boolean prototype"));
  36976. curr = thr->builtins[DUK_BIDX_BOOLEAN_PROTOTYPE];
  36977. break;
  36978. }
  36979. case DUK_TAG_STRING: {
  36980. duk_hstring *h = DUK_TVAL_GET_STRING(tv_obj);
  36981. duk_int_t pop_count;
  36982. #if defined(DUK_USE_FASTINT)
  36983. if (DUK_TVAL_IS_FASTINT(tv_key)) {
  36984. arr_idx = duk__tval_fastint_to_arr_idx(tv_key);
  36985. DUK_DDD(DUK_DDDPRINT("base object string, key is a fast-path fastint; arr_idx %ld", (long) arr_idx));
  36986. pop_count = 0;
  36987. } else
  36988. #endif
  36989. if (DUK_TVAL_IS_NUMBER(tv_key)) {
  36990. arr_idx = duk__tval_number_to_arr_idx(tv_key);
  36991. DUK_DDD(DUK_DDDPRINT("base object string, key is a fast-path number; arr_idx %ld", (long) arr_idx));
  36992. pop_count = 0;
  36993. } else {
  36994. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  36995. DUK_ASSERT(key != NULL);
  36996. DUK_DDD(DUK_DDDPRINT("base object string, key is a non-fast-path number; after "
  36997. "coercion key is %!T, arr_idx %ld",
  36998. (duk_tval *) duk_get_tval(ctx, -1), (long) arr_idx));
  36999. pop_count = 1;
  37000. }
  37001. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  37002. arr_idx < DUK_HSTRING_GET_CHARLEN(h)) {
  37003. duk_pop_n(ctx, pop_count);
  37004. duk_push_hstring(ctx, h);
  37005. duk_substring(ctx, -1, arr_idx, arr_idx + 1); /* [str] -> [substr] */
  37006. DUK_DDD(DUK_DDDPRINT("-> %!T (base is string, key is an index inside string length "
  37007. "after coercion -> return char)",
  37008. (duk_tval *) duk_get_tval(ctx, -1)));
  37009. return 1;
  37010. }
  37011. if (pop_count == 0) {
  37012. /* This is a pretty awkward control flow, but we need to recheck the
  37013. * key coercion here.
  37014. */
  37015. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37016. DUK_ASSERT(key != NULL);
  37017. DUK_DDD(DUK_DDDPRINT("base object string, key is a non-fast-path number; after "
  37018. "coercion key is %!T, arr_idx %ld",
  37019. (duk_tval *) duk_get_tval(ctx, -1), (long) arr_idx));
  37020. }
  37021. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  37022. duk_pop(ctx); /* [key] -> [] */
  37023. duk_push_uint(ctx, (duk_uint_t) DUK_HSTRING_GET_CHARLEN(h)); /* [] -> [res] */
  37024. DUK_DDD(DUK_DDDPRINT("-> %!T (base is string, key is 'length' after coercion -> "
  37025. "return string length)",
  37026. (duk_tval *) duk_get_tval(ctx, -1)));
  37027. return 1;
  37028. }
  37029. DUK_DDD(DUK_DDDPRINT("base object is a string, start lookup from string prototype"));
  37030. curr = thr->builtins[DUK_BIDX_STRING_PROTOTYPE];
  37031. goto lookup; /* avoid double coercion */
  37032. }
  37033. case DUK_TAG_OBJECT: {
  37034. duk_tval *tmp;
  37035. curr = DUK_TVAL_GET_OBJECT(tv_obj);
  37036. DUK_ASSERT(curr != NULL);
  37037. #if defined(DUK_USE_ES6_PROXY)
  37038. if (DUK_UNLIKELY(DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(curr))) {
  37039. duk_hobject *h_target;
  37040. if (duk__proxy_check_prop(thr, curr, DUK_STRIDX_GET, tv_key, &h_target)) {
  37041. /* -> [ ... trap handler ] */
  37042. DUK_DDD(DUK_DDDPRINT("-> proxy object 'get' for key %!T", (duk_tval *) tv_key));
  37043. duk_push_hobject(ctx, h_target); /* target */
  37044. duk_push_tval(ctx, tv_key); /* P */
  37045. duk_push_tval(ctx, tv_obj); /* Receiver: Proxy object */
  37046. duk_call_method(ctx, 3 /*nargs*/);
  37047. /* Target object must be checked for a conflicting
  37048. * non-configurable property.
  37049. */
  37050. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37051. DUK_ASSERT(key != NULL);
  37052. if (duk__get_own_property_desc_raw(thr, h_target, key, arr_idx, &desc, DUK__DESC_FLAG_PUSH_VALUE)) {
  37053. duk_tval *tv_hook = duk_require_tval(ctx, -3); /* value from hook */
  37054. duk_tval *tv_targ = duk_require_tval(ctx, -1); /* value from target */
  37055. duk_bool_t datadesc_reject;
  37056. duk_bool_t accdesc_reject;
  37057. DUK_DDD(DUK_DDDPRINT("proxy 'get': target has matching property %!O, check for "
  37058. "conflicting property; tv_hook=%!T, tv_targ=%!T, desc.flags=0x%08lx, "
  37059. "desc.get=%p, desc.set=%p",
  37060. (duk_heaphdr *) key, (duk_tval *) tv_hook, (duk_tval *) tv_targ,
  37061. (unsigned long) desc.flags,
  37062. (void *) desc.get, (void *) desc.set));
  37063. datadesc_reject = !(desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) &&
  37064. !(desc.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) &&
  37065. !(desc.flags & DUK_PROPDESC_FLAG_WRITABLE) &&
  37066. !duk_js_samevalue(tv_hook, tv_targ);
  37067. accdesc_reject = (desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) &&
  37068. !(desc.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) &&
  37069. (desc.get == NULL) &&
  37070. !DUK_TVAL_IS_UNDEFINED(tv_hook);
  37071. if (datadesc_reject || accdesc_reject) {
  37072. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REJECTED);
  37073. }
  37074. duk_pop_2(ctx);
  37075. } else {
  37076. duk_pop(ctx);
  37077. }
  37078. return 1; /* return value */
  37079. }
  37080. curr = h_target; /* resume lookup from target */
  37081. DUK_TVAL_SET_OBJECT(tv_obj, curr);
  37082. }
  37083. #endif /* DUK_USE_ES6_PROXY */
  37084. tmp = duk__shallow_fast_path_array_check_tval(thr, curr, tv_key);
  37085. if (tmp) {
  37086. duk_push_tval(ctx, tmp);
  37087. DUK_DDD(DUK_DDDPRINT("-> %!T (base is object, key is a number, array part "
  37088. "fast path)",
  37089. (duk_tval *) duk_get_tval(ctx, -1)));
  37090. return 1;
  37091. }
  37092. if (DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(curr)) {
  37093. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37094. DUK_ASSERT(key != NULL);
  37095. if (duk__check_arguments_map_for_get(thr, curr, key, &desc)) {
  37096. DUK_DDD(DUK_DDDPRINT("-> %!T (base is object with arguments exotic behavior, "
  37097. "key matches magically bound property -> skip standard "
  37098. "Get with replacement value)",
  37099. (duk_tval *) duk_get_tval(ctx, -1)));
  37100. /* no need for 'caller' post-check, because 'key' must be an array index */
  37101. duk_remove(ctx, -2); /* [key result] -> [result] */
  37102. return 1;
  37103. }
  37104. goto lookup; /* avoid double coercion */
  37105. }
  37106. break;
  37107. }
  37108. /* Buffer has virtual properties similar to string, but indexed values
  37109. * are numbers, not 1-byte buffers/strings which would perform badly.
  37110. */
  37111. case DUK_TAG_BUFFER: {
  37112. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv_obj);
  37113. duk_int_t pop_count;
  37114. /*
  37115. * Because buffer values are often looped over, a number fast path
  37116. * is important.
  37117. */
  37118. #if defined(DUK_USE_FASTINT)
  37119. if (DUK_TVAL_IS_FASTINT(tv_key)) {
  37120. arr_idx = duk__tval_fastint_to_arr_idx(tv_key);
  37121. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a fast-path fastint; arr_idx %ld", (long) arr_idx));
  37122. pop_count = 0;
  37123. }
  37124. else
  37125. #endif
  37126. if (DUK_TVAL_IS_NUMBER(tv_key)) {
  37127. arr_idx = duk__tval_number_to_arr_idx(tv_key);
  37128. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a fast-path number; arr_idx %ld", (long) arr_idx));
  37129. pop_count = 0;
  37130. } else {
  37131. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37132. DUK_ASSERT(key != NULL);
  37133. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a non-fast-path number; after "
  37134. "coercion key is %!T, arr_idx %ld",
  37135. (duk_tval *) duk_get_tval(ctx, -1), (long) arr_idx));
  37136. pop_count = 1;
  37137. }
  37138. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  37139. arr_idx < DUK_HBUFFER_GET_SIZE(h)) {
  37140. duk_pop_n(ctx, pop_count);
  37141. duk_push_int(ctx, ((duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h))[arr_idx]);
  37142. DUK_DDD(DUK_DDDPRINT("-> %!T (base is buffer, key is an index inside buffer length "
  37143. "after coercion -> return byte as number)",
  37144. (duk_tval *) duk_get_tval(ctx, -1)));
  37145. return 1;
  37146. }
  37147. if (pop_count == 0) {
  37148. /* This is a pretty awkward control flow, but we need to recheck the
  37149. * key coercion here.
  37150. */
  37151. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37152. DUK_ASSERT(key != NULL);
  37153. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a non-fast-path number; after "
  37154. "coercion key is %!T, arr_idx %ld",
  37155. (duk_tval *) duk_get_tval(ctx, -1), (long) arr_idx));
  37156. }
  37157. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  37158. duk_pop(ctx); /* [key] -> [] */
  37159. duk_push_uint(ctx, (duk_uint_t) DUK_HBUFFER_GET_SIZE(h)); /* [] -> [res] */
  37160. DUK_DDD(DUK_DDDPRINT("-> %!T (base is buffer, key is 'length' after coercion -> "
  37161. "return buffer length)",
  37162. (duk_tval *) duk_get_tval(ctx, -1)));
  37163. return 1;
  37164. }
  37165. DUK_DDD(DUK_DDDPRINT("base object is a buffer, start lookup from buffer prototype"));
  37166. curr = thr->builtins[DUK_BIDX_BUFFER_PROTOTYPE];
  37167. goto lookup; /* avoid double coercion */
  37168. }
  37169. case DUK_TAG_POINTER: {
  37170. DUK_DDD(DUK_DDDPRINT("base object is a pointer, start lookup from pointer prototype"));
  37171. curr = thr->builtins[DUK_BIDX_POINTER_PROTOTYPE];
  37172. break;
  37173. }
  37174. case DUK_TAG_LIGHTFUNC: {
  37175. duk_int_t lf_flags = DUK_TVAL_GET_LIGHTFUNC_FLAGS(tv_obj);
  37176. /* Must coerce key: if key is an object, it may coerce to e.g. 'length'. */
  37177. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37178. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  37179. duk_int_t lf_len = DUK_LFUNC_FLAGS_GET_LENGTH(lf_flags);
  37180. duk_pop(ctx);
  37181. duk_push_int(ctx, lf_len);
  37182. return 1;
  37183. } else if (key == DUK_HTHREAD_STRING_NAME(thr)) {
  37184. duk_pop(ctx);
  37185. duk_push_lightfunc_name(ctx, tv_obj);
  37186. return 1;
  37187. }
  37188. DUK_DDD(DUK_DDDPRINT("base object is a lightfunc, start lookup from function prototype"));
  37189. curr = thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE];
  37190. goto lookup; /* avoid double coercion */
  37191. }
  37192. #if defined(DUK_USE_FASTINT)
  37193. case DUK_TAG_FASTINT:
  37194. #endif
  37195. default: {
  37196. /* number */
  37197. DUK_DDD(DUK_DDDPRINT("base object is a number, start lookup from number prototype"));
  37198. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_obj));
  37199. curr = thr->builtins[DUK_BIDX_NUMBER_PROTOTYPE];
  37200. break;
  37201. }
  37202. }
  37203. /* key coercion (unless already coerced above) */
  37204. DUK_ASSERT(key == NULL);
  37205. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37206. DUK_ASSERT(key != NULL);
  37207. /*
  37208. * Property lookup
  37209. */
  37210. lookup:
  37211. /* [key] (coerced) */
  37212. DUK_ASSERT(curr != NULL);
  37213. DUK_ASSERT(key != NULL);
  37214. sanity = DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY;
  37215. do {
  37216. if (!duk__get_own_property_desc_raw(thr, curr, key, arr_idx, &desc, DUK__DESC_FLAG_PUSH_VALUE)) {
  37217. goto next_in_chain;
  37218. }
  37219. if (desc.get != NULL) {
  37220. /* accessor with defined getter */
  37221. DUK_ASSERT((desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) != 0);
  37222. duk_pop(ctx); /* [key undefined] -> [key] */
  37223. duk_push_hobject(ctx, desc.get);
  37224. duk_push_tval(ctx, tv_obj); /* note: original, uncoerced base */
  37225. #ifdef DUK_USE_NONSTD_GETTER_KEY_ARGUMENT
  37226. duk_dup(ctx, -3);
  37227. duk_call_method(ctx, 1); /* [key getter this key] -> [key retval] */
  37228. #else
  37229. duk_call_method(ctx, 0); /* [key getter this] -> [key retval] */
  37230. #endif
  37231. } else {
  37232. /* [key value] or [key undefined] */
  37233. /* data property or accessor without getter */
  37234. DUK_ASSERT(((desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) == 0) ||
  37235. (desc.get == NULL));
  37236. /* if accessor without getter, return value is undefined */
  37237. DUK_ASSERT(((desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) == 0) ||
  37238. duk_is_undefined(ctx, -1));
  37239. /* Note: for an accessor without getter, falling through to
  37240. * check for "caller" exotic behavior is unnecessary as
  37241. * "undefined" will never activate the behavior. But it does
  37242. * no harm, so we'll do it anyway.
  37243. */
  37244. }
  37245. goto found; /* [key result] */
  37246. next_in_chain:
  37247. /* XXX: option to pretend property doesn't exist if sanity limit is
  37248. * hit might be useful.
  37249. */
  37250. if (sanity-- == 0) {
  37251. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_PROTOTYPE_CHAIN_LIMIT);
  37252. }
  37253. curr = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, curr);
  37254. } while (curr);
  37255. /*
  37256. * Not found
  37257. */
  37258. duk_to_undefined(ctx, -1); /* [key] -> [undefined] (default value) */
  37259. DUK_DDD(DUK_DDDPRINT("-> %!T (not found)", (duk_tval *) duk_get_tval(ctx, -1)));
  37260. return 0;
  37261. /*
  37262. * Found; post-processing (Function and arguments objects)
  37263. */
  37264. found:
  37265. /* [key result] */
  37266. #if !defined(DUK_USE_NONSTD_FUNC_CALLER_PROPERTY)
  37267. /* Special behavior for 'caller' property of (non-bound) function objects
  37268. * and non-strict Arguments objects: if 'caller' -value- (!) is a strict
  37269. * mode function, throw a TypeError (E5 Sections 15.3.5.4, 10.6).
  37270. * Quite interestingly, a non-strict function with no formal arguments
  37271. * will get an arguments object -without- special 'caller' behavior!
  37272. *
  37273. * The E5.1 spec is a bit ambiguous if this special behavior applies when
  37274. * a bound function is the base value (not the 'caller' value): Section
  37275. * 15.3.4.5 (describing bind()) states that [[Get]] for bound functions
  37276. * matches that of Section 15.3.5.4 ([[Get]] for Function instances).
  37277. * However, Section 13.3.5.4 has "NOTE: Function objects created using
  37278. * Function.prototype.bind use the default [[Get]] internal method."
  37279. * The current implementation assumes this means that bound functions
  37280. * should not have the special [[Get]] behavior.
  37281. *
  37282. * The E5.1 spec is also a bit unclear if the TypeError throwing is
  37283. * applied if the 'caller' value is a strict bound function. The
  37284. * current implementation will throw even for both strict non-bound
  37285. * and strict bound functions.
  37286. *
  37287. * See test-dev-strict-func-as-caller-prop-value.js for quite extensive
  37288. * tests.
  37289. *
  37290. * This exotic behavior is disabled when the non-standard 'caller' property
  37291. * is enabled, as it conflicts with the free use of 'caller'.
  37292. */
  37293. if (key == DUK_HTHREAD_STRING_CALLER(thr) &&
  37294. DUK_TVAL_IS_OBJECT(tv_obj)) {
  37295. duk_hobject *orig = DUK_TVAL_GET_OBJECT(tv_obj);
  37296. DUK_ASSERT(orig != NULL);
  37297. if (DUK_HOBJECT_IS_NONBOUND_FUNCTION(orig) ||
  37298. DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(orig)) {
  37299. duk_hobject *h;
  37300. /* XXX: The TypeError is currently not applied to bound
  37301. * functions because the 'strict' flag is not copied by
  37302. * bind(). This may or may not be correct, the specification
  37303. * only refers to the value being a "strict mode Function
  37304. * object" which is ambiguous.
  37305. */
  37306. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(orig));
  37307. h = duk_get_hobject(ctx, -1); /* NULL if not an object */
  37308. if (h &&
  37309. DUK_HOBJECT_IS_FUNCTION(h) &&
  37310. DUK_HOBJECT_HAS_STRICT(h)) {
  37311. /* XXX: sufficient to check 'strict', assert for 'is function' */
  37312. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_STRICT_CALLER_READ);
  37313. }
  37314. }
  37315. }
  37316. #endif /* !DUK_USE_NONSTD_FUNC_CALLER_PROPERTY */
  37317. duk_remove(ctx, -2); /* [key result] -> [result] */
  37318. DUK_DDD(DUK_DDDPRINT("-> %!T (found)", (duk_tval *) duk_get_tval(ctx, -1)));
  37319. return 1;
  37320. }
  37321. /*
  37322. * HASPROP: Ecmascript property existence check ("in" operator).
  37323. *
  37324. * Interestingly, the 'in' operator does not do any coercion of
  37325. * the target object.
  37326. */
  37327. DUK_INTERNAL duk_bool_t duk_hobject_hasprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key) {
  37328. duk_context *ctx = (duk_context *) thr;
  37329. duk_tval tv_key_copy;
  37330. duk_hobject *obj;
  37331. duk_hstring *key;
  37332. duk_uint32_t arr_idx;
  37333. duk_bool_t rc;
  37334. duk_propdesc desc;
  37335. DUK_DDD(DUK_DDDPRINT("hasprop: thr=%p, obj=%p, key=%p (obj -> %!T, key -> %!T)",
  37336. (void *) thr, (void *) tv_obj, (void *) tv_key,
  37337. (duk_tval *) tv_obj, (duk_tval *) tv_key));
  37338. DUK_ASSERT(thr != NULL);
  37339. DUK_ASSERT(thr->heap != NULL);
  37340. DUK_ASSERT(tv_obj != NULL);
  37341. DUK_ASSERT(tv_key != NULL);
  37342. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  37343. DUK_TVAL_SET_TVAL(&tv_key_copy, tv_key);
  37344. tv_key = &tv_key_copy;
  37345. /*
  37346. * The 'in' operator requires an object as its right hand side,
  37347. * throwing a TypeError unconditionally if this is not the case.
  37348. *
  37349. * However, lightfuncs need to behave like fully fledged objects
  37350. * here to be maximally transparent, so we need to handle them
  37351. * here.
  37352. */
  37353. /* XXX: Refactor key coercion so that it's only called once. It can't
  37354. * be trivially lifted here because the object must be type checked
  37355. * first.
  37356. */
  37357. if (DUK_TVAL_IS_OBJECT(tv_obj)) {
  37358. obj = DUK_TVAL_GET_OBJECT(tv_obj);
  37359. DUK_ASSERT(obj != NULL);
  37360. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37361. } else if (DUK_TVAL_IS_LIGHTFUNC(tv_obj)) {
  37362. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37363. if (duk__key_is_lightfunc_ownprop(thr, key)) {
  37364. /* FOUND */
  37365. rc = 1;
  37366. goto pop_and_return;
  37367. }
  37368. /* If not found, resume existence check from Function.prototype.
  37369. * We can just substitute the value in this case; nothing will
  37370. * need the original base value (as would be the case with e.g.
  37371. * setters/getters.
  37372. */
  37373. obj = thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE];
  37374. } else {
  37375. /* Note: unconditional throw */
  37376. DUK_DDD(DUK_DDDPRINT("base object is not an object -> reject"));
  37377. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INVALID_BASE);
  37378. }
  37379. /* XXX: fast path for arrays? */
  37380. DUK_ASSERT(key != NULL);
  37381. DUK_ASSERT(obj != NULL);
  37382. DUK_UNREF(arr_idx);
  37383. #if defined(DUK_USE_ES6_PROXY)
  37384. if (DUK_UNLIKELY(DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(obj))) {
  37385. duk_hobject *h_target;
  37386. duk_bool_t tmp_bool;
  37387. /* XXX: the key in 'key in obj' is string coerced before we're called
  37388. * (which is the required behavior in E5/E5.1/E6) so the key is a string
  37389. * here already.
  37390. */
  37391. if (duk__proxy_check_prop(thr, obj, DUK_STRIDX_HAS, tv_key, &h_target)) {
  37392. /* [ ... key trap handler ] */
  37393. DUK_DDD(DUK_DDDPRINT("-> proxy object 'has' for key %!T", (duk_tval *) tv_key));
  37394. duk_push_hobject(ctx, h_target); /* target */
  37395. duk_push_tval(ctx, tv_key); /* P */
  37396. duk_call_method(ctx, 2 /*nargs*/);
  37397. tmp_bool = duk_to_boolean(ctx, -1);
  37398. if (!tmp_bool) {
  37399. /* Target object must be checked for a conflicting
  37400. * non-configurable property.
  37401. */
  37402. if (duk__get_own_property_desc_raw(thr, h_target, key, arr_idx, &desc, 0 /*flags*/)) { /* don't push value */
  37403. DUK_DDD(DUK_DDDPRINT("proxy 'has': target has matching property %!O, check for "
  37404. "conflicting property; desc.flags=0x%08lx, "
  37405. "desc.get=%p, desc.set=%p",
  37406. (duk_heaphdr *) key, (unsigned long) desc.flags,
  37407. (void *) desc.get, (void *) desc.set));
  37408. /* XXX: Extensibility check for target uses IsExtensible(). If we
  37409. * implemented the isExtensible trap and didn't reject proxies as
  37410. * proxy targets, it should be respected here.
  37411. */
  37412. if (!((desc.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) && /* property is configurable and */
  37413. DUK_HOBJECT_HAS_EXTENSIBLE(h_target))) { /* ... target is extensible */
  37414. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REJECTED);
  37415. }
  37416. }
  37417. }
  37418. duk_pop_2(ctx); /* [ key trap_result ] -> [] */
  37419. return tmp_bool;
  37420. }
  37421. obj = h_target; /* resume check from proxy target */
  37422. }
  37423. #endif /* DUK_USE_ES6_PROXY */
  37424. /* XXX: inline into a prototype walking loop? */
  37425. rc = duk__get_property_desc(thr, obj, key, &desc, 0 /*flags*/); /* don't push value */
  37426. /* fall through */
  37427. pop_and_return:
  37428. duk_pop(ctx); /* [ key ] -> [] */
  37429. return rc;
  37430. }
  37431. /*
  37432. * HASPROP variant used internally.
  37433. *
  37434. * This primitive must never throw an error, callers rely on this.
  37435. * In particular, don't throw an error for prototype loops; instead,
  37436. * pretend like the property doesn't exist if a prototype sanity limit
  37437. * is reached.
  37438. *
  37439. * Does not implement proxy behavior: if applied to a proxy object,
  37440. * returns key existence on the proxy object itself.
  37441. */
  37442. DUK_INTERNAL duk_bool_t duk_hobject_hasprop_raw(duk_hthread *thr, duk_hobject *obj, duk_hstring *key) {
  37443. duk_propdesc dummy;
  37444. DUK_ASSERT(thr != NULL);
  37445. DUK_ASSERT(thr->heap != NULL);
  37446. DUK_ASSERT(obj != NULL);
  37447. DUK_ASSERT(key != NULL);
  37448. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  37449. return duk__get_property_desc(thr, obj, key, &dummy, DUK__DESC_FLAG_IGNORE_PROTOLOOP); /* don't push value */
  37450. }
  37451. /*
  37452. * Helper: handle Array object 'length' write which automatically
  37453. * deletes properties, see E5 Section 15.4.5.1, step 3. This is
  37454. * quite tricky to get right.
  37455. *
  37456. * Used by duk_hobject_putprop().
  37457. */
  37458. DUK_LOCAL duk_uint32_t duk__get_old_array_length(duk_hthread *thr, duk_hobject *obj, duk_propdesc *temp_desc) {
  37459. duk_bool_t rc;
  37460. duk_tval *tv;
  37461. duk_uint32_t res;
  37462. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  37463. /* This function is only called for objects with array exotic behavior.
  37464. * The [[DefineOwnProperty]] algorithm for arrays requires that
  37465. * 'length' can never have a value outside the unsigned 32-bit range,
  37466. * attempt to write such a value is a RangeError. Here we can thus
  37467. * assert for this. When Duktape internals go around the official
  37468. * property write interface (doesn't happen often) this assumption is
  37469. * easy to accidentally break, so such code must be written carefully.
  37470. * See test-bi-array-push-maxlen.js.
  37471. */
  37472. rc = duk__get_own_property_desc_raw(thr, obj, DUK_HTHREAD_STRING_LENGTH(thr), DUK__NO_ARRAY_INDEX, temp_desc, 0 /*flags*/); /* don't push value */
  37473. DUK_UNREF(rc);
  37474. DUK_ASSERT(rc != 0); /* arrays MUST have a 'length' property */
  37475. DUK_ASSERT(temp_desc->e_idx >= 0);
  37476. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, temp_desc->e_idx);
  37477. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv)); /* array 'length' is always a number, as we coerce it */
  37478. DUK_ASSERT(DUK_TVAL_GET_NUMBER(tv) >= 0.0);
  37479. DUK_ASSERT(DUK_TVAL_GET_NUMBER(tv) <= (double) 0xffffffffUL);
  37480. DUK_ASSERT((duk_double_t) (duk_uint32_t) DUK_TVAL_GET_NUMBER(tv) == DUK_TVAL_GET_NUMBER(tv));
  37481. #if defined(DUK_USE_FASTINT)
  37482. /* Downgrade checks are not made everywhere, so 'length' is not always
  37483. * a fastint (it is a number though). This can be removed once length
  37484. * is always guaranteed to be a fastint.
  37485. */
  37486. DUK_ASSERT(DUK_TVAL_IS_FASTINT(tv) || DUK_TVAL_IS_DOUBLE(tv));
  37487. if (DUK_TVAL_IS_FASTINT(tv)) {
  37488. res = (duk_uint32_t) DUK_TVAL_GET_FASTINT_U32(tv);
  37489. } else {
  37490. res = (duk_uint32_t) DUK_TVAL_GET_DOUBLE(tv);
  37491. }
  37492. #else
  37493. res = (duk_uint32_t) DUK_TVAL_GET_NUMBER(tv);
  37494. #endif /* DUK_USE_FASTINT */
  37495. return res;
  37496. }
  37497. DUK_LOCAL duk_uint32_t duk__to_new_array_length_checked(duk_hthread *thr) {
  37498. duk_context *ctx = (duk_context *) thr;
  37499. duk_uint32_t res;
  37500. duk_double_t d;
  37501. /* Input value should be on stack top and will be coerced and
  37502. * popped. Refuse to update an Array's 'length' to a value
  37503. * outside the 32-bit range. Negative zero is accepted as zero.
  37504. */
  37505. /* XXX: fastint */
  37506. d = duk_to_number(ctx, -1);
  37507. res = (duk_uint32_t) d;
  37508. if ((duk_double_t) res != d) {
  37509. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_INVALID_ARRAY_LENGTH);
  37510. }
  37511. duk_pop(ctx);
  37512. return res;
  37513. }
  37514. /* Delete elements required by a smaller length, taking into account
  37515. * potentially non-configurable elements. Returns non-zero if all
  37516. * elements could be deleted, and zero if all or some elements could
  37517. * not be deleted. Also writes final "target length" to 'out_result_len'.
  37518. * This is the length value that should go into the 'length' property
  37519. * (must be set by the caller). Never throws an error.
  37520. */
  37521. DUK_LOCAL
  37522. duk_bool_t duk__handle_put_array_length_smaller(duk_hthread *thr,
  37523. duk_hobject *obj,
  37524. duk_uint32_t old_len,
  37525. duk_uint32_t new_len,
  37526. duk_bool_t force_flag,
  37527. duk_uint32_t *out_result_len) {
  37528. duk_uint32_t target_len;
  37529. duk_uint_fast32_t i;
  37530. duk_uint32_t arr_idx;
  37531. duk_hstring *key;
  37532. duk_tval *tv;
  37533. duk_tval tv_tmp;
  37534. duk_bool_t rc;
  37535. DUK_DDD(DUK_DDDPRINT("new array length smaller than old (%ld -> %ld), "
  37536. "probably need to remove elements",
  37537. (long) old_len, (long) new_len));
  37538. /*
  37539. * New length is smaller than old length, need to delete properties above
  37540. * the new length.
  37541. *
  37542. * If array part exists, this is straightforward: array entries cannot
  37543. * be non-configurable so this is guaranteed to work.
  37544. *
  37545. * If array part does not exist, array-indexed values are scattered
  37546. * in the entry part, and some may not be configurable (preventing length
  37547. * from becoming lower than their index + 1). To handle the algorithm
  37548. * in E5 Section 15.4.5.1, step l correctly, we scan the entire property
  37549. * set twice.
  37550. */
  37551. DUK_ASSERT(thr != NULL);
  37552. DUK_ASSERT(obj != NULL);
  37553. DUK_ASSERT(new_len < old_len);
  37554. DUK_ASSERT(out_result_len != NULL);
  37555. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  37556. if (DUK_HOBJECT_HAS_ARRAY_PART(obj)) {
  37557. /*
  37558. * All defined array-indexed properties are in the array part
  37559. * (we assume the array part is comprehensive), and all array
  37560. * entries are writable, configurable, and enumerable. Thus,
  37561. * nothing can prevent array entries from being deleted.
  37562. */
  37563. DUK_DDD(DUK_DDDPRINT("have array part, easy case"));
  37564. if (old_len < DUK_HOBJECT_GET_ASIZE(obj)) {
  37565. /* XXX: assertion that entries >= old_len are already unused */
  37566. i = old_len;
  37567. } else {
  37568. i = DUK_HOBJECT_GET_ASIZE(obj);
  37569. }
  37570. DUK_ASSERT(i <= DUK_HOBJECT_GET_ASIZE(obj));
  37571. while (i > new_len) {
  37572. i--;
  37573. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, i);
  37574. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  37575. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  37576. DUK_TVAL_DECREF(thr, &tv_tmp);
  37577. }
  37578. *out_result_len = new_len;
  37579. return 1;
  37580. } else {
  37581. /*
  37582. * Entries part is a bit more complex
  37583. */
  37584. /* Stage 1: find highest preventing non-configurable entry (if any).
  37585. * When forcing, ignore non-configurability.
  37586. */
  37587. DUK_DDD(DUK_DDDPRINT("no array part, slow case"));
  37588. DUK_DDD(DUK_DDDPRINT("array length write, no array part, stage 1: find target_len "
  37589. "(highest preventing non-configurable entry (if any))"));
  37590. target_len = new_len;
  37591. if (force_flag) {
  37592. DUK_DDD(DUK_DDDPRINT("array length write, no array part; force flag -> skip stage 1"));
  37593. goto skip_stage1;
  37594. }
  37595. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(obj); i++) {
  37596. key = DUK_HOBJECT_E_GET_KEY(thr->heap, obj, i);
  37597. if (!key) {
  37598. DUK_DDD(DUK_DDDPRINT("skip entry index %ld: null key", (long) i));
  37599. continue;
  37600. }
  37601. if (!DUK_HSTRING_HAS_ARRIDX(key)) {
  37602. DUK_DDD(DUK_DDDPRINT("skip entry index %ld: key not an array index", (long) i));
  37603. continue;
  37604. }
  37605. DUK_ASSERT(DUK_HSTRING_HAS_ARRIDX(key)); /* XXX: macro checks for array index flag, which is unnecessary here */
  37606. arr_idx = DUK_HSTRING_GET_ARRIDX_SLOW(key);
  37607. DUK_ASSERT(arr_idx != DUK__NO_ARRAY_INDEX);
  37608. DUK_ASSERT(arr_idx < old_len); /* consistency requires this */
  37609. if (arr_idx < new_len) {
  37610. DUK_DDD(DUK_DDDPRINT("skip entry index %ld: key is array index %ld, below new_len",
  37611. (long) i, (long) arr_idx));
  37612. continue;
  37613. }
  37614. if (DUK_HOBJECT_E_SLOT_IS_CONFIGURABLE(thr->heap, obj, i)) {
  37615. DUK_DDD(DUK_DDDPRINT("skip entry index %ld: key is a relevant array index %ld, but configurable",
  37616. (long) i, (long) arr_idx));
  37617. continue;
  37618. }
  37619. /* relevant array index is non-configurable, blocks write */
  37620. if (arr_idx >= target_len) {
  37621. DUK_DDD(DUK_DDDPRINT("entry at index %ld has arr_idx %ld, is not configurable, "
  37622. "update target_len %ld -> %ld",
  37623. (long) i, (long) arr_idx, (long) target_len,
  37624. (long) (arr_idx + 1)));
  37625. target_len = arr_idx + 1;
  37626. }
  37627. }
  37628. skip_stage1:
  37629. /* stage 2: delete configurable entries above target length */
  37630. DUK_DDD(DUK_DDDPRINT("old_len=%ld, new_len=%ld, target_len=%ld",
  37631. (long) old_len, (long) new_len, (long) target_len));
  37632. DUK_DDD(DUK_DDDPRINT("array length write, no array part, stage 2: remove "
  37633. "entries >= target_len"));
  37634. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(obj); i++) {
  37635. key = DUK_HOBJECT_E_GET_KEY(thr->heap, obj, i);
  37636. if (!key) {
  37637. DUK_DDD(DUK_DDDPRINT("skip entry index %ld: null key", (long) i));
  37638. continue;
  37639. }
  37640. if (!DUK_HSTRING_HAS_ARRIDX(key)) {
  37641. DUK_DDD(DUK_DDDPRINT("skip entry index %ld: key not an array index", (long) i));
  37642. continue;
  37643. }
  37644. DUK_ASSERT(DUK_HSTRING_HAS_ARRIDX(key)); /* XXX: macro checks for array index flag, which is unnecessary here */
  37645. arr_idx = DUK_HSTRING_GET_ARRIDX_SLOW(key);
  37646. DUK_ASSERT(arr_idx != DUK__NO_ARRAY_INDEX);
  37647. DUK_ASSERT(arr_idx < old_len); /* consistency requires this */
  37648. if (arr_idx < target_len) {
  37649. DUK_DDD(DUK_DDDPRINT("skip entry index %ld: key is array index %ld, below target_len",
  37650. (long) i, (long) arr_idx));
  37651. continue;
  37652. }
  37653. DUK_ASSERT(force_flag || DUK_HOBJECT_E_SLOT_IS_CONFIGURABLE(thr->heap, obj, i)); /* stage 1 guarantees */
  37654. DUK_DDD(DUK_DDDPRINT("delete entry index %ld: key is array index %ld",
  37655. (long) i, (long) arr_idx));
  37656. /*
  37657. * Slow delete, but we don't care as we're already in a very slow path.
  37658. * The delete always succeeds: key has no exotic behavior, property
  37659. * is configurable, and no resize occurs.
  37660. */
  37661. rc = duk_hobject_delprop_raw(thr, obj, key, force_flag ? DUK_DELPROP_FLAG_FORCE : 0);
  37662. DUK_UNREF(rc);
  37663. DUK_ASSERT(rc != 0);
  37664. }
  37665. /* stage 3: update length (done by caller), decide return code */
  37666. DUK_DDD(DUK_DDDPRINT("array length write, no array part, stage 3: update length (done by caller)"));
  37667. *out_result_len = target_len;
  37668. if (target_len == new_len) {
  37669. DUK_DDD(DUK_DDDPRINT("target_len matches new_len, return success"));
  37670. return 1;
  37671. }
  37672. DUK_DDD(DUK_DDDPRINT("target_len does not match new_len (some entry prevented "
  37673. "full length adjustment), return error"));
  37674. return 0;
  37675. }
  37676. DUK_UNREACHABLE();
  37677. }
  37678. /* XXX: is valstack top best place for argument? */
  37679. DUK_LOCAL duk_bool_t duk__handle_put_array_length(duk_hthread *thr, duk_hobject *obj) {
  37680. duk_context *ctx = (duk_context *) thr;
  37681. duk_propdesc desc;
  37682. duk_uint32_t old_len;
  37683. duk_uint32_t new_len;
  37684. duk_uint32_t result_len;
  37685. duk_tval *tv;
  37686. duk_bool_t rc;
  37687. DUK_DDD(DUK_DDDPRINT("handling a put operation to array 'length' exotic property, "
  37688. "new val: %!T",
  37689. (duk_tval *) duk_get_tval(ctx, -1)));
  37690. DUK_ASSERT(thr != NULL);
  37691. DUK_ASSERT(ctx != NULL);
  37692. DUK_ASSERT(obj != NULL);
  37693. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  37694. DUK_ASSERT(duk_is_valid_index(ctx, -1));
  37695. /*
  37696. * Get old and new length
  37697. */
  37698. old_len = duk__get_old_array_length(thr, obj, &desc);
  37699. duk_dup(ctx, -1); /* [in_val in_val] */
  37700. new_len = duk__to_new_array_length_checked(thr); /* -> [in_val] */
  37701. DUK_DDD(DUK_DDDPRINT("old_len=%ld, new_len=%ld", (long) old_len, (long) new_len));
  37702. /*
  37703. * Writability check
  37704. */
  37705. if (!(desc.flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  37706. DUK_DDD(DUK_DDDPRINT("length is not writable, fail"));
  37707. return 0;
  37708. }
  37709. /*
  37710. * New length not lower than old length => no changes needed
  37711. * (not even array allocation).
  37712. */
  37713. if (new_len >= old_len) {
  37714. DUK_DDD(DUK_DDDPRINT("new length is higher than old length, just update length, no deletions"));
  37715. DUK_ASSERT(desc.e_idx >= 0);
  37716. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, desc.e_idx));
  37717. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, desc.e_idx);
  37718. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  37719. /* no decref needed for a number */
  37720. #if defined(DUK_USE_FASTINT)
  37721. DUK_TVAL_SET_FASTINT_U32(tv, new_len);
  37722. #else
  37723. DUK_TVAL_SET_NUMBER(tv, (duk_double_t) new_len);
  37724. #endif
  37725. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  37726. return 1;
  37727. }
  37728. DUK_DDD(DUK_DDDPRINT("new length is lower than old length, probably must delete entries"));
  37729. /*
  37730. * New length lower than old length => delete elements, then
  37731. * update length.
  37732. *
  37733. * Note: even though a bunch of elements have been deleted, the 'desc' is
  37734. * still valid as properties haven't been resized (and entries compacted).
  37735. */
  37736. rc = duk__handle_put_array_length_smaller(thr, obj, old_len, new_len, 0 /*force_flag*/, &result_len);
  37737. DUK_ASSERT(result_len >= new_len && result_len <= old_len);
  37738. DUK_ASSERT(desc.e_idx >= 0);
  37739. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, desc.e_idx));
  37740. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, desc.e_idx);
  37741. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  37742. /* no decref needed for a number */
  37743. #if defined(DUK_USE_FASTINT)
  37744. DUK_TVAL_SET_FASTINT_U32(tv, result_len);
  37745. #else
  37746. DUK_TVAL_SET_NUMBER(tv, (duk_double_t) result_len);
  37747. #endif
  37748. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  37749. /* XXX: shrink array allocation or entries compaction here? */
  37750. return rc;
  37751. }
  37752. /*
  37753. * PUTPROP: Ecmascript property write.
  37754. *
  37755. * Unlike Ecmascript primitive which returns nothing, returns 1 to indicate
  37756. * success and 0 to indicate failure (assuming throw is not set).
  37757. *
  37758. * This is an extremely tricky function. Some examples:
  37759. *
  37760. * * Currently a decref may trigger a GC, which may compact an object's
  37761. * property allocation. Consequently, any entry indices (e_idx) will
  37762. * be potentially invalidated by a decref.
  37763. *
  37764. * * Exotic behaviors (strings, arrays, arguments object) require,
  37765. * among other things:
  37766. *
  37767. * - Preprocessing before and postprocessing after an actual property
  37768. * write. For example, array index write requires pre-checking the
  37769. * array 'length' property for access control, and may require an
  37770. * array 'length' update after the actual write has succeeded (but
  37771. * not if it fails).
  37772. *
  37773. * - Deletion of multiple entries, as a result of array 'length' write.
  37774. *
  37775. * * Input values are taken as pointers which may point to the valstack.
  37776. * If valstack is resized because of the put (this may happen at least
  37777. * when the array part is abandoned), the pointers can be invalidated.
  37778. * (We currently make a copy of all of the input values to avoid issues.)
  37779. */
  37780. DUK_INTERNAL duk_bool_t duk_hobject_putprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key, duk_tval *tv_val, duk_bool_t throw_flag) {
  37781. duk_context *ctx = (duk_context *) thr;
  37782. duk_tval tv_obj_copy;
  37783. duk_tval tv_key_copy;
  37784. duk_tval tv_val_copy;
  37785. duk_hobject *orig = NULL; /* NULL if tv_obj is primitive */
  37786. duk_hobject *curr;
  37787. duk_hstring *key = NULL;
  37788. duk_propdesc desc;
  37789. duk_tval *tv;
  37790. duk_uint32_t arr_idx;
  37791. duk_bool_t rc;
  37792. duk_int_t e_idx;
  37793. duk_uint_t sanity;
  37794. duk_uint32_t new_array_length = 0; /* 0 = no update */
  37795. DUK_DDD(DUK_DDDPRINT("putprop: thr=%p, obj=%p, key=%p, val=%p, throw=%ld "
  37796. "(obj -> %!T, key -> %!T, val -> %!T)",
  37797. (void *) thr, (void *) tv_obj, (void *) tv_key, (void *) tv_val,
  37798. (long) throw_flag, (duk_tval *) tv_obj, (duk_tval *) tv_key, (duk_tval *) tv_val));
  37799. DUK_ASSERT(thr != NULL);
  37800. DUK_ASSERT(thr->heap != NULL);
  37801. DUK_ASSERT(ctx != NULL);
  37802. DUK_ASSERT(tv_obj != NULL);
  37803. DUK_ASSERT(tv_key != NULL);
  37804. DUK_ASSERT(tv_val != NULL);
  37805. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  37806. /*
  37807. * Make a copy of tv_obj, tv_key, and tv_val to avoid any issues of
  37808. * them being invalidated by a valstack resize.
  37809. *
  37810. * XXX: this is an overkill for some paths, so optimize this later
  37811. * (or maybe switch to a stack arguments model entirely).
  37812. */
  37813. DUK_TVAL_SET_TVAL(&tv_obj_copy, tv_obj);
  37814. DUK_TVAL_SET_TVAL(&tv_key_copy, tv_key);
  37815. DUK_TVAL_SET_TVAL(&tv_val_copy, tv_val);
  37816. tv_obj = &tv_obj_copy;
  37817. tv_key = &tv_key_copy;
  37818. tv_val = &tv_val_copy;
  37819. /*
  37820. * Coercion and fast path processing.
  37821. */
  37822. switch (DUK_TVAL_GET_TAG(tv_obj)) {
  37823. case DUK_TAG_UNDEFINED:
  37824. case DUK_TAG_NULL: {
  37825. /* Note: unconditional throw */
  37826. DUK_DDD(DUK_DDDPRINT("base object is undefined or null -> reject (object=%!iT)",
  37827. (duk_tval *) tv_obj));
  37828. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INVALID_BASE);
  37829. return 0;
  37830. }
  37831. case DUK_TAG_BOOLEAN: {
  37832. DUK_DDD(DUK_DDDPRINT("base object is a boolean, start lookup from boolean prototype"));
  37833. curr = thr->builtins[DUK_BIDX_BOOLEAN_PROTOTYPE];
  37834. break;
  37835. }
  37836. case DUK_TAG_STRING: {
  37837. duk_hstring *h = DUK_TVAL_GET_STRING(tv_obj);
  37838. /*
  37839. * Note: currently no fast path for array index writes.
  37840. * They won't be possible anyway as strings are immutable.
  37841. */
  37842. DUK_ASSERT(key == NULL);
  37843. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37844. DUK_ASSERT(key != NULL);
  37845. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  37846. goto fail_not_writable;
  37847. }
  37848. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  37849. arr_idx < DUK_HSTRING_GET_CHARLEN(h)) {
  37850. goto fail_not_writable;
  37851. }
  37852. DUK_DDD(DUK_DDDPRINT("base object is a string, start lookup from string prototype"));
  37853. curr = thr->builtins[DUK_BIDX_STRING_PROTOTYPE];
  37854. goto lookup; /* avoid double coercion */
  37855. }
  37856. case DUK_TAG_OBJECT: {
  37857. orig = DUK_TVAL_GET_OBJECT(tv_obj);
  37858. DUK_ASSERT(orig != NULL);
  37859. /* The fast path for array property put is not fully compliant:
  37860. * If one places conflicting number-indexed properties into
  37861. * Array.prototype (for example, a non-writable Array.prototype[7])
  37862. * the fast path will incorrectly ignore them.
  37863. *
  37864. * This fast path could be made compliant by falling through
  37865. * to the slow path if the previous value was UNDEFINED_UNUSED.
  37866. * This would also remove the need to check for extensibility.
  37867. * Right now a non-extensible array is slower than an extensible
  37868. * one as far as writes are concerned.
  37869. *
  37870. * The fast path behavior is documented in more detail here:
  37871. * ecmascript-testcases/test-misc-array-fast-write.js
  37872. */
  37873. if (DUK_HOBJECT_HAS_EXOTIC_ARRAY(orig) &&
  37874. DUK_HOBJECT_HAS_ARRAY_PART(orig) &&
  37875. DUK_HOBJECT_HAS_EXTENSIBLE(orig) &&
  37876. DUK_TVAL_IS_NUMBER(tv_key)) {
  37877. arr_idx = duk__tval_number_to_arr_idx(tv_key);
  37878. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  37879. arr_idx < DUK_HOBJECT_GET_ASIZE(orig)) { /* for resizing of array part, use slow path */
  37880. duk_tval tv_tmp;
  37881. duk_uint32_t old_len, new_len;
  37882. DUK_ASSERT(arr_idx < DUK_HOBJECT_GET_ASIZE(orig));
  37883. old_len = duk__get_old_array_length(thr, orig, &desc);
  37884. if (arr_idx >= old_len) {
  37885. DUK_DDD(DUK_DDDPRINT("write new array entry requires length update "
  37886. "(arr_idx=%ld, old_len=%ld)",
  37887. (long) arr_idx, (long) old_len));
  37888. if (!(desc.flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  37889. DUK_DD(DUK_DDPRINT("attempt to extend array, but array 'length' is not writable"));
  37890. goto fail_not_writable;
  37891. }
  37892. new_len = arr_idx + 1;
  37893. /* No resize has occurred so desc.e_idx is still OK */
  37894. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, orig, desc.e_idx);
  37895. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  37896. #if defined(DUK_USE_FASTINT)
  37897. DUK_TVAL_SET_FASTINT_U32(tv, new_len); /* no need for decref/incref because value is a number */
  37898. #else
  37899. DUK_TVAL_SET_NUMBER(tv, (duk_double_t) new_len); /* no need for decref/incref because value is a number */
  37900. #endif
  37901. } else {
  37902. ;
  37903. }
  37904. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, orig, arr_idx);
  37905. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  37906. DUK_TVAL_SET_TVAL(tv, tv_val);
  37907. DUK_TVAL_INCREF(thr, tv);
  37908. DUK_TVAL_DECREF(thr, &tv_tmp); /* note: may trigger gc and props compaction, must be last */
  37909. DUK_DDD(DUK_DDDPRINT("array fast path success for index %ld", (long) arr_idx));
  37910. return 1;
  37911. }
  37912. }
  37913. #if defined(DUK_USE_ES6_PROXY)
  37914. if (DUK_UNLIKELY(DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(orig))) {
  37915. duk_hobject *h_target;
  37916. duk_bool_t tmp_bool;
  37917. if (duk__proxy_check_prop(thr, orig, DUK_STRIDX_SET, tv_key, &h_target)) {
  37918. /* -> [ ... trap handler ] */
  37919. DUK_DDD(DUK_DDDPRINT("-> proxy object 'set' for key %!T", (duk_tval *) tv_key));
  37920. duk_push_hobject(ctx, h_target); /* target */
  37921. duk_push_tval(ctx, tv_key); /* P */
  37922. duk_push_tval(ctx, tv_val); /* V */
  37923. duk_push_tval(ctx, tv_obj); /* Receiver: Proxy object */
  37924. duk_call_method(ctx, 4 /*nargs*/);
  37925. tmp_bool = duk_to_boolean(ctx, -1);
  37926. duk_pop(ctx);
  37927. if (!tmp_bool) {
  37928. goto fail_proxy_rejected;
  37929. }
  37930. /* Target object must be checked for a conflicting
  37931. * non-configurable property.
  37932. */
  37933. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37934. DUK_ASSERT(key != NULL);
  37935. if (duk__get_own_property_desc_raw(thr, h_target, key, arr_idx, &desc, DUK__DESC_FLAG_PUSH_VALUE)) {
  37936. duk_tval *tv_targ = duk_require_tval(ctx, -1);
  37937. duk_bool_t datadesc_reject;
  37938. duk_bool_t accdesc_reject;
  37939. DUK_DDD(DUK_DDDPRINT("proxy 'set': target has matching property %!O, check for "
  37940. "conflicting property; tv_val=%!T, tv_targ=%!T, desc.flags=0x%08lx, "
  37941. "desc.get=%p, desc.set=%p",
  37942. (duk_heaphdr *) key, (duk_tval *) tv_val, (duk_tval *) tv_targ,
  37943. (unsigned long) desc.flags,
  37944. (void *) desc.get, (void *) desc.set));
  37945. datadesc_reject = !(desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) &&
  37946. !(desc.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) &&
  37947. !(desc.flags & DUK_PROPDESC_FLAG_WRITABLE) &&
  37948. !duk_js_samevalue(tv_val, tv_targ);
  37949. accdesc_reject = (desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) &&
  37950. !(desc.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) &&
  37951. (desc.set == NULL);
  37952. if (datadesc_reject || accdesc_reject) {
  37953. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REJECTED);
  37954. }
  37955. duk_pop_2(ctx);
  37956. } else {
  37957. duk_pop(ctx);
  37958. }
  37959. return 1; /* success */
  37960. }
  37961. orig = h_target; /* resume write to target */
  37962. DUK_TVAL_SET_OBJECT(tv_obj, orig);
  37963. }
  37964. #endif /* DUK_USE_ES6_PROXY */
  37965. curr = orig;
  37966. break;
  37967. }
  37968. case DUK_TAG_BUFFER: {
  37969. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv_obj);
  37970. duk_int_t pop_count = 0;
  37971. /*
  37972. * Because buffer values may be looped over and read/written
  37973. * from, an array index fast path is important.
  37974. */
  37975. #if defined(DUK_USE_FASTINT)
  37976. if (DUK_TVAL_IS_FASTINT(tv_key)) {
  37977. arr_idx = duk__tval_fastint_to_arr_idx(tv_key);
  37978. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a fast-path fastint; arr_idx %ld", (long) arr_idx));
  37979. pop_count = 0;
  37980. } else
  37981. #endif
  37982. if (DUK_TVAL_IS_NUMBER(tv_key)) {
  37983. arr_idx = duk__tval_number_to_arr_idx(tv_key);
  37984. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a fast-path number; arr_idx %ld", (long) arr_idx));
  37985. pop_count = 0;
  37986. } else {
  37987. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  37988. DUK_ASSERT(key != NULL);
  37989. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a non-fast-path number; after "
  37990. "coercion key is %!T, arr_idx %ld",
  37991. (duk_tval *) duk_get_tval(ctx, -1), (long) arr_idx));
  37992. pop_count = 1;
  37993. }
  37994. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  37995. arr_idx < DUK_HBUFFER_GET_SIZE(h)) {
  37996. duk_uint8_t *data;
  37997. DUK_DDD(DUK_DDDPRINT("writing to buffer data at index %ld", (long) arr_idx));
  37998. data = (duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h);
  37999. /* XXX: duk_to_int() ensures we'll get 8 lowest bits as
  38000. * as input is within duk_int_t range (capped outside it).
  38001. */
  38002. #if defined(DUK_USE_FASTINT)
  38003. /* Buffer writes are often integers. */
  38004. if (DUK_TVAL_IS_FASTINT(tv_val)) {
  38005. data[arr_idx] = (duk_uint8_t) DUK_TVAL_GET_FASTINT_U32(tv_val);
  38006. }
  38007. else
  38008. #endif
  38009. {
  38010. duk_push_tval(ctx, tv_val);
  38011. data[arr_idx] = (duk_uint8_t) duk_to_int(ctx, -1);
  38012. pop_count++;
  38013. }
  38014. duk_pop_n(ctx, pop_count);
  38015. DUK_DDD(DUK_DDDPRINT("result: success (buffer data write)"));
  38016. return 1;
  38017. }
  38018. if (pop_count == 0) {
  38019. /* This is a pretty awkward control flow, but we need to recheck the
  38020. * key coercion here.
  38021. */
  38022. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  38023. DUK_ASSERT(key != NULL);
  38024. DUK_DDD(DUK_DDDPRINT("base object buffer, key is a non-fast-path number; after "
  38025. "coercion key is %!T, arr_idx %ld",
  38026. (duk_tval *) duk_get_tval(ctx, -1), (long) arr_idx));
  38027. }
  38028. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  38029. goto fail_not_writable;
  38030. }
  38031. DUK_DDD(DUK_DDDPRINT("base object is a buffer, start lookup from buffer prototype"));
  38032. curr = thr->builtins[DUK_BIDX_BUFFER_PROTOTYPE];
  38033. goto lookup; /* avoid double coercion */
  38034. }
  38035. case DUK_TAG_POINTER: {
  38036. DUK_DDD(DUK_DDDPRINT("base object is a pointer, start lookup from pointer prototype"));
  38037. curr = thr->builtins[DUK_BIDX_POINTER_PROTOTYPE];
  38038. break;
  38039. }
  38040. case DUK_TAG_LIGHTFUNC: {
  38041. /* All lightfunc own properties are non-writable and the lightfunc
  38042. * is considered non-extensible. However, the write may be captured
  38043. * by an inherited setter which means we can't stop the lookup here.
  38044. */
  38045. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  38046. if (duk__key_is_lightfunc_ownprop(thr, key)) {
  38047. goto fail_not_writable;
  38048. }
  38049. DUK_DDD(DUK_DDDPRINT("base object is a lightfunc, start lookup from function prototype"));
  38050. curr = thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE];
  38051. goto lookup; /* avoid double coercion */
  38052. }
  38053. #if defined(DUK_USE_FASTINT)
  38054. case DUK_TAG_FASTINT:
  38055. #endif
  38056. default: {
  38057. /* number */
  38058. DUK_DDD(DUK_DDDPRINT("base object is a number, start lookup from number prototype"));
  38059. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_obj));
  38060. curr = thr->builtins[DUK_BIDX_NUMBER_PROTOTYPE];
  38061. break;
  38062. }
  38063. }
  38064. DUK_ASSERT(key == NULL);
  38065. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  38066. DUK_ASSERT(key != NULL);
  38067. lookup:
  38068. /*
  38069. * Check whether the property already exists in the prototype chain.
  38070. * Note that the actual write goes into the original base object
  38071. * (except if an accessor property captures the write).
  38072. */
  38073. /* [key] */
  38074. DUK_ASSERT(curr != NULL);
  38075. sanity = DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY;
  38076. do {
  38077. if (!duk__get_own_property_desc_raw(thr, curr, key, arr_idx, &desc, 0 /*flags*/)) { /* don't push value */
  38078. goto next_in_chain;
  38079. }
  38080. if (desc.flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  38081. /*
  38082. * Found existing accessor property (own or inherited).
  38083. * Call setter with 'this' set to orig, and value as the only argument.
  38084. *
  38085. * Note: no exotic arguments object behavior, because [[Put]] never
  38086. * calls [[DefineOwnProperty]] (E5 Section 8.12.5, step 5.b).
  38087. */
  38088. duk_hobject *setter;
  38089. DUK_DD(DUK_DDPRINT("put to an own or inherited accessor, calling setter"));
  38090. setter = DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, curr, desc.e_idx);
  38091. if (!setter) {
  38092. goto fail_no_setter;
  38093. }
  38094. duk_push_hobject(ctx, setter);
  38095. duk_push_tval(ctx, tv_obj); /* note: original, uncoerced base */
  38096. duk_push_tval(ctx, tv_val); /* [key setter this val] */
  38097. #ifdef DUK_USE_NONSTD_SETTER_KEY_ARGUMENT
  38098. duk_dup(ctx, -4);
  38099. duk_call_method(ctx, 2); /* [key setter this val key] -> [key retval] */
  38100. #else
  38101. duk_call_method(ctx, 1); /* [key setter this val] -> [key retval] */
  38102. #endif
  38103. duk_pop(ctx); /* ignore retval -> [key] */
  38104. goto success_no_arguments_exotic;
  38105. }
  38106. if (orig == NULL) {
  38107. /*
  38108. * Found existing own or inherited plain property, but original
  38109. * base is a primitive value.
  38110. */
  38111. DUK_DD(DUK_DDPRINT("attempt to create a new property in a primitive base object"));
  38112. goto fail_base_primitive;
  38113. }
  38114. if (curr != orig) {
  38115. /*
  38116. * Found existing inherited plain property.
  38117. * Do an access control check, and if OK, write
  38118. * new property to 'orig'.
  38119. */
  38120. if (!DUK_HOBJECT_HAS_EXTENSIBLE(orig)) {
  38121. DUK_DD(DUK_DDPRINT("found existing inherited plain property, but original object is not extensible"));
  38122. goto fail_not_extensible;
  38123. }
  38124. if (!(desc.flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  38125. DUK_DD(DUK_DDPRINT("found existing inherited plain property, original object is extensible, but inherited property is not writable"));
  38126. goto fail_not_writable;
  38127. }
  38128. DUK_DD(DUK_DDPRINT("put to new property, object extensible, inherited property found and is writable"));
  38129. goto create_new;
  38130. } else {
  38131. /*
  38132. * Found existing own (non-inherited) plain property.
  38133. * Do an access control check and update in place.
  38134. */
  38135. if (!(desc.flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  38136. DUK_DD(DUK_DDPRINT("found existing own (non-inherited) plain property, but property is not writable"));
  38137. goto fail_not_writable;
  38138. }
  38139. if (desc.flags & DUK_PROPDESC_FLAG_VIRTUAL) {
  38140. DUK_DD(DUK_DDPRINT("found existing own (non-inherited) virtual property, property is writable"));
  38141. if (DUK_HOBJECT_HAS_EXOTIC_BUFFEROBJ(curr)) {
  38142. duk_hbuffer *h;
  38143. DUK_DD(DUK_DDPRINT("writable virtual property is in buffer object"));
  38144. h = duk_hobject_get_internal_value_buffer(thr->heap, curr);
  38145. DUK_ASSERT(h != NULL);
  38146. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  38147. arr_idx < DUK_HBUFFER_GET_SIZE(h)) {
  38148. duk_uint8_t *data;
  38149. DUK_DDD(DUK_DDDPRINT("writing to buffer data at index %ld", (long) arr_idx));
  38150. data = (duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h);
  38151. duk_push_tval(ctx, tv_val);
  38152. /* XXX: duk_to_int() ensures we'll get 8 lowest bits as
  38153. * as input is within duk_int_t range (capped outside it).
  38154. */
  38155. data[arr_idx] = (duk_uint8_t) duk_to_int(ctx, -1);
  38156. duk_pop(ctx);
  38157. goto success_no_arguments_exotic;
  38158. }
  38159. }
  38160. goto fail_internal; /* should not happen */
  38161. }
  38162. DUK_DD(DUK_DDPRINT("put to existing own plain property, property is writable"));
  38163. goto update_old;
  38164. }
  38165. DUK_UNREACHABLE();
  38166. next_in_chain:
  38167. /* XXX: option to pretend property doesn't exist if sanity limit is
  38168. * hit might be useful.
  38169. */
  38170. if (sanity-- == 0) {
  38171. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_PROTOTYPE_CHAIN_LIMIT);
  38172. }
  38173. curr = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, curr);
  38174. } while (curr);
  38175. /*
  38176. * Property not found in prototype chain.
  38177. */
  38178. DUK_DDD(DUK_DDDPRINT("property not found in prototype chain"));
  38179. if (orig == NULL) {
  38180. DUK_DD(DUK_DDPRINT("attempt to create a new property in a primitive base object"));
  38181. goto fail_base_primitive;
  38182. }
  38183. if (!DUK_HOBJECT_HAS_EXTENSIBLE(orig)) {
  38184. DUK_DD(DUK_DDPRINT("put to a new property (not found in prototype chain), but original object not extensible"));
  38185. goto fail_not_extensible;
  38186. }
  38187. goto create_new;
  38188. update_old:
  38189. /*
  38190. * Update an existing property of the base object.
  38191. */
  38192. /* [key] */
  38193. DUK_DDD(DUK_DDDPRINT("update an existing property of the original object"));
  38194. DUK_ASSERT(orig != NULL);
  38195. /* Although there are writable virtual properties (e.g. plain buffer
  38196. * and buffer object number indices), they are handled before we come
  38197. * here.
  38198. */
  38199. DUK_ASSERT((desc.flags & DUK_PROPDESC_FLAG_VIRTUAL) == 0);
  38200. DUK_ASSERT(desc.a_idx >= 0 || desc.e_idx >= 0);
  38201. if (DUK_HOBJECT_HAS_EXOTIC_ARRAY(orig) &&
  38202. key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  38203. /*
  38204. * Write to 'length' of an array is a very complex case
  38205. * handled in a helper which updates both the array elements
  38206. * and writes the new 'length'. The write may result in an
  38207. * unconditional RangeError or a partial write (indicated
  38208. * by a return code).
  38209. *
  38210. * Note: the helper has an unnecessary writability check
  38211. * for 'length', we already know it is writable.
  38212. */
  38213. DUK_DDD(DUK_DDDPRINT("writing existing 'length' property to array exotic, invoke complex helper"));
  38214. /* XXX: the helper currently assumes stack top contains new
  38215. * 'length' value and the whole calling convention is not very
  38216. * compatible with what we need.
  38217. */
  38218. duk_push_tval(ctx, tv_val); /* [key val] */
  38219. rc = duk__handle_put_array_length(thr, orig);
  38220. duk_pop(ctx); /* [key val] -> [key] */
  38221. if (!rc) {
  38222. goto fail_array_length_partial;
  38223. }
  38224. /* key is 'length', cannot match argument exotic behavior */
  38225. goto success_no_arguments_exotic;
  38226. }
  38227. if (desc.e_idx >= 0) {
  38228. duk_tval tv_tmp;
  38229. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, orig, desc.e_idx);
  38230. DUK_DDD(DUK_DDDPRINT("previous entry value: %!iT", (duk_tval *) tv));
  38231. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  38232. DUK_TVAL_SET_TVAL(tv, tv_val);
  38233. DUK_TVAL_INCREF(thr, tv);
  38234. DUK_TVAL_DECREF(thr, &tv_tmp); /* note: may trigger gc and props compaction, must be last */
  38235. /* don't touch property attributes or hash part */
  38236. DUK_DD(DUK_DDPRINT("put to an existing entry at index %ld -> new value %!iT",
  38237. (long) desc.e_idx, (duk_tval *) tv));
  38238. } else {
  38239. /* Note: array entries are always writable, so the writability check
  38240. * above is pointless for them. The check could be avoided with some
  38241. * refactoring but is probably not worth it.
  38242. */
  38243. duk_tval tv_tmp;
  38244. DUK_ASSERT(desc.a_idx >= 0);
  38245. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, orig, desc.a_idx);
  38246. DUK_DDD(DUK_DDDPRINT("previous array value: %!iT", (duk_tval *) tv));
  38247. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  38248. DUK_TVAL_SET_TVAL(tv, tv_val);
  38249. DUK_TVAL_INCREF(thr, tv);
  38250. DUK_TVAL_DECREF(thr, &tv_tmp); /* note: may trigger gc and props compaction, must be last */
  38251. DUK_DD(DUK_DDPRINT("put to an existing array entry at index %ld -> new value %!iT",
  38252. (long) desc.a_idx, (duk_tval *) tv));
  38253. }
  38254. /* Regardless of whether property is found in entry or array part,
  38255. * it may have arguments exotic behavior (array indices may reside
  38256. * in entry part for abandoned / non-existent array parts).
  38257. */
  38258. goto success_with_arguments_exotic;
  38259. create_new:
  38260. /*
  38261. * Create a new property in the original object.
  38262. *
  38263. * Exotic properties need to be reconsidered here from a write
  38264. * perspective (not just property attributes perspective).
  38265. * However, the property does not exist in the object already,
  38266. * so this limits the kind of exotic properties that apply.
  38267. */
  38268. /* [key] */
  38269. DUK_DDD(DUK_DDDPRINT("create new property to original object"));
  38270. DUK_ASSERT(orig != NULL);
  38271. /* Not possible because array object 'length' is present
  38272. * from its creation and cannot be deleted, and is thus
  38273. * caught as an existing property above.
  38274. */
  38275. DUK_ASSERT(!(DUK_HOBJECT_HAS_EXOTIC_ARRAY(orig) &&
  38276. key == DUK_HTHREAD_STRING_LENGTH(thr)));
  38277. if (DUK_HOBJECT_HAS_EXOTIC_ARRAY(orig) &&
  38278. arr_idx != DUK__NO_ARRAY_INDEX) {
  38279. /* automatic length update */
  38280. duk_uint32_t old_len;
  38281. old_len = duk__get_old_array_length(thr, orig, &desc);
  38282. if (arr_idx >= old_len) {
  38283. DUK_DDD(DUK_DDDPRINT("write new array entry requires length update "
  38284. "(arr_idx=%ld, old_len=%ld)",
  38285. (long) arr_idx, (long) old_len));
  38286. if (!(desc.flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  38287. DUK_DD(DUK_DDPRINT("attempt to extend array, but array 'length' is not writable"));
  38288. goto fail_not_writable;
  38289. }
  38290. /* Note: actual update happens once write has been completed
  38291. * without error below. The write should always succeed
  38292. * from a specification viewpoint, but we may e.g. run out
  38293. * of memory. It's safer in this order.
  38294. */
  38295. DUK_ASSERT(arr_idx != 0xffffffffUL);
  38296. new_array_length = arr_idx + 1; /* flag for later write */
  38297. } else {
  38298. DUK_DDD(DUK_DDDPRINT("write new array entry does not require length update "
  38299. "(arr_idx=%ld, old_len=%ld)",
  38300. (long) arr_idx, (long) old_len));
  38301. }
  38302. }
  38303. /* write_to_array_part: */
  38304. /*
  38305. * Write to array part?
  38306. *
  38307. * Note: array abandonding requires a property resize which uses
  38308. * 'rechecks' valstack for temporaries and may cause any existing
  38309. * valstack pointers to be invalidated. To protect against this,
  38310. * tv_obj, tv_key, and tv_val are copies of the original inputs.
  38311. */
  38312. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  38313. DUK_HOBJECT_HAS_ARRAY_PART(orig)) {
  38314. if (arr_idx < DUK_HOBJECT_GET_ASIZE(orig)) {
  38315. goto no_array_growth;
  38316. }
  38317. /*
  38318. * Array needs to grow, but we don't want it becoming too sparse.
  38319. * If it were to become sparse, abandon array part, moving all
  38320. * array entries into the entries part (for good).
  38321. *
  38322. * Since we don't keep track of actual density (used vs. size) of
  38323. * the array part, we need to estimate somehow. The check is made
  38324. * in two parts:
  38325. *
  38326. * - Check whether the resize need is small compared to the
  38327. * current size (relatively); if so, resize without further
  38328. * checking (essentially we assume that the original part is
  38329. * "dense" so that the result would be dense enough).
  38330. *
  38331. * - Otherwise, compute the resize using an actual density
  38332. * measurement based on counting the used array entries.
  38333. */
  38334. DUK_DDD(DUK_DDDPRINT("write to new array requires array resize, decide whether to do a "
  38335. "fast resize without abandon check (arr_idx=%ld, old_size=%ld)",
  38336. (long) arr_idx, (long) DUK_HOBJECT_GET_ASIZE(orig)));
  38337. if (duk__abandon_array_slow_check_required(arr_idx, DUK_HOBJECT_GET_ASIZE(orig))) {
  38338. duk_uint32_t old_used;
  38339. duk_uint32_t old_size;
  38340. DUK_DDD(DUK_DDDPRINT("=> fast check is NOT OK, do slow check for array abandon"));
  38341. duk__compute_a_stats(thr, orig, &old_used, &old_size);
  38342. DUK_DDD(DUK_DDDPRINT("abandon check, array stats: old_used=%ld, old_size=%ld, arr_idx=%ld",
  38343. (long) old_used, (long) old_size, (long) arr_idx));
  38344. /* Note: intentionally use approximations to shave a few instructions:
  38345. * a_used = old_used (accurate: old_used + 1)
  38346. * a_size = arr_idx (accurate: arr_idx + 1)
  38347. */
  38348. if (duk__abandon_array_density_check(old_used, arr_idx)) {
  38349. DUK_DD(DUK_DDPRINT("write to new array entry beyond current length, "
  38350. "decided to abandon array part (would become too sparse)"));
  38351. /* abandoning requires a props allocation resize and
  38352. * 'rechecks' the valstack, invalidating any existing
  38353. * valstack value pointers!
  38354. */
  38355. duk__abandon_array_checked(thr, orig);
  38356. DUK_ASSERT(!DUK_HOBJECT_HAS_ARRAY_PART(orig));
  38357. goto write_to_entry_part;
  38358. }
  38359. DUK_DDD(DUK_DDDPRINT("=> decided to keep array part"));
  38360. } else {
  38361. DUK_DDD(DUK_DDDPRINT("=> fast resize is OK"));
  38362. }
  38363. DUK_DD(DUK_DDPRINT("write to new array entry beyond current length, "
  38364. "decided to extend current allocation"));
  38365. duk__grow_props_for_array_item(thr, orig, arr_idx);
  38366. no_array_growth:
  38367. /* Note: assume array part is comprehensive, so that either
  38368. * the write goes to the array part, or we've abandoned the
  38369. * array above (and will not come here).
  38370. */
  38371. DUK_ASSERT(DUK_HOBJECT_HAS_ARRAY_PART(orig));
  38372. DUK_ASSERT(arr_idx < DUK_HOBJECT_GET_ASIZE(orig));
  38373. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, orig, arr_idx);
  38374. /* prev value must be unused, no decref */
  38375. DUK_ASSERT(DUK_TVAL_IS_UNDEFINED_UNUSED(tv));
  38376. DUK_TVAL_SET_TVAL(tv, tv_val);
  38377. DUK_TVAL_INCREF(thr, tv);
  38378. DUK_DD(DUK_DDPRINT("put to new array entry: %ld -> %!T",
  38379. (long) arr_idx, (duk_tval *) tv));
  38380. /* Note: array part values are [[Writable]], [[Enumerable]],
  38381. * and [[Configurable]] which matches the required attributes
  38382. * here.
  38383. */
  38384. goto entry_updated;
  38385. }
  38386. write_to_entry_part:
  38387. /*
  38388. * Write to entry part
  38389. */
  38390. /* entry allocation updates hash part and increases the key
  38391. * refcount; may need a props allocation resize but doesn't
  38392. * 'recheck' the valstack.
  38393. */
  38394. e_idx = duk__alloc_entry_checked(thr, orig, key);
  38395. DUK_ASSERT(e_idx >= 0);
  38396. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, orig, e_idx);
  38397. /* prev value can be garbage, no decref */
  38398. DUK_TVAL_SET_TVAL(tv, tv_val);
  38399. DUK_TVAL_INCREF(thr, tv);
  38400. DUK_HOBJECT_E_SET_FLAGS(thr->heap, orig, e_idx, DUK_PROPDESC_FLAGS_WEC);
  38401. goto entry_updated;
  38402. entry_updated:
  38403. /*
  38404. * Possible pending array length update, which must only be done
  38405. * if the actual entry write succeeded.
  38406. */
  38407. if (new_array_length > 0) {
  38408. /*
  38409. * Note: zero works as a "no update" marker because the new length
  38410. * can never be zero after a new property is written.
  38411. *
  38412. * Note: must re-lookup because calls above (e.g. duk__alloc_entry_checked())
  38413. * may realloc and compact properties and hence change e_idx.
  38414. */
  38415. DUK_DDD(DUK_DDDPRINT("write successful, pending array length update to: %ld",
  38416. (long) new_array_length));
  38417. rc = duk__get_own_property_desc_raw(thr, orig, DUK_HTHREAD_STRING_LENGTH(thr), DUK__NO_ARRAY_INDEX, &desc, 0 /*flags*/); /* don't push value */
  38418. DUK_UNREF(rc);
  38419. DUK_ASSERT(rc != 0);
  38420. DUK_ASSERT(desc.e_idx >= 0);
  38421. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, orig, desc.e_idx);
  38422. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  38423. /* no need for decref/incref because value is a number */
  38424. #if defined(DUK_USE_FASTINT)
  38425. DUK_TVAL_SET_FASTINT_U32(tv, new_array_length);
  38426. #else
  38427. DUK_TVAL_SET_NUMBER(tv, (duk_double_t) new_array_length);
  38428. #endif
  38429. }
  38430. /*
  38431. * Arguments exotic behavior not possible for new properties: all
  38432. * magically bound properties are initially present in the arguments
  38433. * object, and if they are deleted, the binding is also removed from
  38434. * parameter map.
  38435. */
  38436. goto success_no_arguments_exotic;
  38437. success_with_arguments_exotic:
  38438. /*
  38439. * Arguments objects have exotic [[DefineOwnProperty]] which updates
  38440. * the internal 'map' of arguments for writes to currently mapped
  38441. * arguments. More conretely, writes to mapped arguments generate
  38442. * a write to a bound variable.
  38443. *
  38444. * The [[Put]] algorithm invokes [[DefineOwnProperty]] for existing
  38445. * data properties and new properties, but not for existing accessors.
  38446. * Hence, in E5 Section 10.6 ([[DefinedOwnProperty]] algorithm), we
  38447. * have a Desc with 'Value' (and possibly other properties too), and
  38448. * we end up in step 5.b.i.
  38449. */
  38450. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  38451. DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(orig)) {
  38452. /* Note: only numbered indices are relevant, so arr_idx fast reject
  38453. * is good (this is valid unless there are more than 4**32-1 arguments).
  38454. */
  38455. DUK_DDD(DUK_DDDPRINT("putprop successful, arguments exotic behavior needed"));
  38456. /* Note: we can reuse 'desc' here */
  38457. /* XXX: top of stack must contain value, which helper doesn't touch,
  38458. * rework to use tv_val directly?
  38459. */
  38460. duk_push_tval(ctx, tv_val);
  38461. (void) duk__check_arguments_map_for_put(thr, orig, key, &desc, throw_flag);
  38462. duk_pop(ctx);
  38463. }
  38464. /* fall thru */
  38465. success_no_arguments_exotic:
  38466. /* shared exit path now */
  38467. DUK_DDD(DUK_DDDPRINT("result: success"));
  38468. duk_pop(ctx); /* remove key */
  38469. return 1;
  38470. fail_proxy_rejected:
  38471. DUK_DDD(DUK_DDDPRINT("result: error, proxy rejects"));
  38472. if (throw_flag) {
  38473. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REJECTED);
  38474. }
  38475. /* Note: no key on stack */
  38476. return 0;
  38477. fail_base_primitive:
  38478. DUK_DDD(DUK_DDDPRINT("result: error, base primitive"));
  38479. if (throw_flag) {
  38480. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INVALID_BASE);
  38481. }
  38482. duk_pop(ctx); /* remove key */
  38483. return 0;
  38484. fail_not_extensible:
  38485. DUK_DDD(DUK_DDDPRINT("result: error, not extensible"));
  38486. if (throw_flag) {
  38487. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_EXTENSIBLE);
  38488. }
  38489. duk_pop(ctx); /* remove key */
  38490. return 0;
  38491. fail_not_writable:
  38492. DUK_DDD(DUK_DDDPRINT("result: error, not writable"));
  38493. if (throw_flag) {
  38494. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_WRITABLE);
  38495. }
  38496. duk_pop(ctx); /* remove key */
  38497. return 0;
  38498. fail_array_length_partial:
  38499. DUK_DDD(DUK_DDDPRINT("result: error, array length write only partially successful"));
  38500. if (throw_flag) {
  38501. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_ARRAY_LENGTH_WRITE_FAILED);
  38502. }
  38503. duk_pop(ctx); /* remove key */
  38504. return 0;
  38505. fail_no_setter:
  38506. DUK_DDD(DUK_DDDPRINT("result: error, accessor property without setter"));
  38507. if (throw_flag) {
  38508. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_SETTER_UNDEFINED);
  38509. }
  38510. duk_pop(ctx); /* remove key */
  38511. return 0;
  38512. fail_internal:
  38513. DUK_DDD(DUK_DDDPRINT("result: error, internal"));
  38514. if (throw_flag) {
  38515. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INTERNAL_ERROR);
  38516. }
  38517. duk_pop(ctx); /* remove key */
  38518. return 0;
  38519. }
  38520. /*
  38521. * Ecmascript compliant [[Delete]](P, Throw).
  38522. */
  38523. DUK_INTERNAL duk_bool_t duk_hobject_delprop_raw(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_small_uint_t flags) {
  38524. duk_propdesc desc;
  38525. duk_tval *tv;
  38526. duk_tval tv_tmp;
  38527. duk_uint32_t arr_idx;
  38528. duk_bool_t throw_flag;
  38529. duk_bool_t force_flag;
  38530. throw_flag = (flags & DUK_DELPROP_FLAG_THROW);
  38531. force_flag = (flags & DUK_DELPROP_FLAG_FORCE);
  38532. DUK_DDD(DUK_DDDPRINT("delprop_raw: thr=%p, obj=%p, key=%p, throw=%ld, force=%ld (obj -> %!O, key -> %!O)",
  38533. (void *) thr, (void *) obj, (void *) key, (long) throw_flag, (long) force_flag,
  38534. (duk_heaphdr *) obj, (duk_heaphdr *) key));
  38535. DUK_ASSERT(thr != NULL);
  38536. DUK_ASSERT(thr->heap != NULL);
  38537. DUK_ASSERT(obj != NULL);
  38538. DUK_ASSERT(key != NULL);
  38539. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  38540. arr_idx = DUK_HSTRING_GET_ARRIDX_FAST(key);
  38541. /* 0 = don't push current value */
  38542. if (!duk__get_own_property_desc_raw(thr, obj, key, arr_idx, &desc, 0 /*flags*/)) { /* don't push value */
  38543. DUK_DDD(DUK_DDDPRINT("property not found, succeed always"));
  38544. goto success;
  38545. }
  38546. if ((desc.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) == 0 && !force_flag) {
  38547. goto fail_not_configurable;
  38548. }
  38549. if (desc.a_idx < 0 && desc.e_idx < 0) {
  38550. /* Currently there are no deletable virtual properties, but
  38551. * with force_flag we might attempt to delete one.
  38552. */
  38553. goto fail_virtual;
  38554. }
  38555. if (desc.a_idx >= 0) {
  38556. DUK_ASSERT(desc.e_idx < 0);
  38557. tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, desc.a_idx);
  38558. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  38559. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  38560. DUK_TVAL_DECREF(thr, &tv_tmp);
  38561. goto success;
  38562. } else {
  38563. DUK_ASSERT(desc.a_idx < 0);
  38564. /* remove hash entry (no decref) */
  38565. #if defined(DUK_USE_HOBJECT_HASH_PART)
  38566. if (desc.h_idx >= 0) {
  38567. duk_uint32_t *h_base = DUK_HOBJECT_H_GET_BASE(thr->heap, obj);
  38568. DUK_DDD(DUK_DDDPRINT("removing hash entry at h_idx %ld", (long) desc.h_idx));
  38569. DUK_ASSERT(DUK_HOBJECT_GET_HSIZE(obj) > 0);
  38570. DUK_ASSERT((duk_uint32_t) desc.h_idx < DUK_HOBJECT_GET_HSIZE(obj));
  38571. h_base[desc.h_idx] = DUK__HASH_DELETED;
  38572. } else {
  38573. DUK_ASSERT(DUK_HOBJECT_GET_HSIZE(obj) == 0);
  38574. }
  38575. #else
  38576. DUK_ASSERT(DUK_HOBJECT_GET_HSIZE(obj) == 0);
  38577. #endif
  38578. /* remove value */
  38579. DUK_DDD(DUK_DDDPRINT("before removing value, e_idx %ld, key %p, key at slot %p",
  38580. (long) desc.e_idx, (void *) key, (void *) DUK_HOBJECT_E_GET_KEY(thr->heap, obj, desc.e_idx)));
  38581. DUK_DDD(DUK_DDDPRINT("removing value at e_idx %ld", (long) desc.e_idx));
  38582. if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, desc.e_idx)) {
  38583. duk_hobject *tmp;
  38584. tmp = DUK_HOBJECT_E_GET_VALUE_GETTER(thr->heap, obj, desc.e_idx);
  38585. DUK_HOBJECT_E_SET_VALUE_GETTER(thr->heap, obj, desc.e_idx, NULL);
  38586. DUK_UNREF(tmp);
  38587. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  38588. tmp = DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, obj, desc.e_idx);
  38589. DUK_HOBJECT_E_SET_VALUE_SETTER(thr->heap, obj, desc.e_idx, NULL);
  38590. DUK_UNREF(tmp);
  38591. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  38592. } else {
  38593. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, desc.e_idx);
  38594. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  38595. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  38596. DUK_TVAL_DECREF(thr, &tv_tmp);
  38597. }
  38598. /* this is not strictly necessary because if key == NULL, value MUST be ignored */
  38599. DUK_HOBJECT_E_SET_FLAGS(thr->heap, obj, desc.e_idx, 0);
  38600. DUK_TVAL_SET_UNDEFINED_UNUSED(DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, desc.e_idx));
  38601. /* remove key */
  38602. DUK_DDD(DUK_DDDPRINT("before removing key, e_idx %ld, key %p, key at slot %p",
  38603. (long) desc.e_idx, (void *) key, (void *) DUK_HOBJECT_E_GET_KEY(thr->heap, obj, desc.e_idx)));
  38604. DUK_DDD(DUK_DDDPRINT("removing key at e_idx %ld", (long) desc.e_idx));
  38605. DUK_ASSERT(key == DUK_HOBJECT_E_GET_KEY(thr->heap, obj, desc.e_idx));
  38606. DUK_HOBJECT_E_SET_KEY(thr->heap, obj, desc.e_idx, NULL);
  38607. DUK_HSTRING_DECREF(thr, key);
  38608. goto success;
  38609. }
  38610. DUK_UNREACHABLE();
  38611. success:
  38612. /*
  38613. * Argument exotic [[Delete]] behavior (E5 Section 10.6) is
  38614. * a post-check, keeping arguments internal 'map' in sync with
  38615. * any successful deletes (note that property does not need to
  38616. * exist for delete to 'succeed').
  38617. *
  38618. * Delete key from 'map'. Since 'map' only contains array index
  38619. * keys, we can use arr_idx for a fast skip.
  38620. */
  38621. DUK_DDD(DUK_DDDPRINT("delete successful, check for arguments exotic behavior"));
  38622. if (arr_idx != DUK__NO_ARRAY_INDEX && DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj)) {
  38623. /* Note: only numbered indices are relevant, so arr_idx fast reject
  38624. * is good (this is valid unless there are more than 4**32-1 arguments).
  38625. */
  38626. DUK_DDD(DUK_DDDPRINT("delete successful, arguments exotic behavior needed"));
  38627. /* Note: we can reuse 'desc' here */
  38628. (void) duk__check_arguments_map_for_delete(thr, obj, key, &desc);
  38629. }
  38630. DUK_DDD(DUK_DDDPRINT("delete successful"));
  38631. return 1;
  38632. fail_virtual:
  38633. DUK_DDD(DUK_DDDPRINT("delete failed: property found, force flag, but virtual"));
  38634. if (throw_flag) {
  38635. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROPERTY_IS_VIRTUAL);
  38636. }
  38637. return 0;
  38638. fail_not_configurable:
  38639. DUK_DDD(DUK_DDDPRINT("delete failed: property found, not configurable"));
  38640. if (throw_flag) {
  38641. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_CONFIGURABLE);
  38642. }
  38643. return 0;
  38644. }
  38645. /*
  38646. * DELPROP: Ecmascript property deletion.
  38647. */
  38648. DUK_INTERNAL duk_bool_t duk_hobject_delprop(duk_hthread *thr, duk_tval *tv_obj, duk_tval *tv_key, duk_bool_t throw_flag) {
  38649. duk_context *ctx = (duk_context *) thr;
  38650. duk_hstring *key = NULL;
  38651. #if defined(DUK_USE_ES6_PROXY)
  38652. duk_propdesc desc;
  38653. #endif
  38654. duk_int_t entry_top;
  38655. duk_uint32_t arr_idx = DUK__NO_ARRAY_INDEX;
  38656. duk_bool_t rc;
  38657. DUK_DDD(DUK_DDDPRINT("delprop: thr=%p, obj=%p, key=%p (obj -> %!T, key -> %!T)",
  38658. (void *) thr, (void *) tv_obj, (void *) tv_key,
  38659. (duk_tval *) tv_obj, (duk_tval *) tv_key));
  38660. DUK_ASSERT(ctx != NULL);
  38661. DUK_ASSERT(thr != NULL);
  38662. DUK_ASSERT(thr->heap != NULL);
  38663. DUK_ASSERT(tv_obj != NULL);
  38664. DUK_ASSERT(tv_key != NULL);
  38665. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  38666. /* Storing the entry top is cheaper here to ensure stack is correct at exit,
  38667. * as there are several paths out.
  38668. */
  38669. entry_top = duk_get_top(ctx);
  38670. if (DUK_TVAL_IS_UNDEFINED(tv_obj) ||
  38671. DUK_TVAL_IS_NULL(tv_obj)) {
  38672. DUK_DDD(DUK_DDDPRINT("base object is undefined or null -> reject"));
  38673. goto fail_invalid_base_uncond;
  38674. }
  38675. duk_push_tval(ctx, tv_obj);
  38676. duk_push_tval(ctx, tv_key);
  38677. tv_obj = duk_get_tval(ctx, -2);
  38678. if (DUK_TVAL_IS_OBJECT(tv_obj)) {
  38679. duk_hobject *obj = DUK_TVAL_GET_OBJECT(tv_obj);
  38680. DUK_ASSERT(obj != NULL);
  38681. #if defined(DUK_USE_ES6_PROXY)
  38682. if (DUK_UNLIKELY(DUK_HOBJECT_HAS_EXOTIC_PROXYOBJ(obj))) {
  38683. duk_hobject *h_target;
  38684. duk_bool_t tmp_bool;
  38685. /* Note: proxy handling must happen before key is string coerced. */
  38686. if (duk__proxy_check_prop(thr, obj, DUK_STRIDX_DELETE_PROPERTY, tv_key, &h_target)) {
  38687. /* -> [ ... trap handler ] */
  38688. DUK_DDD(DUK_DDDPRINT("-> proxy object 'deleteProperty' for key %!T", (duk_tval *) tv_key));
  38689. duk_push_hobject(ctx, h_target); /* target */
  38690. duk_push_tval(ctx, tv_key); /* P */
  38691. duk_call_method(ctx, 2 /*nargs*/);
  38692. tmp_bool = duk_to_boolean(ctx, -1);
  38693. duk_pop(ctx);
  38694. if (!tmp_bool) {
  38695. goto fail_proxy_rejected; /* retval indicates delete failed */
  38696. }
  38697. /* Target object must be checked for a conflicting
  38698. * non-configurable property.
  38699. */
  38700. arr_idx = duk__push_tval_to_hstring_arr_idx(ctx, tv_key, &key);
  38701. DUK_ASSERT(key != NULL);
  38702. if (duk__get_own_property_desc_raw(thr, h_target, key, arr_idx, &desc, 0 /*flags*/)) { /* don't push value */
  38703. int desc_reject;
  38704. DUK_DDD(DUK_DDDPRINT("proxy 'deleteProperty': target has matching property %!O, check for "
  38705. "conflicting property; desc.flags=0x%08lx, "
  38706. "desc.get=%p, desc.set=%p",
  38707. (duk_heaphdr *) key, (unsigned long) desc.flags,
  38708. (void *) desc.get, (void *) desc.set));
  38709. desc_reject = !(desc.flags & DUK_PROPDESC_FLAG_CONFIGURABLE);
  38710. if (desc_reject) {
  38711. /* unconditional */
  38712. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REJECTED);
  38713. }
  38714. }
  38715. rc = 1; /* success */
  38716. goto done_rc;
  38717. }
  38718. obj = h_target; /* resume delete to target */
  38719. }
  38720. #endif /* DUK_USE_ES6_PROXY */
  38721. duk_to_string(ctx, -1);
  38722. key = duk_get_hstring(ctx, -1);
  38723. DUK_ASSERT(key != NULL);
  38724. rc = duk_hobject_delprop_raw(thr, obj, key, throw_flag ? DUK_DELPROP_FLAG_THROW : 0);
  38725. goto done_rc;
  38726. } else if (DUK_TVAL_IS_STRING(tv_obj)) {
  38727. /* XXX: unnecessary string coercion for array indices,
  38728. * intentional to keep small.
  38729. */
  38730. duk_hstring *h = DUK_TVAL_GET_STRING(tv_obj);
  38731. DUK_ASSERT(h != NULL);
  38732. duk_to_string(ctx, -1);
  38733. key = duk_get_hstring(ctx, -1);
  38734. DUK_ASSERT(key != NULL);
  38735. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  38736. goto fail_not_configurable;
  38737. }
  38738. arr_idx = DUK_HSTRING_GET_ARRIDX_FAST(key);
  38739. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  38740. arr_idx < DUK_HSTRING_GET_CHARLEN(h)) {
  38741. goto fail_not_configurable;
  38742. }
  38743. } else if (DUK_TVAL_IS_BUFFER(tv_obj)) {
  38744. /* XXX: unnecessary string coercion for array indices,
  38745. * intentional to keep small; some overlap with string
  38746. * handling.
  38747. */
  38748. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv_obj);
  38749. DUK_ASSERT(h != NULL);
  38750. duk_to_string(ctx, -1);
  38751. key = duk_get_hstring(ctx, -1);
  38752. DUK_ASSERT(key != NULL);
  38753. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  38754. goto fail_not_configurable;
  38755. }
  38756. arr_idx = DUK_HSTRING_GET_ARRIDX_FAST(key);
  38757. if (arr_idx != DUK__NO_ARRAY_INDEX &&
  38758. arr_idx < DUK_HBUFFER_GET_SIZE(h)) {
  38759. goto fail_not_configurable;
  38760. }
  38761. } else if (DUK_TVAL_IS_LIGHTFUNC(tv_obj)) {
  38762. /* Lightfunc virtual properties are non-configurable, so
  38763. * reject if match any of them.
  38764. */
  38765. duk_to_string(ctx, -1);
  38766. key = duk_get_hstring(ctx, -1);
  38767. DUK_ASSERT(key != NULL);
  38768. if (duk__key_is_lightfunc_ownprop(thr, key)) {
  38769. goto fail_not_configurable;
  38770. }
  38771. }
  38772. /* non-object base, no offending virtual property */
  38773. rc = 1;
  38774. goto done_rc;
  38775. done_rc:
  38776. duk_set_top(ctx, entry_top);
  38777. return rc;
  38778. fail_invalid_base_uncond:
  38779. /* Note: unconditional throw */
  38780. DUK_ASSERT(duk_get_top(ctx) == entry_top);
  38781. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INVALID_BASE);
  38782. return 0;
  38783. fail_proxy_rejected:
  38784. if (throw_flag) {
  38785. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROXY_REJECTED);
  38786. }
  38787. duk_set_top(ctx, entry_top);
  38788. return 0;
  38789. fail_not_configurable:
  38790. if (throw_flag) {
  38791. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_CONFIGURABLE);
  38792. }
  38793. duk_set_top(ctx, entry_top);
  38794. return 0;
  38795. }
  38796. /*
  38797. * Internal helper to define a property with specific flags, ignoring
  38798. * normal semantics such as extensibility, write protection etc.
  38799. * Overwrites any existing value and attributes unless caller requests
  38800. * that value only be updated if it doesn't already exists.
  38801. *
  38802. * Does not support:
  38803. * - virtual properties (error if write attempted)
  38804. * - getter/setter properties (error if write attempted)
  38805. * - non-default (!= WEC) attributes for array entries (error if attempted)
  38806. * - array abandoning: if array part exists, it is always extended
  38807. * - array 'length' updating
  38808. *
  38809. * Stack: [... in_val] -> []
  38810. *
  38811. * Used for e.g. built-in initialization and environment record
  38812. * operations.
  38813. */
  38814. DUK_INTERNAL void duk_hobject_define_property_internal(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_small_uint_t flags) {
  38815. duk_context *ctx = (duk_context *) thr;
  38816. duk_propdesc desc;
  38817. duk_uint32_t arr_idx;
  38818. duk_int_t e_idx;
  38819. duk_tval tv_tmp;
  38820. duk_tval *tv1 = NULL;
  38821. duk_tval *tv2 = NULL;
  38822. duk_small_uint_t propflags = flags & DUK_PROPDESC_FLAGS_MASK; /* mask out flags not actually stored */
  38823. DUK_DDD(DUK_DDDPRINT("define new property (internal): thr=%p, obj=%!O, key=%!O, flags=0x%02lx, val=%!T",
  38824. (void *) thr, (duk_heaphdr *) obj, (duk_heaphdr *) key,
  38825. (unsigned long) flags, (duk_tval *) duk_get_tval(ctx, -1)));
  38826. DUK_ASSERT(thr != NULL);
  38827. DUK_ASSERT(thr->heap != NULL);
  38828. DUK_ASSERT(obj != NULL);
  38829. DUK_ASSERT(key != NULL);
  38830. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  38831. DUK_ASSERT(duk_is_valid_index(ctx, -1)); /* contains value */
  38832. arr_idx = DUK_HSTRING_GET_ARRIDX_SLOW(key);
  38833. if (duk__get_own_property_desc_raw(thr, obj, key, arr_idx, &desc, 0 /*flags*/)) { /* don't push value */
  38834. if (desc.e_idx >= 0) {
  38835. if (flags & DUK_PROPDESC_FLAG_NO_OVERWRITE) {
  38836. DUK_DDD(DUK_DDDPRINT("property already exists in the entry part -> skip as requested"));
  38837. goto pop_exit;
  38838. }
  38839. DUK_DDD(DUK_DDDPRINT("property already exists in the entry part -> update value and attributes"));
  38840. if (DUK_UNLIKELY(DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, desc.e_idx))) {
  38841. DUK_D(DUK_DPRINT("existing property is an accessor, not supported"));
  38842. goto error_internal;
  38843. }
  38844. DUK_HOBJECT_E_SET_FLAGS(thr->heap, obj, desc.e_idx, propflags);
  38845. tv1 = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, desc.e_idx);
  38846. } else if (desc.a_idx >= 0) {
  38847. if (flags & DUK_PROPDESC_FLAG_NO_OVERWRITE) {
  38848. DUK_DDD(DUK_DDDPRINT("property already exists in the array part -> skip as requested"));
  38849. goto pop_exit;
  38850. }
  38851. DUK_DDD(DUK_DDDPRINT("property already exists in the array part -> update value (assert attributes)"));
  38852. if (propflags != DUK_PROPDESC_FLAGS_WEC) {
  38853. DUK_D(DUK_DPRINT("existing property in array part, but propflags not WEC (0x%02lx)",
  38854. (unsigned long) propflags));
  38855. goto error_internal;
  38856. }
  38857. tv1 = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, desc.a_idx);
  38858. } else {
  38859. if (flags & DUK_PROPDESC_FLAG_NO_OVERWRITE) {
  38860. DUK_DDD(DUK_DDDPRINT("property already exists but is virtual -> skip as requested"));
  38861. goto pop_exit;
  38862. }
  38863. DUK_DDD(DUK_DDDPRINT("property already exists but is virtual -> failure"));
  38864. goto error_virtual;
  38865. }
  38866. goto write_value;
  38867. }
  38868. if (DUK_HOBJECT_HAS_ARRAY_PART(obj)) {
  38869. if (arr_idx != DUK__NO_ARRAY_INDEX) {
  38870. DUK_DDD(DUK_DDDPRINT("property does not exist, object has array part -> possibly extend array part and write value (assert attributes)"));
  38871. DUK_ASSERT(propflags == DUK_PROPDESC_FLAGS_WEC);
  38872. /* always grow the array, no sparse / abandon support here */
  38873. if (arr_idx >= DUK_HOBJECT_GET_ASIZE(obj)) {
  38874. duk__grow_props_for_array_item(thr, obj, arr_idx);
  38875. }
  38876. DUK_ASSERT(arr_idx < DUK_HOBJECT_GET_ASIZE(obj));
  38877. tv1 = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, arr_idx);
  38878. goto write_value;
  38879. }
  38880. }
  38881. DUK_DDD(DUK_DDDPRINT("property does not exist, object belongs in entry part -> allocate new entry and write value and attributes"));
  38882. e_idx = duk__alloc_entry_checked(thr, obj, key); /* increases key refcount */
  38883. DUK_ASSERT(e_idx >= 0);
  38884. DUK_HOBJECT_E_SET_FLAGS(thr->heap, obj, e_idx, propflags);
  38885. tv1 = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, e_idx);
  38886. /* new entry: previous value is garbage; set to undefined to share write_value */
  38887. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv1);
  38888. goto write_value;
  38889. write_value:
  38890. /* tv1 points to value storage */
  38891. tv2 = duk_require_tval(ctx, -1); /* late lookup, avoid side effects */
  38892. DUK_DDD(DUK_DDDPRINT("writing/updating value: %!T -> %!T",
  38893. (duk_tval *) tv1, (duk_tval *) tv2));
  38894. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  38895. DUK_TVAL_SET_TVAL(tv1, tv2);
  38896. DUK_TVAL_INCREF(thr, tv1);
  38897. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  38898. goto pop_exit;
  38899. pop_exit:
  38900. duk_pop(ctx); /* remove in_val */
  38901. return;
  38902. error_internal:
  38903. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR);
  38904. return;
  38905. error_virtual:
  38906. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_REDEFINE_VIRT_PROP);
  38907. return;
  38908. }
  38909. /*
  38910. * Fast path for defining array indexed values without interning the key.
  38911. * This is used by e.g. code for Array prototype and traceback creation so
  38912. * must avoid interning.
  38913. */
  38914. DUK_INTERNAL void duk_hobject_define_property_internal_arridx(duk_hthread *thr, duk_hobject *obj, duk_uarridx_t arr_idx, duk_small_uint_t flags) {
  38915. duk_context *ctx = (duk_context *) thr;
  38916. duk_hstring *key;
  38917. duk_tval *tv1, *tv2;
  38918. duk_tval tv_tmp;
  38919. DUK_DDD(DUK_DDDPRINT("define new property (internal) arr_idx fast path: thr=%p, obj=%!O, "
  38920. "arr_idx=%ld, flags=0x%02lx, val=%!T",
  38921. (void *) thr, obj, (long) arr_idx, (unsigned long) flags,
  38922. (duk_tval *) duk_get_tval(ctx, -1)));
  38923. DUK_ASSERT(thr != NULL);
  38924. DUK_ASSERT(thr->heap != NULL);
  38925. DUK_ASSERT(obj != NULL);
  38926. if (DUK_HOBJECT_HAS_ARRAY_PART(obj) &&
  38927. arr_idx != DUK__NO_ARRAY_INDEX &&
  38928. flags == DUK_PROPDESC_FLAGS_WEC) {
  38929. DUK_ASSERT((flags & DUK_PROPDESC_FLAG_NO_OVERWRITE) == 0); /* covered by comparison */
  38930. DUK_DDD(DUK_DDDPRINT("define property to array part (property may or may not exist yet)"));
  38931. /* always grow the array, no sparse / abandon support here */
  38932. if (arr_idx >= DUK_HOBJECT_GET_ASIZE(obj)) {
  38933. duk__grow_props_for_array_item(thr, obj, arr_idx);
  38934. }
  38935. DUK_ASSERT(arr_idx < DUK_HOBJECT_GET_ASIZE(obj));
  38936. tv1 = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, arr_idx);
  38937. tv2 = duk_require_tval(ctx, -1);
  38938. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  38939. DUK_TVAL_SET_TVAL(tv1, tv2);
  38940. DUK_TVAL_INCREF(thr, tv1);
  38941. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  38942. duk_pop(ctx); /* [ ...val ] -> [ ... ] */
  38943. return;
  38944. }
  38945. DUK_DDD(DUK_DDDPRINT("define property fast path didn't work, use slow path"));
  38946. duk_push_uint(ctx, (duk_uint_t) arr_idx);
  38947. key = duk_to_hstring(ctx, -1);
  38948. DUK_ASSERT(key != NULL);
  38949. duk_insert(ctx, -2); /* [ ... val key ] -> [ ... key val ] */
  38950. duk_hobject_define_property_internal(thr, obj, key, flags);
  38951. duk_pop(ctx); /* [ ... key ] -> [ ... ] */
  38952. }
  38953. /*
  38954. * Internal helper for defining an accessor property, ignoring
  38955. * normal semantics such as extensibility, write protection etc.
  38956. * Overwrites any existing value and attributes. This is called
  38957. * very rarely, so the implementation first sets a value to undefined
  38958. * and then changes the entry to an accessor (this is to save code space).
  38959. */
  38960. DUK_INTERNAL void duk_hobject_define_accessor_internal(duk_hthread *thr, duk_hobject *obj, duk_hstring *key, duk_hobject *getter, duk_hobject *setter, duk_small_uint_t propflags) {
  38961. duk_context *ctx = (duk_context *) thr;
  38962. duk_int_t e_idx;
  38963. duk_int_t h_idx;
  38964. DUK_DDD(DUK_DDDPRINT("define new accessor (internal): thr=%p, obj=%!O, key=%!O, "
  38965. "getter=%!O, setter=%!O, flags=0x%02lx",
  38966. (void *) thr, (duk_heaphdr *) obj, (duk_heaphdr *) key,
  38967. (duk_heaphdr *) getter, (duk_heaphdr *) setter,
  38968. (unsigned long) propflags));
  38969. DUK_ASSERT(thr != NULL);
  38970. DUK_ASSERT(thr->heap != NULL);
  38971. DUK_ASSERT(obj != NULL);
  38972. DUK_ASSERT(key != NULL);
  38973. DUK_ASSERT((propflags & ~DUK_PROPDESC_FLAGS_MASK) == 0);
  38974. /* setter and/or getter may be NULL */
  38975. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  38976. /* force the property to 'undefined' to create a slot for it */
  38977. duk_push_undefined(ctx);
  38978. duk_hobject_define_property_internal(thr, obj, key, propflags);
  38979. duk_hobject_find_existing_entry(thr->heap, obj, key, &e_idx, &h_idx);
  38980. DUK_DDD(DUK_DDDPRINT("accessor slot: e_idx=%ld, h_idx=%ld", (long) e_idx, (long) h_idx));
  38981. DUK_ASSERT(e_idx >= 0);
  38982. DUK_ASSERT((duk_uint32_t) e_idx < DUK_HOBJECT_GET_ENEXT(obj));
  38983. /* no need to decref, as previous value is 'undefined' */
  38984. DUK_HOBJECT_E_SLOT_SET_ACCESSOR(thr->heap, obj, e_idx);
  38985. DUK_HOBJECT_E_SET_VALUE_GETTER(thr->heap, obj, e_idx, getter);
  38986. DUK_HOBJECT_E_SET_VALUE_SETTER(thr->heap, obj, e_idx, setter);
  38987. DUK_HOBJECT_INCREF_ALLOWNULL(thr, getter);
  38988. DUK_HOBJECT_INCREF_ALLOWNULL(thr, setter);
  38989. }
  38990. /*
  38991. * Internal helpers for managing object 'length'
  38992. */
  38993. /* XXX: awkward helpers */
  38994. DUK_INTERNAL void duk_hobject_set_length(duk_hthread *thr, duk_hobject *obj, duk_uint32_t length) {
  38995. duk_context *ctx = (duk_context *) thr;
  38996. duk_push_hobject(ctx, obj);
  38997. duk_push_hstring_stridx(ctx, DUK_STRIDX_LENGTH);
  38998. duk_push_u32(ctx, length);
  38999. (void) duk_hobject_putprop(thr, duk_get_tval(ctx, -3), duk_get_tval(ctx, -2), duk_get_tval(ctx, -1), 0);
  39000. duk_pop_n(ctx, 3);
  39001. }
  39002. DUK_INTERNAL void duk_hobject_set_length_zero(duk_hthread *thr, duk_hobject *obj) {
  39003. duk_hobject_set_length(thr, obj, 0);
  39004. }
  39005. DUK_INTERNAL duk_uint32_t duk_hobject_get_length(duk_hthread *thr, duk_hobject *obj) {
  39006. duk_context *ctx = (duk_context *) thr;
  39007. duk_double_t val;
  39008. duk_push_hobject(ctx, obj);
  39009. duk_push_hstring_stridx(ctx, DUK_STRIDX_LENGTH);
  39010. (void) duk_hobject_getprop(thr, duk_get_tval(ctx, -2), duk_get_tval(ctx, -1));
  39011. val = duk_to_number(ctx, -1);
  39012. duk_pop_n(ctx, 3);
  39013. if (val >= 0.0 && val < DUK_DOUBLE_2TO32) {
  39014. return (duk_uint32_t) val;
  39015. }
  39016. return 0;
  39017. }
  39018. /*
  39019. * Object.getOwnPropertyDescriptor() (E5 Sections 15.2.3.3, 8.10.4)
  39020. *
  39021. * This is an actual function call.
  39022. */
  39023. DUK_INTERNAL duk_ret_t duk_hobject_object_get_own_property_descriptor(duk_context *ctx) {
  39024. duk_hthread *thr = (duk_hthread *) ctx;
  39025. duk_hobject *obj;
  39026. duk_hstring *key;
  39027. duk_propdesc pd;
  39028. duk_bool_t rc;
  39029. DUK_ASSERT(ctx != NULL);
  39030. DUK_ASSERT(thr != NULL);
  39031. DUK_ASSERT(thr->heap != NULL);
  39032. obj = duk_require_hobject_or_lfunc_coerce(ctx, 0);
  39033. (void) duk_to_string(ctx, 1);
  39034. key = duk_require_hstring(ctx, 1);
  39035. DUK_ASSERT(obj != NULL);
  39036. DUK_ASSERT(key != NULL);
  39037. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  39038. rc = duk__get_own_property_desc(thr, obj, key, &pd, DUK__DESC_FLAG_PUSH_VALUE);
  39039. if (!rc) {
  39040. duk_push_undefined(ctx);
  39041. /* [obj key undefined] */
  39042. return 1;
  39043. }
  39044. duk_push_object(ctx);
  39045. /* [obj key value desc] */
  39046. if (DUK_PROPDESC_IS_ACCESSOR(&pd)) {
  39047. /* If a setter/getter is missing (undefined), the descriptor must
  39048. * still have the property present with the value 'undefined'.
  39049. */
  39050. if (pd.get) {
  39051. duk_push_hobject(ctx, pd.get);
  39052. } else {
  39053. duk_push_undefined(ctx);
  39054. }
  39055. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_GET);
  39056. if (pd.set) {
  39057. duk_push_hobject(ctx, pd.set);
  39058. } else {
  39059. duk_push_undefined(ctx);
  39060. }
  39061. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_SET);
  39062. } else {
  39063. duk_dup(ctx, -2); /* [obj key value desc value] */
  39064. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_VALUE);
  39065. duk_push_boolean(ctx, DUK_PROPDESC_IS_WRITABLE(&pd));
  39066. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_WRITABLE);
  39067. /* [obj key value desc] */
  39068. }
  39069. duk_push_boolean(ctx, DUK_PROPDESC_IS_ENUMERABLE(&pd));
  39070. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_ENUMERABLE);
  39071. duk_push_boolean(ctx, DUK_PROPDESC_IS_CONFIGURABLE(&pd));
  39072. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_CONFIGURABLE);
  39073. /* [obj key value desc] */
  39074. return 1;
  39075. }
  39076. /*
  39077. * NormalizePropertyDescriptor() related helper.
  39078. *
  39079. * Internal helper which validates and normalizes a property descriptor
  39080. * represented as an Ecmascript object (e.g. argument to defineProperty()).
  39081. * The output of this conversion is a set of defprop_flags and possibly
  39082. * some values pushed on the value stack; some subset of: property value,
  39083. * getter, setter. Caller must manage stack top carefully because the
  39084. * number of values pushed depends on the input property descriptor.
  39085. *
  39086. * The original descriptor object must not be altered in the process.
  39087. */
  39088. /* XXX: very basic optimization -> duk_get_prop_stridx_top */
  39089. DUK_INTERNAL
  39090. void duk_hobject_prepare_property_descriptor(duk_context *ctx,
  39091. duk_idx_t idx_in,
  39092. duk_uint_t *out_defprop_flags,
  39093. duk_idx_t *out_idx_value,
  39094. duk_hobject **out_getter,
  39095. duk_hobject **out_setter) {
  39096. duk_hthread *thr = (duk_hthread *) ctx;
  39097. duk_idx_t idx_value = -1;
  39098. duk_hobject *getter = NULL;
  39099. duk_hobject *setter = NULL;
  39100. duk_bool_t is_data_desc = 0;
  39101. duk_bool_t is_acc_desc = 0;
  39102. duk_uint_t defprop_flags = 0;
  39103. DUK_ASSERT(ctx != NULL);
  39104. DUK_ASSERT(out_defprop_flags != NULL);
  39105. DUK_ASSERT(out_idx_value != NULL);
  39106. DUK_ASSERT(out_getter != NULL);
  39107. DUK_ASSERT(out_setter != NULL);
  39108. /* Must be an object, otherwise TypeError (E5.1 Section 8.10.5, step 1). */
  39109. idx_in = duk_require_normalize_index(ctx, idx_in);
  39110. (void) duk_require_hobject(ctx, idx_in);
  39111. /* The coercion order must match the ToPropertyDescriptor() algorithm
  39112. * so that side effects in coercion happen in the correct order.
  39113. * (This order also happens to be compatible with duk_def_prop(),
  39114. * although it doesn't matter in practice.)
  39115. */
  39116. if (duk_get_prop_stridx(ctx, idx_in, DUK_STRIDX_VALUE)) {
  39117. is_data_desc = 1;
  39118. defprop_flags |= DUK_DEFPROP_HAVE_VALUE;
  39119. idx_value = duk_get_top_index(ctx);
  39120. /* Leave 'value' on stack */
  39121. } else {
  39122. duk_pop(ctx);
  39123. }
  39124. if (duk_get_prop_stridx(ctx, idx_in, DUK_STRIDX_WRITABLE)) {
  39125. is_data_desc = 1;
  39126. if (duk_to_boolean(ctx, -1)) {
  39127. defprop_flags |= DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_WRITABLE;
  39128. } else {
  39129. defprop_flags |= DUK_DEFPROP_HAVE_WRITABLE;
  39130. }
  39131. }
  39132. duk_pop(ctx);
  39133. if (duk_get_prop_stridx(ctx, idx_in, DUK_STRIDX_GET)) {
  39134. duk_tval *tv = duk_require_tval(ctx, -1);
  39135. duk_hobject *h_get;
  39136. if (DUK_TVAL_IS_UNDEFINED(tv)) {
  39137. /* undefined is accepted */
  39138. DUK_ASSERT(getter == NULL);
  39139. } else {
  39140. /* NOTE: lightfuncs are coerced to full functions because
  39141. * lightfuncs don't fit into a property value slot. This
  39142. * has some side effects, see test-dev-lightfunc-accessor.js.
  39143. */
  39144. h_get = duk_get_hobject_or_lfunc_coerce(ctx, -1);
  39145. if (h_get == NULL || !DUK_HOBJECT_IS_CALLABLE(h_get)) {
  39146. goto type_error;
  39147. }
  39148. getter = h_get;
  39149. }
  39150. is_acc_desc = 1;
  39151. defprop_flags |= DUK_DEFPROP_HAVE_GETTER;
  39152. /* Leave 'getter' on stack */
  39153. } else {
  39154. duk_pop(ctx);
  39155. }
  39156. if (duk_get_prop_stridx(ctx, idx_in, DUK_STRIDX_SET)) {
  39157. duk_tval *tv = duk_require_tval(ctx, -1);
  39158. duk_hobject *h_set;
  39159. is_acc_desc = 1;
  39160. if (DUK_TVAL_IS_UNDEFINED(tv)) {
  39161. /* undefined is accepted */
  39162. DUK_ASSERT(setter == NULL);
  39163. } else {
  39164. /* NOTE: lightfuncs are coerced to full functions because
  39165. * lightfuncs don't fit into a property value slot. This
  39166. * has some side effects, see test-dev-lightfunc-accessor.js.
  39167. */
  39168. h_set = duk_get_hobject_or_lfunc_coerce(ctx, -1);
  39169. if (h_set == NULL || !DUK_HOBJECT_IS_CALLABLE(h_set)) {
  39170. goto type_error;
  39171. }
  39172. setter = h_set;
  39173. }
  39174. is_acc_desc = 1;
  39175. defprop_flags |= DUK_DEFPROP_HAVE_SETTER;
  39176. /* Leave 'setter' on stack */
  39177. } else {
  39178. duk_pop(ctx);
  39179. }
  39180. if (duk_get_prop_stridx(ctx, idx_in, DUK_STRIDX_ENUMERABLE)) {
  39181. if (duk_to_boolean(ctx, -1)) {
  39182. defprop_flags |= DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE;
  39183. } else {
  39184. defprop_flags |= DUK_DEFPROP_HAVE_ENUMERABLE;
  39185. }
  39186. }
  39187. duk_pop(ctx);
  39188. if (duk_get_prop_stridx(ctx, idx_in, DUK_STRIDX_CONFIGURABLE)) {
  39189. if (duk_to_boolean(ctx, -1)) {
  39190. defprop_flags |= DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE;
  39191. } else {
  39192. defprop_flags |= DUK_DEFPROP_HAVE_CONFIGURABLE;
  39193. }
  39194. }
  39195. duk_pop(ctx);
  39196. if (is_data_desc && is_acc_desc) {
  39197. goto type_error;
  39198. }
  39199. *out_defprop_flags = defprop_flags;
  39200. *out_idx_value = idx_value;
  39201. *out_getter = getter;
  39202. *out_setter = setter;
  39203. /* [ ... value? getter? setter? ] */
  39204. return;
  39205. type_error:
  39206. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_INVALID_DESCRIPTOR);
  39207. }
  39208. /*
  39209. * Object.defineProperty() related helper (E5 Section 15.2.3.6)
  39210. *
  39211. * Inlines all [[DefineOwnProperty]] exotic behaviors.
  39212. *
  39213. * Note: Ecmascript compliant [[DefineOwnProperty]](P, Desc, Throw) is not
  39214. * implemented directly, but Object.defineProperty() serves its purpose.
  39215. * We don't need the [[DefineOwnProperty]] internally and we don't have a
  39216. * property descriptor with 'missing values' so it's easier to avoid it
  39217. * entirely.
  39218. *
  39219. * Note: this is only called for actual objects, not primitive values.
  39220. * This must support virtual properties for full objects (e.g. Strings)
  39221. * but not for plain values (e.g. strings). Lightfuncs, even though
  39222. * primitive in a sense, are treated like objects and accepted as target
  39223. * values.
  39224. */
  39225. /* XXX: this is a major target for size optimization */
  39226. DUK_INTERNAL
  39227. void duk_hobject_define_property_helper(duk_context *ctx,
  39228. duk_uint_t defprop_flags,
  39229. duk_hobject *obj,
  39230. duk_hstring *key,
  39231. duk_idx_t idx_value,
  39232. duk_hobject *get,
  39233. duk_hobject *set) {
  39234. duk_hthread *thr = (duk_hthread *) ctx;
  39235. duk_uint32_t arr_idx;
  39236. duk_tval tv;
  39237. duk_bool_t has_enumerable;
  39238. duk_bool_t has_configurable;
  39239. duk_bool_t has_writable;
  39240. duk_bool_t has_value;
  39241. duk_bool_t has_get;
  39242. duk_bool_t has_set;
  39243. duk_bool_t is_enumerable;
  39244. duk_bool_t is_configurable;
  39245. duk_bool_t is_writable;
  39246. duk_bool_t throw_flag;
  39247. duk_bool_t force_flag;
  39248. duk_small_uint_t new_flags;
  39249. duk_propdesc curr;
  39250. duk_uint32_t arridx_new_array_length; /* != 0 => post-update for array 'length' (used when key is an array index) */
  39251. duk_uint32_t arrlen_old_len;
  39252. duk_uint32_t arrlen_new_len;
  39253. duk_bool_t pending_write_protect;
  39254. DUK_ASSERT(thr != NULL);
  39255. DUK_ASSERT(thr->heap != NULL);
  39256. DUK_ASSERT(ctx != NULL);
  39257. DUK_ASSERT(obj != NULL);
  39258. DUK_ASSERT(key != NULL);
  39259. /* idx_value may be < 0 (no value), set and get may be NULL */
  39260. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  39261. /* All the flags fit in 16 bits, so will fit into duk_bool_t. */
  39262. has_writable = (defprop_flags & DUK_DEFPROP_HAVE_WRITABLE);
  39263. has_enumerable = (defprop_flags & DUK_DEFPROP_HAVE_ENUMERABLE);
  39264. has_configurable = (defprop_flags & DUK_DEFPROP_HAVE_CONFIGURABLE);
  39265. has_value = (defprop_flags & DUK_DEFPROP_HAVE_VALUE);
  39266. has_get = (defprop_flags & DUK_DEFPROP_HAVE_GETTER);
  39267. has_set = (defprop_flags & DUK_DEFPROP_HAVE_SETTER);
  39268. is_writable = (defprop_flags & DUK_DEFPROP_WRITABLE);
  39269. is_enumerable = (defprop_flags & DUK_DEFPROP_ENUMERABLE);
  39270. is_configurable = (defprop_flags & DUK_DEFPROP_CONFIGURABLE);
  39271. throw_flag = 1; /* Object.defineProperty() calls [[DefineOwnProperty]] with Throw=true */
  39272. force_flag = (defprop_flags & DUK_DEFPROP_FORCE);
  39273. arr_idx = DUK_HSTRING_GET_ARRIDX_SLOW(key);
  39274. arridx_new_array_length = 0;
  39275. pending_write_protect = 0;
  39276. arrlen_old_len = 0;
  39277. arrlen_new_len = 0;
  39278. DUK_DDD(DUK_DDDPRINT("has_enumerable=%ld is_enumerable=%ld "
  39279. "has_configurable=%ld is_configurable=%ld "
  39280. "has_writable=%ld is_writable=%ld "
  39281. "has_value=%ld value=%!T "
  39282. "has_get=%ld get=%p=%!O "
  39283. "has_set=%ld set=%p=%!O "
  39284. "arr_idx=%ld",
  39285. (long) has_enumerable, (long) is_enumerable,
  39286. (long) has_configurable, (long) is_configurable,
  39287. (long) has_writable, (long) is_writable,
  39288. (long) has_value, (duk_tval *) (idx_value >= 0 ? duk_get_tval(ctx, idx_value) : NULL),
  39289. (long) has_get, (void *) get, (duk_heaphdr *) get,
  39290. (long) has_set, (void *) set, (duk_heaphdr *) set,
  39291. (long) arr_idx));
  39292. /*
  39293. * Array exotic behaviors can be implemented at this point. The local variables
  39294. * are essentially a 'value copy' of the input descriptor (Desc), which is modified
  39295. * by the Array [[DefineOwnProperty]] (E5 Section 15.4.5.1).
  39296. */
  39297. if (!DUK_HOBJECT_HAS_EXOTIC_ARRAY(obj)) {
  39298. goto skip_array_exotic;
  39299. }
  39300. if (key == DUK_HTHREAD_STRING_LENGTH(thr)) {
  39301. /* E5 Section 15.4.5.1, step 3, steps a - i are implemented here, j - n at the end */
  39302. if (!has_value) {
  39303. DUK_DDD(DUK_DDDPRINT("exotic array behavior for 'length', but no value in descriptor -> normal behavior"));
  39304. goto skip_array_exotic;
  39305. }
  39306. DUK_DDD(DUK_DDDPRINT("exotic array behavior for 'length', value present in descriptor -> exotic behavior"));
  39307. /*
  39308. * Get old and new length
  39309. */
  39310. /* Note: reuse 'curr' as a temp propdesc */
  39311. arrlen_old_len = duk__get_old_array_length(thr, obj, &curr);
  39312. duk_dup(ctx, idx_value);
  39313. arrlen_new_len = duk__to_new_array_length_checked(thr);
  39314. duk_push_u32(ctx, arrlen_new_len);
  39315. duk_replace(ctx, idx_value); /* step 3.e: replace 'Desc.[[Value]]' */
  39316. DUK_DDD(DUK_DDDPRINT("old_len=%ld, new_len=%ld", (long) arrlen_old_len, (long) arrlen_new_len));
  39317. if (arrlen_new_len >= arrlen_old_len) {
  39318. /* standard behavior, step 3.f.i */
  39319. DUK_DDD(DUK_DDDPRINT("new length is same or higher as previous => standard behavior"));
  39320. goto skip_array_exotic;
  39321. }
  39322. DUK_DDD(DUK_DDDPRINT("new length is smaller than previous => exotic post behavior"));
  39323. /* XXX: consolidated algorithm step 15.f -> redundant? */
  39324. if (!(curr.flags & DUK_PROPDESC_FLAG_WRITABLE) && !force_flag) {
  39325. /* Note: 'curr' refers to 'length' propdesc */
  39326. goto fail_not_writable_array_length;
  39327. }
  39328. /* steps 3.h and 3.i */
  39329. if (has_writable && !is_writable) {
  39330. DUK_DDD(DUK_DDDPRINT("desc writable is false, force it back to true, and flag pending write protect"));
  39331. is_writable = 1;
  39332. pending_write_protect = 1;
  39333. }
  39334. /* remaining actual steps are carried out if standard DefineOwnProperty succeeds */
  39335. } else if (arr_idx != DUK__NO_ARRAY_INDEX) {
  39336. /* XXX: any chance of unifying this with the 'length' key handling? */
  39337. /* E5 Section 15.4.5.1, step 4 */
  39338. duk_uint32_t old_len;
  39339. /* Note: use 'curr' as a temp propdesc */
  39340. old_len = duk__get_old_array_length(thr, obj, &curr);
  39341. if (arr_idx >= old_len) {
  39342. DUK_DDD(DUK_DDDPRINT("defineProperty requires array length update "
  39343. "(arr_idx=%ld, old_len=%ld)",
  39344. (long) arr_idx, (long) old_len));
  39345. if (!(curr.flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  39346. /* Note: 'curr' refers to 'length' propdesc */
  39347. goto fail_not_writable_array_length;
  39348. }
  39349. /* actual update happens once write has been completed without
  39350. * error below.
  39351. */
  39352. DUK_ASSERT(arr_idx != 0xffffffffUL);
  39353. arridx_new_array_length = arr_idx + 1;
  39354. } else {
  39355. DUK_DDD(DUK_DDDPRINT("defineProperty does not require length update "
  39356. "(arr_idx=%ld, old_len=%ld) -> standard behavior",
  39357. (long) arr_idx, (long) old_len));
  39358. }
  39359. }
  39360. skip_array_exotic:
  39361. /* XXX: There is currently no support for writing buffer object
  39362. * indexed elements here. Attempt to do so will succeed and
  39363. * write a concrete property into the buffer object. This should
  39364. * be fixed at some point but because buffers are a custom feature
  39365. * anyway, this is relatively unimportant.
  39366. */
  39367. /*
  39368. * Actual Object.defineProperty() default algorithm.
  39369. */
  39370. /*
  39371. * First check whether property exists; if not, simple case. This covers
  39372. * steps 1-4.
  39373. */
  39374. if (!duk__get_own_property_desc_raw(thr, obj, key, arr_idx, &curr, DUK__DESC_FLAG_PUSH_VALUE)) {
  39375. DUK_DDD(DUK_DDDPRINT("property does not exist"));
  39376. if (!DUK_HOBJECT_HAS_EXTENSIBLE(obj) && !force_flag) {
  39377. goto fail_not_extensible;
  39378. }
  39379. /* XXX: share final setting code for value and flags? difficult because
  39380. * refcount code is different. Share entry allocation? But can't allocate
  39381. * until array index checked.
  39382. */
  39383. /* steps 4.a and 4.b are tricky */
  39384. if (has_set || has_get) {
  39385. duk_int_t e_idx;
  39386. DUK_DDD(DUK_DDDPRINT("create new accessor property"));
  39387. DUK_ASSERT(has_set || set == NULL);
  39388. DUK_ASSERT(has_get || get == NULL);
  39389. DUK_ASSERT(!has_value);
  39390. DUK_ASSERT(!has_writable);
  39391. new_flags = DUK_PROPDESC_FLAG_ACCESSOR; /* defaults, E5 Section 8.6.1, Table 7 */
  39392. if (has_enumerable && is_enumerable) {
  39393. new_flags |= DUK_PROPDESC_FLAG_ENUMERABLE;
  39394. }
  39395. if (has_configurable && is_configurable) {
  39396. new_flags |= DUK_PROPDESC_FLAG_CONFIGURABLE;
  39397. }
  39398. if (arr_idx != DUK__NO_ARRAY_INDEX && DUK_HOBJECT_HAS_ARRAY_PART(obj)) {
  39399. DUK_DDD(DUK_DDDPRINT("accessor cannot go to array part, abandon array"));
  39400. duk__abandon_array_checked(thr, obj);
  39401. }
  39402. /* write to entry part */
  39403. e_idx = duk__alloc_entry_checked(thr, obj, key);
  39404. DUK_ASSERT(e_idx >= 0);
  39405. DUK_HOBJECT_E_SET_VALUE_GETTER(thr->heap, obj, e_idx, get);
  39406. DUK_HOBJECT_E_SET_VALUE_SETTER(thr->heap, obj, e_idx, set);
  39407. DUK_HOBJECT_INCREF_ALLOWNULL(thr, get);
  39408. DUK_HOBJECT_INCREF_ALLOWNULL(thr, set);
  39409. DUK_HOBJECT_E_SET_FLAGS(thr->heap, obj, e_idx, new_flags);
  39410. goto success_exotics;
  39411. } else {
  39412. duk_int_t e_idx;
  39413. duk_tval *tv2;
  39414. DUK_DDD(DUK_DDDPRINT("create new data property"));
  39415. DUK_ASSERT(!has_set);
  39416. DUK_ASSERT(!has_get);
  39417. new_flags = 0; /* defaults, E5 Section 8.6.1, Table 7 */
  39418. if (has_writable && is_writable) {
  39419. new_flags |= DUK_PROPDESC_FLAG_WRITABLE;
  39420. }
  39421. if (has_enumerable && is_enumerable) {
  39422. new_flags |= DUK_PROPDESC_FLAG_ENUMERABLE;
  39423. }
  39424. if (has_configurable && is_configurable) {
  39425. new_flags |= DUK_PROPDESC_FLAG_CONFIGURABLE;
  39426. }
  39427. if (has_value) {
  39428. duk_tval *tv_tmp = duk_require_tval(ctx, idx_value);
  39429. DUK_TVAL_SET_TVAL(&tv, tv_tmp);
  39430. } else {
  39431. DUK_TVAL_SET_UNDEFINED_ACTUAL(&tv); /* default value */
  39432. }
  39433. if (arr_idx != DUK__NO_ARRAY_INDEX && DUK_HOBJECT_HAS_ARRAY_PART(obj)) {
  39434. if (new_flags == DUK_PROPDESC_FLAGS_WEC) {
  39435. #if 0
  39436. DUK_DDD(DUK_DDDPRINT("new data property attributes match array defaults, attempt to write to array part"));
  39437. /* may become sparse...*/
  39438. #endif
  39439. /* XXX: handling for array part missing now; this doesn't affect
  39440. * compliance but causes array entry writes using defineProperty()
  39441. * to always abandon array part.
  39442. */
  39443. }
  39444. DUK_DDD(DUK_DDDPRINT("new data property cannot go to array part, abandon array"));
  39445. duk__abandon_array_checked(thr, obj);
  39446. /* fall through */
  39447. }
  39448. /* write to entry part */
  39449. e_idx = duk__alloc_entry_checked(thr, obj, key);
  39450. DUK_ASSERT(e_idx >= 0);
  39451. tv2 = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, e_idx);
  39452. DUK_TVAL_SET_TVAL(tv2, &tv);
  39453. DUK_TVAL_INCREF(thr, tv2);
  39454. DUK_HOBJECT_E_SET_FLAGS(thr->heap, obj, e_idx, new_flags);
  39455. goto success_exotics;
  39456. }
  39457. DUK_UNREACHABLE();
  39458. }
  39459. /* we currently assume virtual properties are not configurable (as none of them are) */
  39460. DUK_ASSERT((curr.e_idx >= 0 || curr.a_idx >= 0) || !(curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE));
  39461. /* [obj key desc value get set curr_value] */
  39462. /*
  39463. * Property already exists. Steps 5-6 detect whether any changes need
  39464. * to be made.
  39465. */
  39466. if (has_enumerable) {
  39467. if (is_enumerable) {
  39468. if (!(curr.flags & DUK_PROPDESC_FLAG_ENUMERABLE)) {
  39469. goto need_check;
  39470. }
  39471. } else {
  39472. if (curr.flags & DUK_PROPDESC_FLAG_ENUMERABLE) {
  39473. goto need_check;
  39474. }
  39475. }
  39476. }
  39477. if (has_configurable) {
  39478. if (is_configurable) {
  39479. if (!(curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE)) {
  39480. goto need_check;
  39481. }
  39482. } else {
  39483. if (curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) {
  39484. goto need_check;
  39485. }
  39486. }
  39487. }
  39488. if (has_value) {
  39489. duk_tval *tmp1;
  39490. duk_tval *tmp2;
  39491. /* attempt to change from accessor to data property */
  39492. if (curr.flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  39493. goto need_check;
  39494. }
  39495. tmp1 = duk_require_tval(ctx, -1); /* curr value */
  39496. tmp2 = duk_require_tval(ctx, idx_value); /* new value */
  39497. if (!duk_js_samevalue(tmp1, tmp2)) {
  39498. goto need_check;
  39499. }
  39500. }
  39501. if (has_writable) {
  39502. /* attempt to change from accessor to data property */
  39503. if (curr.flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  39504. goto need_check;
  39505. }
  39506. if (is_writable) {
  39507. if (!(curr.flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  39508. goto need_check;
  39509. }
  39510. } else {
  39511. if (curr.flags & DUK_PROPDESC_FLAG_WRITABLE) {
  39512. goto need_check;
  39513. }
  39514. }
  39515. }
  39516. if (has_set) {
  39517. if (curr.flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  39518. if (set != curr.set) {
  39519. goto need_check;
  39520. }
  39521. } else {
  39522. goto need_check;
  39523. }
  39524. }
  39525. if (has_get) {
  39526. if (curr.flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  39527. if (get != curr.get) {
  39528. goto need_check;
  39529. }
  39530. } else {
  39531. goto need_check;
  39532. }
  39533. }
  39534. /* property exists, either 'desc' is empty, or all values
  39535. * match (SameValue)
  39536. */
  39537. goto success_no_exotics;
  39538. need_check:
  39539. /*
  39540. * Some change(s) need to be made. Steps 7-11.
  39541. */
  39542. /* shared checks for all descriptor types */
  39543. if (!(curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) && !force_flag) {
  39544. if (has_configurable && is_configurable) {
  39545. goto fail_not_configurable;
  39546. }
  39547. if (has_enumerable) {
  39548. if (curr.flags & DUK_PROPDESC_FLAG_ENUMERABLE) {
  39549. if (!is_enumerable) {
  39550. goto fail_not_configurable;
  39551. }
  39552. } else {
  39553. if (is_enumerable) {
  39554. goto fail_not_configurable;
  39555. }
  39556. }
  39557. }
  39558. }
  39559. /* Reject attempt to change virtual properties: not part of the
  39560. * standard algorithm, applies currently to e.g. virtual index
  39561. * properties of buffer objects (which are virtual but writable).
  39562. * (Cannot "force" modification of a virtual property.)
  39563. */
  39564. if (curr.flags & DUK_PROPDESC_FLAG_VIRTUAL) {
  39565. goto fail_virtual;
  39566. }
  39567. /* descriptor type specific checks */
  39568. if (has_set || has_get) {
  39569. /* IsAccessorDescriptor(desc) == true */
  39570. DUK_ASSERT(!has_writable);
  39571. DUK_ASSERT(!has_value);
  39572. if (curr.flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  39573. /* curr and desc are accessors */
  39574. if (!(curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) && !force_flag) {
  39575. if (has_set && set != curr.set) {
  39576. goto fail_not_configurable;
  39577. }
  39578. if (has_get && get != curr.get) {
  39579. goto fail_not_configurable;
  39580. }
  39581. }
  39582. } else {
  39583. duk_bool_t rc;
  39584. duk_tval tv_tmp;
  39585. duk_tval *tv1;
  39586. /* curr is data, desc is accessor */
  39587. if (!(curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) && !force_flag) {
  39588. goto fail_not_configurable;
  39589. }
  39590. DUK_DDD(DUK_DDDPRINT("convert property to accessor property"));
  39591. if (curr.a_idx >= 0) {
  39592. DUK_DDD(DUK_DDDPRINT("property to convert is stored in an array entry, abandon array and re-lookup"));
  39593. duk__abandon_array_checked(thr, obj);
  39594. duk_pop(ctx); /* remove old value */
  39595. rc = duk__get_own_property_desc_raw(thr, obj, key, arr_idx, &curr, DUK__DESC_FLAG_PUSH_VALUE);
  39596. DUK_UNREF(rc);
  39597. DUK_ASSERT(rc != 0);
  39598. DUK_ASSERT(curr.e_idx >= 0 && curr.a_idx < 0);
  39599. }
  39600. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, curr.e_idx));
  39601. tv1 = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, curr.e_idx);
  39602. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  39603. DUK_TVAL_SET_UNDEFINED_UNUSED(tv1);
  39604. DUK_TVAL_DECREF(thr, &tv_tmp);
  39605. DUK_HOBJECT_E_SET_VALUE_GETTER(thr->heap, obj, curr.e_idx, NULL);
  39606. DUK_HOBJECT_E_SET_VALUE_SETTER(thr->heap, obj, curr.e_idx, NULL);
  39607. DUK_HOBJECT_E_SLOT_CLEAR_WRITABLE(thr->heap, obj, curr.e_idx);
  39608. DUK_HOBJECT_E_SLOT_SET_ACCESSOR(thr->heap, obj, curr.e_idx);
  39609. DUK_DDD(DUK_DDDPRINT("flags after data->accessor conversion: 0x%02lx",
  39610. (unsigned long) DUK_HOBJECT_E_GET_FLAGS(thr->heap, obj, curr.e_idx)));
  39611. /* re-lookup to update curr.flags
  39612. * XXX: would be faster to update directly
  39613. */
  39614. duk_pop(ctx); /* remove old value */
  39615. rc = duk__get_own_property_desc_raw(thr, obj, key, arr_idx, &curr, DUK__DESC_FLAG_PUSH_VALUE);
  39616. DUK_UNREF(rc);
  39617. DUK_ASSERT(rc != 0);
  39618. }
  39619. } else if (has_value || has_writable) {
  39620. /* IsDataDescriptor(desc) == true */
  39621. DUK_ASSERT(!has_set);
  39622. DUK_ASSERT(!has_get);
  39623. if (curr.flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  39624. duk_bool_t rc;
  39625. duk_hobject *tmp;
  39626. /* curr is accessor, desc is data */
  39627. if (!(curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) && !force_flag) {
  39628. goto fail_not_configurable;
  39629. }
  39630. /* curr is accessor -> cannot be in array part */
  39631. DUK_ASSERT(curr.e_idx >= 0 && curr.a_idx < 0);
  39632. DUK_DDD(DUK_DDDPRINT("convert property to data property"));
  39633. DUK_ASSERT(DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, curr.e_idx));
  39634. tmp = DUK_HOBJECT_E_GET_VALUE_GETTER(thr->heap, obj, curr.e_idx);
  39635. DUK_UNREF(tmp);
  39636. DUK_HOBJECT_E_SET_VALUE_GETTER(thr->heap, obj, curr.e_idx, NULL);
  39637. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  39638. tmp = DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, obj, curr.e_idx);
  39639. DUK_UNREF(tmp);
  39640. DUK_HOBJECT_E_SET_VALUE_SETTER(thr->heap, obj, curr.e_idx, NULL);
  39641. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  39642. DUK_TVAL_SET_UNDEFINED_ACTUAL(DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, curr.e_idx));
  39643. DUK_HOBJECT_E_SLOT_CLEAR_WRITABLE(thr->heap, obj, curr.e_idx);
  39644. DUK_HOBJECT_E_SLOT_CLEAR_ACCESSOR(thr->heap, obj, curr.e_idx);
  39645. DUK_DDD(DUK_DDDPRINT("flags after accessor->data conversion: 0x%02lx",
  39646. (unsigned long) DUK_HOBJECT_E_GET_FLAGS(thr->heap, obj, curr.e_idx)));
  39647. /* re-lookup to update curr.flags
  39648. * XXX: would be faster to update directly
  39649. */
  39650. duk_pop(ctx); /* remove old value */
  39651. rc = duk__get_own_property_desc_raw(thr, obj, key, arr_idx, &curr, DUK__DESC_FLAG_PUSH_VALUE);
  39652. DUK_UNREF(rc);
  39653. DUK_ASSERT(rc != 0);
  39654. } else {
  39655. /* curr and desc are data */
  39656. if (!(curr.flags & DUK_PROPDESC_FLAG_CONFIGURABLE) && !force_flag) {
  39657. if (!(curr.flags & DUK_PROPDESC_FLAG_WRITABLE) && has_writable && is_writable) {
  39658. goto fail_not_configurable;
  39659. }
  39660. /* Note: changing from writable to non-writable is OK */
  39661. if (!(curr.flags & DUK_PROPDESC_FLAG_WRITABLE) && has_value) {
  39662. duk_tval *tmp1 = duk_require_tval(ctx, -1); /* curr value */
  39663. duk_tval *tmp2 = duk_require_tval(ctx, idx_value); /* new value */
  39664. if (!duk_js_samevalue(tmp1, tmp2)) {
  39665. goto fail_not_configurable;
  39666. }
  39667. }
  39668. }
  39669. }
  39670. } else {
  39671. /* IsGenericDescriptor(desc) == true; this means in practice that 'desc'
  39672. * only has [[Enumerable]] or [[Configurable]] flag updates, which are
  39673. * allowed at this point.
  39674. */
  39675. DUK_ASSERT(!has_value && !has_writable && !has_get && !has_set);
  39676. }
  39677. /*
  39678. * Start doing property attributes updates. Steps 12-13.
  39679. *
  39680. * Start by computing new attribute flags without writing yet.
  39681. * Property type conversion is done above if necessary.
  39682. */
  39683. new_flags = curr.flags;
  39684. if (has_enumerable) {
  39685. if (is_enumerable) {
  39686. new_flags |= DUK_PROPDESC_FLAG_ENUMERABLE;
  39687. } else {
  39688. new_flags &= ~DUK_PROPDESC_FLAG_ENUMERABLE;
  39689. }
  39690. }
  39691. if (has_configurable) {
  39692. if (is_configurable) {
  39693. new_flags |= DUK_PROPDESC_FLAG_CONFIGURABLE;
  39694. } else {
  39695. new_flags &= ~DUK_PROPDESC_FLAG_CONFIGURABLE;
  39696. }
  39697. }
  39698. if (has_writable) {
  39699. if (is_writable) {
  39700. new_flags |= DUK_PROPDESC_FLAG_WRITABLE;
  39701. } else {
  39702. new_flags &= ~DUK_PROPDESC_FLAG_WRITABLE;
  39703. }
  39704. }
  39705. /* XXX: write protect after flag? -> any chance of handling it here? */
  39706. DUK_DDD(DUK_DDDPRINT("new flags that we want to write: 0x%02lx",
  39707. (unsigned long) new_flags));
  39708. /*
  39709. * Check whether we need to abandon an array part (if it exists)
  39710. */
  39711. if (curr.a_idx >= 0) {
  39712. duk_bool_t rc;
  39713. DUK_ASSERT(curr.e_idx < 0);
  39714. if (new_flags == DUK_PROPDESC_FLAGS_WEC) {
  39715. duk_tval *tv1, *tv2;
  39716. duk_tval tv_tmp;
  39717. DUK_DDD(DUK_DDDPRINT("array index, new property attributes match array defaults, update in-place"));
  39718. DUK_ASSERT(curr.flags == DUK_PROPDESC_FLAGS_WEC); /* must have been, since in array part */
  39719. DUK_ASSERT(!has_set);
  39720. DUK_ASSERT(!has_get);
  39721. tv2 = duk_require_tval(ctx, idx_value);
  39722. tv1 = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, curr.a_idx);
  39723. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  39724. DUK_TVAL_SET_TVAL(tv1, tv2);
  39725. DUK_TVAL_INCREF(thr, tv1);
  39726. DUK_TVAL_DECREF(thr, &tv_tmp);
  39727. goto success_exotics;
  39728. }
  39729. DUK_DDD(DUK_DDDPRINT("array index, new property attributes do not match array defaults, abandon array and re-lookup"));
  39730. duk__abandon_array_checked(thr, obj);
  39731. duk_pop(ctx); /* remove old value */
  39732. rc = duk__get_own_property_desc_raw(thr, obj, key, arr_idx, &curr, DUK__DESC_FLAG_PUSH_VALUE);
  39733. DUK_UNREF(rc);
  39734. DUK_ASSERT(rc != 0);
  39735. DUK_ASSERT(curr.e_idx >= 0 && curr.a_idx < 0);
  39736. }
  39737. DUK_DDD(DUK_DDDPRINT("updating existing property in entry part"));
  39738. /* array case is handled comprehensively above */
  39739. DUK_ASSERT(curr.e_idx >= 0 && curr.a_idx < 0);
  39740. DUK_DDD(DUK_DDDPRINT("update existing property attributes"));
  39741. DUK_HOBJECT_E_SET_FLAGS(thr->heap, obj, curr.e_idx, new_flags);
  39742. if (has_set) {
  39743. duk_hobject *tmp;
  39744. DUK_DDD(DUK_DDDPRINT("update existing property setter"));
  39745. DUK_ASSERT(DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, curr.e_idx));
  39746. tmp = DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, obj, curr.e_idx);
  39747. DUK_UNREF(tmp);
  39748. DUK_HOBJECT_E_SET_VALUE_SETTER(thr->heap, obj, curr.e_idx, set);
  39749. DUK_HOBJECT_INCREF_ALLOWNULL(thr, set);
  39750. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  39751. }
  39752. if (has_get) {
  39753. duk_hobject *tmp;
  39754. DUK_DDD(DUK_DDDPRINT("update existing property getter"));
  39755. DUK_ASSERT(DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, curr.e_idx));
  39756. tmp = DUK_HOBJECT_E_GET_VALUE_GETTER(thr->heap, obj, curr.e_idx);
  39757. DUK_UNREF(tmp);
  39758. DUK_HOBJECT_E_SET_VALUE_GETTER(thr->heap, obj, curr.e_idx, get);
  39759. DUK_HOBJECT_INCREF_ALLOWNULL(thr, get);
  39760. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  39761. }
  39762. if (has_value) {
  39763. duk_tval *tv1, *tv2;
  39764. duk_tval tv_tmp;
  39765. DUK_DDD(DUK_DDDPRINT("update existing property value"));
  39766. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, curr.e_idx));
  39767. tv2 = duk_require_tval(ctx, idx_value);
  39768. tv1 = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, curr.e_idx);
  39769. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  39770. DUK_TVAL_SET_TVAL(tv1, tv2);
  39771. DUK_TVAL_INCREF(thr, tv1);
  39772. DUK_TVAL_DECREF(thr, &tv_tmp);
  39773. }
  39774. /*
  39775. * Standard algorithm succeeded without errors, check for exotic post-behaviors.
  39776. *
  39777. * Arguments exotic behavior in E5 Section 10.6 occurs after the standard
  39778. * [[DefineOwnProperty]] has completed successfully.
  39779. *
  39780. * Array exotic behavior in E5 Section 15.4.5.1 is implemented partly
  39781. * prior to the default [[DefineOwnProperty]], but:
  39782. * - for an array index key (e.g. "10") the final 'length' update occurs here
  39783. * - for 'length' key the element deletion and 'length' update occurs here
  39784. */
  39785. success_exotics:
  39786. /* [obj key desc value get set curr_value] */
  39787. if (DUK_HOBJECT_HAS_EXOTIC_ARRAY(obj)) {
  39788. if (arridx_new_array_length > 0) {
  39789. duk_tval *tmp;
  39790. duk_bool_t rc;
  39791. /*
  39792. * Note: zero works as a "no update" marker because the new length
  39793. * can never be zero after a new property is written.
  39794. */
  39795. /* E5 Section 15.4.5.1, steps 4.e.i - 4.e.ii */
  39796. DUK_DDD(DUK_DDDPRINT("defineProperty successful, pending array length update to: %ld",
  39797. (long) arridx_new_array_length));
  39798. /* Note: reuse 'curr' */
  39799. rc = duk__get_own_property_desc_raw(thr, obj, DUK_HTHREAD_STRING_LENGTH(thr), DUK__NO_ARRAY_INDEX, &curr, 0 /*flags*/); /* don't push value */
  39800. DUK_UNREF(rc);
  39801. DUK_ASSERT(rc != 0);
  39802. DUK_ASSERT(curr.e_idx >= 0);
  39803. tmp = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, curr.e_idx);
  39804. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tmp));
  39805. /* no need for decref/incref because value is a number */
  39806. #if defined(DUK_USE_FASTINT)
  39807. DUK_TVAL_SET_FASTINT_U32(tmp, arridx_new_array_length);
  39808. #else
  39809. DUK_TVAL_SET_NUMBER(tmp, (duk_double_t) arridx_new_array_length);
  39810. #endif
  39811. }
  39812. if (key == DUK_HTHREAD_STRING_LENGTH(thr) && arrlen_new_len < arrlen_old_len) {
  39813. /*
  39814. * E5 Section 15.4.5.1, steps 3.k - 3.n. The order at the end combines
  39815. * the error case 3.l.iii and the success case 3.m-3.n.
  39816. *
  39817. * Note: 'length' is always in entries part, so no array abandon issues for
  39818. * 'writable' update.
  39819. */
  39820. /* XXX: investigate whether write protect can be handled above, if we
  39821. * just update length here while ignoring its protected status
  39822. */
  39823. duk_tval *tmp;
  39824. duk_uint32_t result_len;
  39825. duk_bool_t rc;
  39826. DUK_DDD(DUK_DDDPRINT("defineProperty successful, key is 'length', exotic array behavior, "
  39827. "doing array element deletion and length update"));
  39828. rc = duk__handle_put_array_length_smaller(thr, obj, arrlen_old_len, arrlen_new_len, force_flag, &result_len);
  39829. /* update length (curr points to length, and we assume it's still valid) */
  39830. DUK_ASSERT(result_len >= arrlen_new_len && result_len <= arrlen_old_len);
  39831. DUK_ASSERT(curr.e_idx >= 0);
  39832. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, obj, curr.e_idx));
  39833. tmp = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, obj, curr.e_idx);
  39834. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tmp));
  39835. /* no decref needed for a number */
  39836. #if defined(DUK_USE_FASTINT)
  39837. DUK_TVAL_SET_FASTINT_U32(tmp, result_len);
  39838. #else
  39839. DUK_TVAL_SET_NUMBER(tmp, (duk_double_t) result_len);
  39840. #endif
  39841. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tmp));
  39842. if (pending_write_protect) {
  39843. DUK_DDD(DUK_DDDPRINT("setting array length non-writable (pending writability update)"));
  39844. DUK_HOBJECT_E_SLOT_CLEAR_WRITABLE(thr->heap, obj, curr.e_idx);
  39845. }
  39846. /*
  39847. * XXX: shrink array allocation or entries compaction here?
  39848. */
  39849. if (!rc) {
  39850. goto fail_array_length_partial;
  39851. }
  39852. }
  39853. } else if (arr_idx != DUK__NO_ARRAY_INDEX && DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(obj)) {
  39854. duk_hobject *map;
  39855. duk_hobject *varenv;
  39856. DUK_ASSERT(arridx_new_array_length == 0);
  39857. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARRAY(obj)); /* traits are separate; in particular, arguments not an array */
  39858. map = NULL;
  39859. varenv = NULL;
  39860. if (!duk__lookup_arguments_map(thr, obj, key, &curr, &map, &varenv)) {
  39861. goto success_no_exotics;
  39862. }
  39863. DUK_ASSERT(map != NULL);
  39864. DUK_ASSERT(varenv != NULL);
  39865. /* [obj key desc value get set curr_value varname] */
  39866. if (has_set || has_get) {
  39867. /* = IsAccessorDescriptor(Desc) */
  39868. DUK_DDD(DUK_DDDPRINT("defineProperty successful, key mapped to arguments 'map' "
  39869. "changed to an accessor, delete arguments binding"));
  39870. (void) duk_hobject_delprop_raw(thr, map, key, 0); /* ignore result */
  39871. } else {
  39872. /* Note: this order matters (final value before deleting map entry must be done) */
  39873. DUK_DDD(DUK_DDDPRINT("defineProperty successful, key mapped to arguments 'map', "
  39874. "check for value update / binding deletion"));
  39875. if (has_value) {
  39876. duk_hstring *varname;
  39877. DUK_DDD(DUK_DDDPRINT("defineProperty successful, key mapped to arguments 'map', "
  39878. "update bound value (variable/argument)"));
  39879. varname = duk_require_hstring(ctx, -1);
  39880. DUK_ASSERT(varname != NULL);
  39881. DUK_DDD(DUK_DDDPRINT("arguments object automatic putvar for a bound variable; "
  39882. "key=%!O, varname=%!O, value=%!T",
  39883. (duk_heaphdr *) key,
  39884. (duk_heaphdr *) varname,
  39885. (duk_tval *) duk_require_tval(ctx, idx_value)));
  39886. /* strict flag for putvar comes from our caller (currently: fixed) */
  39887. duk_js_putvar_envrec(thr, varenv, varname, duk_require_tval(ctx, idx_value), throw_flag);
  39888. }
  39889. if (has_writable && !is_writable) {
  39890. DUK_DDD(DUK_DDDPRINT("defineProperty successful, key mapped to arguments 'map', "
  39891. "changed to non-writable, delete arguments binding"));
  39892. (void) duk_hobject_delprop_raw(thr, map, key, 0); /* ignore result */
  39893. }
  39894. }
  39895. /* 'varname' is in stack in this else branch, leaving an unbalanced stack below,
  39896. * but this doesn't matter now.
  39897. */
  39898. }
  39899. success_no_exotics:
  39900. return;
  39901. fail_virtual:
  39902. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_PROPERTY_IS_VIRTUAL);
  39903. return;
  39904. fail_not_writable_array_length:
  39905. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_ARRAY_LENGTH_NOT_WRITABLE);
  39906. return;
  39907. fail_not_extensible:
  39908. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_EXTENSIBLE);
  39909. return;
  39910. fail_not_configurable:
  39911. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_CONFIGURABLE);
  39912. return;
  39913. fail_array_length_partial:
  39914. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_ARRAY_LENGTH_WRITE_FAILED);
  39915. return;
  39916. }
  39917. /*
  39918. * Object.prototype.hasOwnProperty() and Object.prototype.propertyIsEnumerable().
  39919. */
  39920. DUK_INTERNAL duk_bool_t duk_hobject_object_ownprop_helper(duk_context *ctx, duk_small_uint_t required_desc_flags) {
  39921. duk_hthread *thr = (duk_hthread *) ctx;
  39922. duk_hstring *h_v;
  39923. duk_hobject *h_obj;
  39924. duk_propdesc desc;
  39925. duk_bool_t ret;
  39926. /* coercion order matters */
  39927. h_v = duk_to_hstring(ctx, 0);
  39928. DUK_ASSERT(h_v != NULL);
  39929. h_obj = duk_push_this_coercible_to_object(ctx);
  39930. DUK_ASSERT(h_obj != NULL);
  39931. ret = duk__get_own_property_desc(thr, h_obj, h_v, &desc, 0 /*flags*/); /* don't push value */
  39932. duk_push_boolean(ctx, ret && ((desc.flags & required_desc_flags) == required_desc_flags));
  39933. return 1;
  39934. }
  39935. /*
  39936. * Object.seal() and Object.freeze() (E5 Sections 15.2.3.8 and 15.2.3.9)
  39937. *
  39938. * Since the algorithms are similar, a helper provides both functions.
  39939. * Freezing is essentially sealing + making plain properties non-writable.
  39940. *
  39941. * Note: virtual (non-concrete) properties which are non-configurable but
  39942. * writable would pose some problems, but such properties do not currently
  39943. * exist (all virtual properties are non-configurable and non-writable).
  39944. * If they did exist, the non-configurability does NOT prevent them from
  39945. * becoming non-writable. However, this change should be recorded somehow
  39946. * so that it would turn up (e.g. when getting the property descriptor),
  39947. * requiring some additional flags in the object.
  39948. */
  39949. DUK_INTERNAL void duk_hobject_object_seal_freeze_helper(duk_hthread *thr, duk_hobject *obj, duk_bool_t is_freeze) {
  39950. duk_uint_fast32_t i;
  39951. DUK_ASSERT(thr != NULL);
  39952. DUK_ASSERT(thr->heap != NULL);
  39953. DUK_ASSERT(obj != NULL);
  39954. DUK_ASSERT_VALSTACK_SPACE(thr, DUK__VALSTACK_SPACE);
  39955. /*
  39956. * Abandon array part because all properties must become non-configurable.
  39957. * Note that this is now done regardless of whether this is always the case
  39958. * (skips check, but performance problem if caller would do this many times
  39959. * for the same object; not likely).
  39960. */
  39961. duk__abandon_array_checked(thr, obj);
  39962. DUK_ASSERT(DUK_HOBJECT_GET_ASIZE(obj) == 0);
  39963. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(obj); i++) {
  39964. duk_uint8_t *fp;
  39965. /* since duk__abandon_array_checked() causes a resize, there should be no gaps in keys */
  39966. DUK_ASSERT(DUK_HOBJECT_E_GET_KEY(thr->heap, obj, i) != NULL);
  39967. /* avoid multiple computations of flags address; bypasses macros */
  39968. fp = DUK_HOBJECT_E_GET_FLAGS_PTR(thr->heap, obj, i);
  39969. if (is_freeze && !((*fp) & DUK_PROPDESC_FLAG_ACCESSOR)) {
  39970. *fp &= ~(DUK_PROPDESC_FLAG_WRITABLE | DUK_PROPDESC_FLAG_CONFIGURABLE);
  39971. } else {
  39972. *fp &= ~DUK_PROPDESC_FLAG_CONFIGURABLE;
  39973. }
  39974. }
  39975. DUK_HOBJECT_CLEAR_EXTENSIBLE(obj);
  39976. /* no need to compact since we already did that in duk__abandon_array_checked()
  39977. * (regardless of whether an array part existed or not.
  39978. */
  39979. return;
  39980. }
  39981. /*
  39982. * Object.isSealed() and Object.isFrozen() (E5 Sections 15.2.3.11, 15.2.3.13)
  39983. *
  39984. * Since the algorithms are similar, a helper provides both functions.
  39985. * Freezing is essentially sealing + making plain properties non-writable.
  39986. *
  39987. * Note: all virtual (non-concrete) properties are currently non-configurable
  39988. * and non-writable (and there are no accessor virtual properties), so they don't
  39989. * need to be considered here now.
  39990. */
  39991. DUK_INTERNAL duk_bool_t duk_hobject_object_is_sealed_frozen_helper(duk_hthread *thr, duk_hobject *obj, duk_bool_t is_frozen) {
  39992. duk_uint_fast32_t i;
  39993. DUK_ASSERT(obj != NULL);
  39994. DUK_UNREF(thr);
  39995. /* Note: no allocation pressure, no need to check refcounts etc */
  39996. /* must not be extensible */
  39997. if (DUK_HOBJECT_HAS_EXTENSIBLE(obj)) {
  39998. return 0;
  39999. }
  40000. /* all virtual properties are non-configurable and non-writable */
  40001. /* entry part must not contain any configurable properties, or
  40002. * writable properties (if is_frozen).
  40003. */
  40004. for (i = 0; i < DUK_HOBJECT_GET_ENEXT(obj); i++) {
  40005. duk_small_uint_t flags;
  40006. if (!DUK_HOBJECT_E_GET_KEY(thr->heap, obj, i)) {
  40007. continue;
  40008. }
  40009. /* avoid multiple computations of flags address; bypasses macros */
  40010. flags = (duk_small_uint_t) DUK_HOBJECT_E_GET_FLAGS(thr->heap, obj, i);
  40011. if (flags & DUK_PROPDESC_FLAG_CONFIGURABLE) {
  40012. return 0;
  40013. }
  40014. if (is_frozen &&
  40015. !(flags & DUK_PROPDESC_FLAG_ACCESSOR) &&
  40016. (flags & DUK_PROPDESC_FLAG_WRITABLE)) {
  40017. return 0;
  40018. }
  40019. }
  40020. /* array part must not contain any non-unused properties, as they would
  40021. * be configurable and writable.
  40022. */
  40023. for (i = 0; i < DUK_HOBJECT_GET_ASIZE(obj); i++) {
  40024. duk_tval *tv = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, obj, i);
  40025. if (!DUK_TVAL_IS_UNDEFINED_UNUSED(tv)) {
  40026. return 0;
  40027. }
  40028. }
  40029. return 1;
  40030. }
  40031. /*
  40032. * Object.preventExtensions() and Object.isExtensible() (E5 Sections 15.2.3.10, 15.2.3.13)
  40033. *
  40034. * Not needed, implemented by macros DUK_HOBJECT_{HAS,CLEAR,SET}_EXTENSIBLE
  40035. * and the Object built-in bindings.
  40036. */
  40037. /* Undefine local defines */
  40038. #undef DUK__NO_ARRAY_INDEX
  40039. #undef DUK__HASH_INITIAL
  40040. #undef DUK__HASH_PROBE_STEP
  40041. #undef DUK__HASH_UNUSED
  40042. #undef DUK__HASH_DELETED
  40043. #undef DUK__VALSTACK_SPACE
  40044. #line 1 "duk_hstring_misc.c"
  40045. /*
  40046. * Misc support functions
  40047. */
  40048. /* include removed: duk_internal.h */
  40049. DUK_INTERNAL duk_ucodepoint_t duk_hstring_char_code_at_raw(duk_hthread *thr, duk_hstring *h, duk_uint_t pos) {
  40050. duk_uint32_t boff;
  40051. const duk_uint8_t *p, *p_start, *p_end;
  40052. duk_ucodepoint_t cp;
  40053. /* Caller must check character offset to be inside the string. */
  40054. DUK_ASSERT(thr != NULL);
  40055. DUK_ASSERT(h != NULL);
  40056. DUK_ASSERT_DISABLE(pos >= 0); /* unsigned */
  40057. DUK_ASSERT(pos < (duk_uint_t) DUK_HSTRING_GET_CHARLEN(h));
  40058. boff = duk_heap_strcache_offset_char2byte(thr, h, (duk_uint32_t) pos);
  40059. DUK_DDD(DUK_DDDPRINT("charCodeAt: pos=%ld -> boff=%ld, str=%!O",
  40060. (long) pos, (long) boff, (duk_heaphdr *) h));
  40061. DUK_ASSERT_DISABLE(boff >= 0);
  40062. DUK_ASSERT(boff < DUK_HSTRING_GET_BYTELEN(h));
  40063. p_start = DUK_HSTRING_GET_DATA(h);
  40064. p_end = p_start + DUK_HSTRING_GET_BYTELEN(h);
  40065. p = p_start + boff;
  40066. DUK_DDD(DUK_DDDPRINT("p_start=%p, p_end=%p, p=%p",
  40067. (void *) p_start, (void *) p_end, (void *) p));
  40068. /* This may throw an error though not for valid E5 strings. */
  40069. cp = duk_unicode_decode_xutf8_checked(thr, &p, p_start, p_end);
  40070. return cp;
  40071. }
  40072. #line 1 "duk_hthread_alloc.c"
  40073. /*
  40074. * duk_hthread allocation and freeing.
  40075. */
  40076. /* include removed: duk_internal.h */
  40077. /*
  40078. * Allocate initial stacks for a thread. Note that 'thr' must be reachable
  40079. * as a garbage collection may be triggered by the allocation attempts.
  40080. * Returns zero (without leaking memory) if init fails.
  40081. */
  40082. DUK_INTERNAL duk_bool_t duk_hthread_init_stacks(duk_heap *heap, duk_hthread *thr) {
  40083. duk_size_t alloc_size;
  40084. duk_size_t i;
  40085. DUK_ASSERT(heap != NULL);
  40086. DUK_ASSERT(thr != NULL);
  40087. DUK_ASSERT(thr->valstack == NULL);
  40088. DUK_ASSERT(thr->valstack_end == NULL);
  40089. DUK_ASSERT(thr->valstack_bottom == NULL);
  40090. DUK_ASSERT(thr->valstack_top == NULL);
  40091. DUK_ASSERT(thr->callstack == NULL);
  40092. DUK_ASSERT(thr->catchstack == NULL);
  40093. /* valstack */
  40094. alloc_size = sizeof(duk_tval) * DUK_VALSTACK_INITIAL_SIZE;
  40095. thr->valstack = (duk_tval *) DUK_ALLOC(heap, alloc_size);
  40096. if (!thr->valstack) {
  40097. goto fail;
  40098. }
  40099. DUK_MEMZERO(thr->valstack, alloc_size);
  40100. thr->valstack_end = thr->valstack + DUK_VALSTACK_INITIAL_SIZE;
  40101. thr->valstack_bottom = thr->valstack;
  40102. thr->valstack_top = thr->valstack;
  40103. for (i = 0; i < DUK_VALSTACK_INITIAL_SIZE; i++) {
  40104. DUK_TVAL_SET_UNDEFINED_UNUSED(&thr->valstack[i]);
  40105. }
  40106. /* callstack */
  40107. alloc_size = sizeof(duk_activation) * DUK_CALLSTACK_INITIAL_SIZE;
  40108. thr->callstack = (duk_activation *) DUK_ALLOC(heap, alloc_size);
  40109. if (!thr->callstack) {
  40110. goto fail;
  40111. }
  40112. DUK_MEMZERO(thr->callstack, alloc_size);
  40113. thr->callstack_size = DUK_CALLSTACK_INITIAL_SIZE;
  40114. DUK_ASSERT(thr->callstack_top == 0);
  40115. /* catchstack */
  40116. alloc_size = sizeof(duk_catcher) * DUK_CATCHSTACK_INITIAL_SIZE;
  40117. thr->catchstack = (duk_catcher *) DUK_ALLOC(heap, alloc_size);
  40118. if (!thr->catchstack) {
  40119. goto fail;
  40120. }
  40121. DUK_MEMZERO(thr->catchstack, alloc_size);
  40122. thr->catchstack_size = DUK_CATCHSTACK_INITIAL_SIZE;
  40123. DUK_ASSERT(thr->catchstack_top == 0);
  40124. return 1;
  40125. fail:
  40126. DUK_FREE(heap, thr->valstack);
  40127. DUK_FREE(heap, thr->callstack);
  40128. DUK_FREE(heap, thr->catchstack);
  40129. thr->valstack = NULL;
  40130. thr->callstack = NULL;
  40131. thr->catchstack = NULL;
  40132. return 0;
  40133. }
  40134. /* For indirect allocs. */
  40135. DUK_INTERNAL void *duk_hthread_get_valstack_ptr(duk_heap *heap, void *ud) {
  40136. duk_hthread *thr = (duk_hthread *) ud;
  40137. DUK_UNREF(heap);
  40138. return (void *) thr->valstack;
  40139. }
  40140. DUK_INTERNAL void *duk_hthread_get_callstack_ptr(duk_heap *heap, void *ud) {
  40141. duk_hthread *thr = (duk_hthread *) ud;
  40142. DUK_UNREF(heap);
  40143. return (void *) thr->callstack;
  40144. }
  40145. DUK_INTERNAL void *duk_hthread_get_catchstack_ptr(duk_heap *heap, void *ud) {
  40146. duk_hthread *thr = (duk_hthread *) ud;
  40147. DUK_UNREF(heap);
  40148. return (void *) thr->catchstack;
  40149. }
  40150. #line 1 "duk_hthread_builtins.c"
  40151. /*
  40152. * Initialize built-in objects. Current thread must have a valstack
  40153. * and initialization errors may longjmp, so a setjmp() catch point
  40154. * must exist.
  40155. */
  40156. /* include removed: duk_internal.h */
  40157. /*
  40158. * Encoding constants, must match genbuiltins.py
  40159. */
  40160. #define DUK__CLASS_BITS 5
  40161. #define DUK__BIDX_BITS 6
  40162. #define DUK__STRIDX_BITS 9 /* XXX: try to optimize to 8 */
  40163. #define DUK__NATIDX_BITS 8
  40164. #define DUK__NUM_NORMAL_PROPS_BITS 6
  40165. #define DUK__NUM_FUNC_PROPS_BITS 6
  40166. #define DUK__PROP_FLAGS_BITS 3
  40167. #define DUK__STRING_LENGTH_BITS 8
  40168. #define DUK__STRING_CHAR_BITS 7
  40169. #define DUK__LENGTH_PROP_BITS 3
  40170. #define DUK__NARGS_BITS 3
  40171. #define DUK__PROP_TYPE_BITS 3
  40172. #define DUK__MAGIC_BITS 16
  40173. #define DUK__NARGS_VARARGS_MARKER 0x07
  40174. #define DUK__NO_CLASS_MARKER 0x00 /* 0 = DUK_HOBJECT_CLASS_UNUSED */
  40175. #define DUK__NO_BIDX_MARKER 0x3f
  40176. #define DUK__NO_STRIDX_MARKER 0xff
  40177. #define DUK__PROP_TYPE_DOUBLE 0
  40178. #define DUK__PROP_TYPE_STRING 1
  40179. #define DUK__PROP_TYPE_STRIDX 2
  40180. #define DUK__PROP_TYPE_BUILTIN 3
  40181. #define DUK__PROP_TYPE_UNDEFINED 4
  40182. #define DUK__PROP_TYPE_BOOLEAN_TRUE 5
  40183. #define DUK__PROP_TYPE_BOOLEAN_FALSE 6
  40184. #define DUK__PROP_TYPE_ACCESSOR 7
  40185. /*
  40186. * Create built-in objects by parsing an init bitstream generated
  40187. * by genbuiltins.py.
  40188. */
  40189. DUK_INTERNAL void duk_hthread_create_builtin_objects(duk_hthread *thr) {
  40190. duk_context *ctx = (duk_context *) thr;
  40191. duk_bitdecoder_ctx bd_ctx;
  40192. duk_bitdecoder_ctx *bd = &bd_ctx; /* convenience */
  40193. duk_hobject *h;
  40194. duk_small_uint_t i, j;
  40195. DUK_D(DUK_DPRINT("INITBUILTINS BEGIN"));
  40196. DUK_MEMZERO(&bd_ctx, sizeof(bd_ctx));
  40197. bd->data = (const duk_uint8_t *) duk_builtins_data;
  40198. bd->length = (duk_size_t) DUK_BUILTINS_DATA_LENGTH;
  40199. /*
  40200. * First create all built-in bare objects on the empty valstack.
  40201. * During init, their indices will correspond to built-in indices.
  40202. *
  40203. * Built-ins will be reachable from both valstack and thr->builtins.
  40204. */
  40205. /* XXX: there is no need to resize valstack because builtin count
  40206. * is much less than the default space; assert for it.
  40207. */
  40208. DUK_DD(DUK_DDPRINT("create empty built-ins"));
  40209. DUK_ASSERT_TOP(ctx, 0);
  40210. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  40211. duk_small_uint_t class_num;
  40212. duk_small_int_t len = -1; /* must be signed */
  40213. class_num = (duk_small_uint_t) duk_bd_decode(bd, DUK__CLASS_BITS);
  40214. len = (duk_small_int_t) duk_bd_decode_flagged(bd, DUK__LENGTH_PROP_BITS, (duk_int32_t) -1 /*def_value*/);
  40215. if (class_num == DUK_HOBJECT_CLASS_FUNCTION) {
  40216. duk_small_uint_t natidx;
  40217. duk_small_uint_t stridx;
  40218. duk_int_t c_nargs; /* must hold DUK_VARARGS */
  40219. duk_c_function c_func;
  40220. duk_int16_t magic;
  40221. DUK_DDD(DUK_DDDPRINT("len=%ld", (long) len));
  40222. DUK_ASSERT(len >= 0);
  40223. natidx = (duk_small_uint_t) duk_bd_decode(bd, DUK__NATIDX_BITS);
  40224. stridx = (duk_small_uint_t) duk_bd_decode(bd, DUK__STRIDX_BITS);
  40225. c_func = duk_bi_native_functions[natidx];
  40226. c_nargs = (duk_small_uint_t) duk_bd_decode_flagged(bd, DUK__NARGS_BITS, len /*def_value*/);
  40227. if (c_nargs == DUK__NARGS_VARARGS_MARKER) {
  40228. c_nargs = DUK_VARARGS;
  40229. }
  40230. /* XXX: set magic directly here? (it could share the c_nargs arg) */
  40231. duk_push_c_function_noexotic(ctx, c_func, c_nargs);
  40232. h = duk_require_hobject(ctx, -1);
  40233. DUK_ASSERT(h != NULL);
  40234. /* Currently all built-in native functions are strict.
  40235. * duk_push_c_function() now sets strict flag, so
  40236. * assert for it.
  40237. */
  40238. DUK_ASSERT(DUK_HOBJECT_HAS_STRICT(h));
  40239. /* XXX: function properties */
  40240. duk_push_hstring_stridx(ctx, stridx);
  40241. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_NAME, DUK_PROPDESC_FLAGS_NONE);
  40242. /* Almost all global level Function objects are constructable
  40243. * but not all: Function.prototype is a non-constructable,
  40244. * callable Function.
  40245. */
  40246. if (duk_bd_decode_flag(bd)) {
  40247. DUK_ASSERT(DUK_HOBJECT_HAS_CONSTRUCTABLE(h));
  40248. } else {
  40249. DUK_HOBJECT_CLEAR_CONSTRUCTABLE(h);
  40250. }
  40251. /* Cast converts magic to 16-bit signed value */
  40252. magic = (duk_int16_t) duk_bd_decode_flagged(bd, DUK__MAGIC_BITS, 0 /*def_value*/);
  40253. ((duk_hnativefunction *) h)->magic = magic;
  40254. } else {
  40255. /* XXX: ARRAY_PART for Array prototype? */
  40256. duk_push_object_helper(ctx,
  40257. DUK_HOBJECT_FLAG_EXTENSIBLE,
  40258. -1); /* no prototype or class yet */
  40259. h = duk_require_hobject(ctx, -1);
  40260. DUK_ASSERT(h != NULL);
  40261. }
  40262. DUK_HOBJECT_SET_CLASS_NUMBER(h, class_num);
  40263. thr->builtins[i] = h;
  40264. DUK_HOBJECT_INCREF(thr, &h->hdr);
  40265. if (len >= 0) {
  40266. /*
  40267. * For top-level objects, 'length' property has the following
  40268. * default attributes: non-writable, non-enumerable, non-configurable
  40269. * (E5 Section 15).
  40270. *
  40271. * However, 'length' property for Array.prototype has attributes
  40272. * expected of an Array instance which are different: writable,
  40273. * non-enumerable, non-configurable (E5 Section 15.4.5.2).
  40274. *
  40275. * This is currently determined implicitly based on class; there are
  40276. * no attribute flags in the init data.
  40277. */
  40278. duk_push_int(ctx, len);
  40279. duk_xdef_prop_stridx(ctx,
  40280. -2,
  40281. DUK_STRIDX_LENGTH,
  40282. (class_num == DUK_HOBJECT_CLASS_ARRAY ? /* only Array.prototype matches */
  40283. DUK_PROPDESC_FLAGS_W : DUK_PROPDESC_FLAGS_NONE));
  40284. }
  40285. /* enable exotic behaviors last */
  40286. if (class_num == DUK_HOBJECT_CLASS_ARRAY) {
  40287. DUK_HOBJECT_SET_EXOTIC_ARRAY(h);
  40288. }
  40289. if (class_num == DUK_HOBJECT_CLASS_STRING) {
  40290. DUK_HOBJECT_SET_EXOTIC_STRINGOBJ(h);
  40291. }
  40292. /* some assertions */
  40293. DUK_ASSERT(DUK_HOBJECT_HAS_EXTENSIBLE(h));
  40294. /* DUK_HOBJECT_FLAG_CONSTRUCTABLE varies */
  40295. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(h));
  40296. DUK_ASSERT(!DUK_HOBJECT_HAS_COMPILEDFUNCTION(h));
  40297. /* DUK_HOBJECT_FLAG_NATIVEFUNCTION varies */
  40298. DUK_ASSERT(!DUK_HOBJECT_HAS_THREAD(h));
  40299. DUK_ASSERT(!DUK_HOBJECT_HAS_ARRAY_PART(h)); /* currently, even for Array.prototype */
  40300. /* DUK_HOBJECT_FLAG_STRICT varies */
  40301. DUK_ASSERT(!DUK_HOBJECT_HAS_NATIVEFUNCTION(h) || /* all native functions have NEWENV */
  40302. DUK_HOBJECT_HAS_NEWENV(h));
  40303. DUK_ASSERT(!DUK_HOBJECT_HAS_NAMEBINDING(h));
  40304. DUK_ASSERT(!DUK_HOBJECT_HAS_CREATEARGS(h));
  40305. DUK_ASSERT(!DUK_HOBJECT_HAS_ENVRECCLOSED(h));
  40306. /* DUK_HOBJECT_FLAG_EXOTIC_ARRAY varies */
  40307. /* DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ varies */
  40308. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(h));
  40309. DUK_DDD(DUK_DDDPRINT("created built-in %ld, class=%ld, length=%ld", (long) i, (long) class_num, (long) len));
  40310. }
  40311. /*
  40312. * Then decode the builtins init data (see genbuiltins.py) to
  40313. * init objects
  40314. */
  40315. DUK_DD(DUK_DDPRINT("initialize built-in object properties"));
  40316. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  40317. duk_small_uint_t t;
  40318. duk_small_uint_t num;
  40319. DUK_DDD(DUK_DDDPRINT("initializing built-in object at index %ld", (long) i));
  40320. h = thr->builtins[i];
  40321. t = (duk_small_uint_t) duk_bd_decode(bd, DUK__BIDX_BITS);
  40322. if (t != DUK__NO_BIDX_MARKER) {
  40323. DUK_DDD(DUK_DDDPRINT("set internal prototype: built-in %ld", (long) t));
  40324. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, h, thr->builtins[t]);
  40325. }
  40326. t = (duk_small_uint_t) duk_bd_decode(bd, DUK__BIDX_BITS);
  40327. if (t != DUK__NO_BIDX_MARKER) {
  40328. /* 'prototype' property for all built-in objects (which have it) has attributes:
  40329. * [[Writable]] = false,
  40330. * [[Enumerable]] = false,
  40331. * [[Configurable]] = false
  40332. */
  40333. DUK_DDD(DUK_DDDPRINT("set external prototype: built-in %ld", (long) t));
  40334. duk_xdef_prop_stridx_builtin(ctx, i, DUK_STRIDX_PROTOTYPE, t, DUK_PROPDESC_FLAGS_NONE);
  40335. }
  40336. t = (duk_small_uint_t) duk_bd_decode(bd, DUK__BIDX_BITS);
  40337. if (t != DUK__NO_BIDX_MARKER) {
  40338. /* 'constructor' property for all built-in objects (which have it) has attributes:
  40339. * [[Writable]] = true,
  40340. * [[Enumerable]] = false,
  40341. * [[Configurable]] = true
  40342. */
  40343. DUK_DDD(DUK_DDDPRINT("set external constructor: built-in %ld", (long) t));
  40344. duk_xdef_prop_stridx_builtin(ctx, i, DUK_STRIDX_CONSTRUCTOR, t, DUK_PROPDESC_FLAGS_WC);
  40345. }
  40346. /* normal valued properties */
  40347. num = (duk_small_uint_t) duk_bd_decode(bd, DUK__NUM_NORMAL_PROPS_BITS);
  40348. DUK_DDD(DUK_DDDPRINT("built-in object %ld, %ld normal valued properties", (long) i, (long) num));
  40349. for (j = 0; j < num; j++) {
  40350. duk_small_uint_t stridx;
  40351. duk_small_uint_t prop_flags;
  40352. stridx = (duk_small_uint_t) duk_bd_decode(bd, DUK__STRIDX_BITS);
  40353. /*
  40354. * Property attribute defaults are defined in E5 Section 15 (first
  40355. * few pages); there is a default for all properties and a special
  40356. * default for 'length' properties. Variation from the defaults is
  40357. * signaled using a single flag bit in the bitstream.
  40358. */
  40359. if (duk_bd_decode_flag(bd)) {
  40360. prop_flags = (duk_small_uint_t) duk_bd_decode(bd, DUK__PROP_FLAGS_BITS);
  40361. } else {
  40362. if (stridx == DUK_STRIDX_LENGTH) {
  40363. prop_flags = DUK_PROPDESC_FLAGS_NONE;
  40364. } else {
  40365. prop_flags = DUK_PROPDESC_FLAGS_WC;
  40366. }
  40367. }
  40368. t = (duk_small_uint_t) duk_bd_decode(bd, DUK__PROP_TYPE_BITS);
  40369. DUK_DDD(DUK_DDDPRINT("built-in %ld, normal-valued property %ld, stridx %ld, flags 0x%02lx, type %ld",
  40370. (long) i, (long) j, (long) stridx, (unsigned long) prop_flags, (long) t));
  40371. switch (t) {
  40372. case DUK__PROP_TYPE_DOUBLE: {
  40373. duk_double_union du;
  40374. duk_small_uint_t k;
  40375. for (k = 0; k < 8; k++) {
  40376. /* Encoding endianness must match target memory layout,
  40377. * build scripts and genbuiltins.py must ensure this.
  40378. */
  40379. du.uc[k] = (duk_uint8_t) duk_bd_decode(bd, 8);
  40380. }
  40381. duk_push_number(ctx, du.d); /* push operation normalizes NaNs */
  40382. break;
  40383. }
  40384. case DUK__PROP_TYPE_STRING: {
  40385. duk_small_uint_t n;
  40386. duk_small_uint_t k;
  40387. duk_uint8_t *p;
  40388. n = (duk_small_uint_t) duk_bd_decode(bd, DUK__STRING_LENGTH_BITS);
  40389. p = (duk_uint8_t *) duk_push_fixed_buffer(ctx, n);
  40390. for (k = 0; k < n; k++) {
  40391. *p++ = (duk_uint8_t) duk_bd_decode(bd, DUK__STRING_CHAR_BITS);
  40392. }
  40393. duk_to_string(ctx, -1);
  40394. break;
  40395. }
  40396. case DUK__PROP_TYPE_STRIDX: {
  40397. duk_small_uint_t n;
  40398. n = (duk_small_uint_t) duk_bd_decode(bd, DUK__STRIDX_BITS);
  40399. DUK_ASSERT_DISABLE(n >= 0); /* unsigned */
  40400. DUK_ASSERT(n < DUK_HEAP_NUM_STRINGS);
  40401. duk_push_hstring_stridx(ctx, n);
  40402. break;
  40403. }
  40404. case DUK__PROP_TYPE_BUILTIN: {
  40405. duk_small_uint_t bidx;
  40406. bidx = (duk_small_uint_t) duk_bd_decode(bd, DUK__BIDX_BITS);
  40407. DUK_ASSERT(bidx != DUK__NO_BIDX_MARKER);
  40408. duk_dup(ctx, (duk_idx_t) bidx);
  40409. break;
  40410. }
  40411. case DUK__PROP_TYPE_UNDEFINED: {
  40412. duk_push_undefined(ctx);
  40413. break;
  40414. }
  40415. case DUK__PROP_TYPE_BOOLEAN_TRUE: {
  40416. duk_push_true(ctx);
  40417. break;
  40418. }
  40419. case DUK__PROP_TYPE_BOOLEAN_FALSE: {
  40420. duk_push_false(ctx);
  40421. break;
  40422. }
  40423. case DUK__PROP_TYPE_ACCESSOR: {
  40424. duk_small_uint_t natidx_getter = (duk_small_uint_t) duk_bd_decode(bd, DUK__NATIDX_BITS);
  40425. duk_small_uint_t natidx_setter = (duk_small_uint_t) duk_bd_decode(bd, DUK__NATIDX_BITS);
  40426. duk_c_function c_func_getter;
  40427. duk_c_function c_func_setter;
  40428. /* XXX: this is a bit awkward because there is no exposed helper
  40429. * in the API style, only this internal helper.
  40430. */
  40431. DUK_DDD(DUK_DDDPRINT("built-in accessor property: objidx=%ld, stridx=%ld, getteridx=%ld, setteridx=%ld, flags=0x%04lx",
  40432. (long) i, (long) stridx, (long) natidx_getter, (long) natidx_setter, (unsigned long) prop_flags));
  40433. c_func_getter = duk_bi_native_functions[natidx_getter];
  40434. c_func_setter = duk_bi_native_functions[natidx_setter];
  40435. duk_push_c_function_noconstruct_noexotic(ctx, c_func_getter, 0); /* always 0 args */
  40436. duk_push_c_function_noconstruct_noexotic(ctx, c_func_setter, 1); /* always 1 arg */
  40437. /* XXX: magic for getter/setter? */
  40438. prop_flags |= DUK_PROPDESC_FLAG_ACCESSOR; /* accessor flag not encoded explicitly */
  40439. duk_hobject_define_accessor_internal(thr,
  40440. duk_require_hobject(ctx, i),
  40441. DUK_HTHREAD_GET_STRING(thr, stridx),
  40442. duk_require_hobject(ctx, -2),
  40443. duk_require_hobject(ctx, -1),
  40444. prop_flags);
  40445. duk_pop_2(ctx); /* getter and setter, now reachable through object */
  40446. goto skip_value;
  40447. }
  40448. default: {
  40449. /* exhaustive */
  40450. DUK_UNREACHABLE();
  40451. }
  40452. }
  40453. DUK_ASSERT((prop_flags & DUK_PROPDESC_FLAG_ACCESSOR) == 0);
  40454. duk_xdef_prop_stridx(ctx, i, stridx, prop_flags);
  40455. skip_value:
  40456. continue; /* avoid empty label at the end of a compound statement */
  40457. }
  40458. /* native function properties */
  40459. num = (duk_small_uint_t) duk_bd_decode(bd, DUK__NUM_FUNC_PROPS_BITS);
  40460. DUK_DDD(DUK_DDDPRINT("built-in object %ld, %ld function valued properties", (long) i, (long) num));
  40461. for (j = 0; j < num; j++) {
  40462. duk_small_uint_t stridx;
  40463. duk_small_uint_t natidx;
  40464. duk_int_t c_nargs; /* must hold DUK_VARARGS */
  40465. duk_small_uint_t c_length;
  40466. duk_int16_t magic;
  40467. duk_c_function c_func;
  40468. duk_hnativefunction *h_func;
  40469. #if defined(DUK_USE_LIGHTFUNC_BUILTINS)
  40470. duk_small_int_t lightfunc_eligible;
  40471. #endif
  40472. stridx = (duk_small_uint_t) duk_bd_decode(bd, DUK__STRIDX_BITS);
  40473. natidx = (duk_small_uint_t) duk_bd_decode(bd, DUK__NATIDX_BITS);
  40474. c_length = (duk_small_uint_t) duk_bd_decode(bd, DUK__LENGTH_PROP_BITS);
  40475. c_nargs = (duk_int_t) duk_bd_decode_flagged(bd, DUK__NARGS_BITS, (duk_int32_t) c_length /*def_value*/);
  40476. if (c_nargs == DUK__NARGS_VARARGS_MARKER) {
  40477. c_nargs = DUK_VARARGS;
  40478. }
  40479. c_func = duk_bi_native_functions[natidx];
  40480. DUK_DDD(DUK_DDDPRINT("built-in %ld, function-valued property %ld, stridx %ld, natidx %ld, length %ld, nargs %ld",
  40481. (long) i, (long) j, (long) stridx, (long) natidx, (long) c_length,
  40482. (c_nargs == DUK_VARARGS ? (long) -1 : (long) c_nargs)));
  40483. /* Cast converts magic to 16-bit signed value */
  40484. magic = (duk_int16_t) duk_bd_decode_flagged(bd, DUK__MAGIC_BITS, 0);
  40485. #if defined(DUK_USE_LIGHTFUNC_BUILTINS)
  40486. lightfunc_eligible =
  40487. ((c_nargs >= DUK_LFUNC_NARGS_MIN && c_nargs <= DUK_LFUNC_NARGS_MAX) || (c_nargs == DUK_VARARGS)) &&
  40488. (c_length <= DUK_LFUNC_LENGTH_MAX) &&
  40489. (magic >= DUK_LFUNC_MAGIC_MIN && magic <= DUK_LFUNC_MAGIC_MAX);
  40490. if (stridx == DUK_STRIDX_EVAL ||
  40491. stridx == DUK_STRIDX_YIELD ||
  40492. stridx == DUK_STRIDX_RESUME ||
  40493. stridx == DUK_STRIDX_REQUIRE) {
  40494. /* These functions have trouble working as lightfuncs.
  40495. * Some of them have specific asserts and some may have
  40496. * additional properties (e.g. 'require.id' may be written).
  40497. */
  40498. DUK_D(DUK_DPRINT("reject as lightfunc: stridx=%d, i=%d, j=%d", (int) stridx, (int) i, (int) j));
  40499. lightfunc_eligible = 0;
  40500. }
  40501. if (lightfunc_eligible) {
  40502. duk_tval tv_lfunc;
  40503. duk_small_uint_t lf_nargs = (c_nargs == DUK_VARARGS ? DUK_LFUNC_NARGS_VARARGS : c_nargs);
  40504. duk_small_uint_t lf_flags = DUK_LFUNC_FLAGS_PACK(magic, c_length, lf_nargs);
  40505. DUK_TVAL_SET_LIGHTFUNC(&tv_lfunc, c_func, lf_flags);
  40506. duk_push_tval(ctx, &tv_lfunc);
  40507. DUK_D(DUK_DPRINT("built-in function eligible as light function: i=%d, j=%d c_length=%ld, c_nargs=%ld, magic=%ld -> %!iT", (int) i, (int) j, (long) c_length, (long) c_nargs, (long) magic, duk_get_tval(ctx, -1)));
  40508. goto lightfunc_skip;
  40509. }
  40510. DUK_D(DUK_DPRINT("built-in function NOT ELIGIBLE as light function: i=%d, j=%d c_length=%ld, c_nargs=%ld, magic=%ld", (int) i, (int) j, (long) c_length, (long) c_nargs, (long) magic));
  40511. #endif /* DUK_USE_LIGHTFUNC_BUILTINS */
  40512. /* [ (builtin objects) ] */
  40513. duk_push_c_function_noconstruct_noexotic(ctx, c_func, c_nargs);
  40514. h_func = duk_require_hnativefunction(ctx, -1);
  40515. DUK_UNREF(h_func);
  40516. /* Currently all built-in native functions are strict.
  40517. * This doesn't matter for many functions, but e.g.
  40518. * String.prototype.charAt (and other string functions)
  40519. * rely on being strict so that their 'this' binding is
  40520. * not automatically coerced.
  40521. */
  40522. DUK_HOBJECT_SET_STRICT((duk_hobject *) h_func);
  40523. /* No built-in functions are constructable except the top
  40524. * level ones (Number, etc).
  40525. */
  40526. DUK_ASSERT(!DUK_HOBJECT_HAS_CONSTRUCTABLE((duk_hobject *) h_func));
  40527. /* XXX: any way to avoid decoding magic bit; there are quite
  40528. * many function properties and relatively few with magic values.
  40529. */
  40530. h_func->magic = magic;
  40531. /* [ (builtin objects) func ] */
  40532. duk_push_int(ctx, c_length);
  40533. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_NONE);
  40534. duk_push_hstring_stridx(ctx, stridx);
  40535. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_NAME, DUK_PROPDESC_FLAGS_NONE);
  40536. /* XXX: other properties of function instances; 'arguments', 'caller'. */
  40537. DUK_DD(DUK_DDPRINT("built-in object %ld, function property %ld -> %!T",
  40538. (long) i, (long) j, (duk_tval *) duk_get_tval(ctx, -1)));
  40539. /* [ (builtin objects) func ] */
  40540. /*
  40541. * The default property attributes are correct for all
  40542. * function valued properties of built-in objects now.
  40543. */
  40544. #if defined(DUK_USE_LIGHTFUNC_BUILTINS)
  40545. lightfunc_skip:
  40546. #endif
  40547. duk_xdef_prop_stridx(ctx, i, stridx, DUK_PROPDESC_FLAGS_WC);
  40548. /* [ (builtin objects) ] */
  40549. }
  40550. }
  40551. /*
  40552. * Special post-tweaks, for cases not covered by the init data format.
  40553. *
  40554. * - Set Date.prototype.toGMTString to Date.prototype.toUTCString.
  40555. * toGMTString is required to have the same Function object as
  40556. * toUTCString in E5 Section B.2.6. Note that while Smjs respects
  40557. * this, V8 does not (the Function objects are distinct).
  40558. *
  40559. * - Make DoubleError non-extensible.
  40560. *
  40561. * - Add info about most important effective compile options to Duktape.
  40562. *
  40563. * - Possibly remove some properties (values or methods) which are not
  40564. * desirable with current feature options but are not currently
  40565. * conditional in init data.
  40566. */
  40567. duk_get_prop_stridx(ctx, DUK_BIDX_DATE_PROTOTYPE, DUK_STRIDX_TO_UTC_STRING);
  40568. duk_xdef_prop_stridx(ctx, DUK_BIDX_DATE_PROTOTYPE, DUK_STRIDX_TO_GMT_STRING, DUK_PROPDESC_FLAGS_WC);
  40569. h = duk_require_hobject(ctx, DUK_BIDX_DOUBLE_ERROR);
  40570. DUK_ASSERT(h != NULL);
  40571. DUK_HOBJECT_CLEAR_EXTENSIBLE(h);
  40572. #if !defined(DUK_USE_ES6_OBJECT_PROTO_PROPERTY)
  40573. DUK_DD(DUK_DDPRINT("delete Object.prototype.__proto__ built-in which is not enabled in features"));
  40574. (void) duk_hobject_delprop_raw(thr, thr->builtins[DUK_BIDX_OBJECT_PROTOTYPE], DUK_HTHREAD_STRING___PROTO__(thr), DUK_DELPROP_FLAG_THROW);
  40575. #endif
  40576. #if !defined(DUK_USE_ES6_OBJECT_SETPROTOTYPEOF)
  40577. DUK_DD(DUK_DDPRINT("delete Object.setPrototypeOf built-in which is not enabled in features"));
  40578. (void) duk_hobject_delprop_raw(thr, thr->builtins[DUK_BIDX_OBJECT_CONSTRUCTOR], DUK_HTHREAD_STRING_SET_PROTOTYPE_OF(thr), DUK_DELPROP_FLAG_THROW);
  40579. #endif
  40580. duk_push_string(ctx,
  40581. /* Endianness indicator */
  40582. #if defined(DUK_USE_INTEGER_LE)
  40583. "l"
  40584. #elif defined(DUK_USE_INTEGER_BE)
  40585. "b"
  40586. #elif defined(DUK_USE_INTEGER_ME) /* integer mixed endian not really used now */
  40587. "m"
  40588. #else
  40589. "?"
  40590. #endif
  40591. #if defined(DUK_USE_DOUBLE_LE)
  40592. "l"
  40593. #elif defined(DUK_USE_DOUBLE_BE)
  40594. "b"
  40595. #elif defined(DUK_USE_DOUBLE_ME)
  40596. "m"
  40597. #else
  40598. "?"
  40599. #endif
  40600. #if defined(DUK_USE_BYTEORDER_FORCED)
  40601. "f"
  40602. #endif
  40603. " "
  40604. /* Packed or unpacked tval */
  40605. #if defined(DUK_USE_PACKED_TVAL)
  40606. "p"
  40607. #else
  40608. "u"
  40609. #endif
  40610. #if defined(DUK_USE_FASTINT)
  40611. "f"
  40612. #endif
  40613. " "
  40614. /* Low memory options */
  40615. #if defined(DUK_USE_STRTAB_CHAIN)
  40616. "c" /* chain */
  40617. #elif defined(DUK_USE_STRTAB_PROBE)
  40618. "p" /* probe */
  40619. #else
  40620. "?"
  40621. #endif
  40622. #if !defined(DUK_USE_HEAPPTR16) && !defined(DUK_DATAPTR16) && !defined(DUK_FUNCPTR16)
  40623. "n"
  40624. #endif
  40625. #if defined(DUK_USE_HEAPPTR16)
  40626. "h"
  40627. #endif
  40628. #if defined(DUK_USE_DATAPTR16)
  40629. "d"
  40630. #endif
  40631. #if defined(DUK_USE_FUNCPTR16)
  40632. "f"
  40633. #endif
  40634. #if defined(DUK_USE_REFCOUNT16)
  40635. "R"
  40636. #endif
  40637. #if defined(DUK_USE_STRHASH16)
  40638. "H"
  40639. #endif
  40640. #if defined(DUK_USE_STRLEN16)
  40641. "S"
  40642. #endif
  40643. #if defined(DUK_USE_BUFLEN16)
  40644. "B"
  40645. #endif
  40646. #if defined(DUK_USE_OBJSIZES16)
  40647. "O"
  40648. #endif
  40649. #if defined(DUK_USE_LIGHTFUNC_BUILTINS)
  40650. "L"
  40651. #endif
  40652. " "
  40653. /* Object property allocation layout */
  40654. #if defined(DUK_USE_HOBJECT_LAYOUT_1)
  40655. "p1"
  40656. #elif defined(DUK_USE_HOBJECT_LAYOUT_2)
  40657. "p2"
  40658. #elif defined(DUK_USE_HOBJECT_LAYOUT_3)
  40659. "p3"
  40660. #else
  40661. "p?"
  40662. #endif
  40663. " "
  40664. /* Alignment guarantee */
  40665. #if defined(DUK_USE_ALIGN_4)
  40666. "a4"
  40667. #elif defined(DUK_USE_ALIGN_8)
  40668. "a8"
  40669. #else
  40670. "a1"
  40671. #endif
  40672. " "
  40673. /* Architecture, OS, and compiler strings */
  40674. DUK_USE_ARCH_STRING
  40675. " "
  40676. DUK_USE_OS_STRING
  40677. " "
  40678. DUK_USE_COMPILER_STRING);
  40679. duk_xdef_prop_stridx(ctx, DUK_BIDX_DUKTAPE, DUK_STRIDX_ENV, DUK_PROPDESC_FLAGS_WC);
  40680. /*
  40681. * InitJS code - Ecmascript code evaluated from a built-in source
  40682. * which provides e.g. backward compatibility. User can also provide
  40683. * JS code to be evaluated at startup.
  40684. */
  40685. #ifdef DUK_USE_BUILTIN_INITJS
  40686. /* XXX: compression */
  40687. DUK_DD(DUK_DDPRINT("running built-in initjs"));
  40688. duk_eval_string(ctx, (const char *) duk_initjs_data); /* initjs data is NUL terminated */
  40689. duk_pop(ctx);
  40690. #endif /* DUK_USE_BUILTIN_INITJS */
  40691. #ifdef DUK_USE_USER_INITJS
  40692. /* XXX: compression (as an option) */
  40693. DUK_DD(DUK_DDPRINT("running user initjs"));
  40694. duk_eval_string_noresult(ctx, (const char *) DUK_USE_USER_INITJS);
  40695. #endif /* DUK_USE_USER_INITJS */
  40696. /*
  40697. * Since built-ins are not often extended, compact them.
  40698. */
  40699. DUK_DD(DUK_DDPRINT("compact built-ins"));
  40700. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  40701. duk_hobject_compact_props(thr, thr->builtins[i]);
  40702. }
  40703. DUK_D(DUK_DPRINT("INITBUILTINS END"));
  40704. #ifdef DUK_USE_DDPRINT
  40705. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  40706. DUK_DD(DUK_DDPRINT("built-in object %ld after initialization and compacting: %!@iO",
  40707. (long) i, (duk_heaphdr *) thr->builtins[i]));
  40708. }
  40709. #endif
  40710. /*
  40711. * Pop built-ins from stack: they are now INCREF'd and
  40712. * reachable from the builtins[] array.
  40713. */
  40714. duk_pop_n(ctx, DUK_NUM_BUILTINS);
  40715. DUK_ASSERT_TOP(ctx, 0);
  40716. }
  40717. DUK_INTERNAL void duk_hthread_copy_builtin_objects(duk_hthread *thr_from, duk_hthread *thr_to) {
  40718. duk_small_uint_t i;
  40719. for (i = 0; i < DUK_NUM_BUILTINS; i++) {
  40720. thr_to->builtins[i] = thr_from->builtins[i];
  40721. DUK_HOBJECT_INCREF_ALLOWNULL(thr_to, thr_to->builtins[i]); /* side effect free */
  40722. }
  40723. }
  40724. #line 1 "duk_hthread_misc.c"
  40725. /*
  40726. * Thread support.
  40727. */
  40728. /* include removed: duk_internal.h */
  40729. DUK_INTERNAL void duk_hthread_terminate(duk_hthread *thr) {
  40730. DUK_ASSERT(thr != NULL);
  40731. /* Order of unwinding is important */
  40732. duk_hthread_catchstack_unwind(thr, 0);
  40733. duk_hthread_callstack_unwind(thr, 0); /* side effects, possibly errors */
  40734. thr->valstack_bottom = thr->valstack;
  40735. duk_set_top((duk_context *) thr, 0); /* unwinds valstack, updating refcounts */
  40736. thr->state = DUK_HTHREAD_STATE_TERMINATED;
  40737. /* Here we could remove references to built-ins, but it may not be
  40738. * worth the effort because built-ins are quite likely to be shared
  40739. * with another (unterminated) thread, and terminated threads are also
  40740. * usually garbage collected quite quickly. Also, doing DECREFs
  40741. * could trigger finalization, which would run on the current thread
  40742. * and have access to only some of the built-ins. Garbage collection
  40743. * deals with this correctly already.
  40744. */
  40745. /* XXX: Shrink the stacks to minimize memory usage? May not
  40746. * be worth the effort because terminated threads are usually
  40747. * garbage collected quite soon.
  40748. */
  40749. }
  40750. DUK_INTERNAL duk_activation *duk_hthread_get_current_activation(duk_hthread *thr) {
  40751. DUK_ASSERT(thr != NULL);
  40752. if (thr->callstack_top > 0) {
  40753. return thr->callstack + thr->callstack_top - 1;
  40754. } else {
  40755. return NULL;
  40756. }
  40757. }
  40758. #line 1 "duk_hthread_stacks.c"
  40759. /*
  40760. * Manipulation of thread stacks (valstack, callstack, catchstack).
  40761. *
  40762. * Ideally unwinding of stacks should have no side effects, which would
  40763. * then favor separate unwinding and shrink check primitives for each
  40764. * stack type. A shrink check may realloc and thus have side effects.
  40765. *
  40766. * However, currently callstack unwinding itself has side effects, as it
  40767. * needs to DECREF multiple objects, close environment records, etc.
  40768. * Stacks must thus be unwound in the correct order by the caller.
  40769. *
  40770. * (XXX: This should be probably reworked so that there is a shared
  40771. * unwind primitive which handles all stacks as requested, and knows
  40772. * the proper order for unwinding.)
  40773. *
  40774. * Valstack entries above 'top' are always kept initialized to
  40775. * "undefined unused". Callstack and catchstack entries above 'top'
  40776. * are not zeroed and are left as garbage.
  40777. *
  40778. * Value stack handling is mostly a part of the API implementation.
  40779. */
  40780. /* include removed: duk_internal.h */
  40781. /* check that there is space for at least one new entry */
  40782. DUK_INTERNAL void duk_hthread_callstack_grow(duk_hthread *thr) {
  40783. duk_activation *new_ptr;
  40784. duk_size_t old_size;
  40785. duk_size_t new_size;
  40786. DUK_ASSERT(thr != NULL);
  40787. DUK_ASSERT_DISABLE(thr->callstack_top >= 0); /* avoid warning (unsigned) */
  40788. DUK_ASSERT(thr->callstack_size >= thr->callstack_top);
  40789. if (thr->callstack_top < thr->callstack_size) {
  40790. return;
  40791. }
  40792. old_size = thr->callstack_size;
  40793. new_size = old_size + DUK_CALLSTACK_GROW_STEP;
  40794. /* this is a bit approximate (errors out before max is reached); this is OK */
  40795. if (new_size >= thr->callstack_max) {
  40796. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_CALLSTACK_LIMIT);
  40797. }
  40798. DUK_DD(DUK_DDPRINT("growing callstack %ld -> %ld", (long) old_size, (long) new_size));
  40799. /*
  40800. * Note: must use indirect variant of DUK_REALLOC() because underlying
  40801. * pointer may be changed by mark-and-sweep.
  40802. */
  40803. DUK_ASSERT(new_size > 0);
  40804. new_ptr = (duk_activation *) DUK_REALLOC_INDIRECT(thr->heap, duk_hthread_get_callstack_ptr, (void *) thr, sizeof(duk_activation) * new_size);
  40805. if (!new_ptr) {
  40806. /* No need for a NULL/zero-size check because new_size > 0) */
  40807. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_REALLOC_FAILED);
  40808. }
  40809. thr->callstack = new_ptr;
  40810. thr->callstack_size = new_size;
  40811. /* note: any entries above the callstack top are garbage and not zeroed */
  40812. }
  40813. DUK_INTERNAL void duk_hthread_callstack_shrink_check(duk_hthread *thr) {
  40814. duk_size_t new_size;
  40815. duk_activation *p;
  40816. DUK_ASSERT(thr != NULL);
  40817. DUK_ASSERT_DISABLE(thr->callstack_top >= 0); /* avoid warning (unsigned) */
  40818. DUK_ASSERT(thr->callstack_size >= thr->callstack_top);
  40819. if (thr->callstack_size - thr->callstack_top < DUK_CALLSTACK_SHRINK_THRESHOLD) {
  40820. return;
  40821. }
  40822. new_size = thr->callstack_top + DUK_CALLSTACK_SHRINK_SPARE;
  40823. DUK_ASSERT(new_size >= thr->callstack_top);
  40824. DUK_DD(DUK_DDPRINT("shrinking callstack %ld -> %ld", (long) thr->callstack_size, (long) new_size));
  40825. /*
  40826. * Note: must use indirect variant of DUK_REALLOC() because underlying
  40827. * pointer may be changed by mark-and-sweep.
  40828. */
  40829. /* shrink failure is not fatal */
  40830. p = (duk_activation *) DUK_REALLOC_INDIRECT(thr->heap, duk_hthread_get_callstack_ptr, (void *) thr, sizeof(duk_activation) * new_size);
  40831. if (p) {
  40832. thr->callstack = p;
  40833. thr->callstack_size = new_size;
  40834. } else {
  40835. /* Because new_size != 0, if condition doesn't need to be
  40836. * (p != NULL || new_size == 0).
  40837. */
  40838. DUK_ASSERT(new_size != 0);
  40839. DUK_D(DUK_DPRINT("callstack shrink failed, ignoring"));
  40840. }
  40841. /* note: any entries above the callstack top are garbage and not zeroed */
  40842. }
  40843. DUK_INTERNAL void duk_hthread_callstack_unwind(duk_hthread *thr, duk_size_t new_top) {
  40844. duk_size_t idx;
  40845. DUK_DDD(DUK_DDDPRINT("unwind callstack top of thread %p from %ld to %ld",
  40846. (void *) thr,
  40847. (thr != NULL ? (long) thr->callstack_top : (long) -1),
  40848. (long) new_top));
  40849. DUK_ASSERT(thr);
  40850. DUK_ASSERT(thr->heap);
  40851. DUK_ASSERT_DISABLE(new_top >= 0); /* unsigned */
  40852. DUK_ASSERT((duk_size_t) new_top <= thr->callstack_top); /* cannot grow */
  40853. /*
  40854. * The loop below must avoid issues with potential callstack
  40855. * reallocations. A resize (and other side effects) may happen
  40856. * e.g. due to finalizer/errhandler calls caused by a refzero or
  40857. * mark-and-sweep. Arbitrary finalizers may run, because when
  40858. * an environment record is refzero'd, it may refer to arbitrary
  40859. * values which also become refzero'd.
  40860. *
  40861. * So, the pointer 'p' is re-looked-up below whenever a side effect
  40862. * might have changed it.
  40863. */
  40864. idx = thr->callstack_top;
  40865. while (idx > new_top) {
  40866. duk_activation *act;
  40867. duk_hobject *func;
  40868. #ifdef DUK_USE_REFERENCE_COUNTING
  40869. duk_hobject *tmp;
  40870. #endif
  40871. #ifdef DUK_USE_DEBUGGER_SUPPORT
  40872. duk_heap *heap;
  40873. #endif
  40874. idx--;
  40875. DUK_ASSERT_DISABLE(idx >= 0); /* unsigned */
  40876. DUK_ASSERT((duk_size_t) idx < thr->callstack_size); /* true, despite side effect resizes */
  40877. act = thr->callstack + idx;
  40878. /* With lightfuncs, act 'func' may be NULL */
  40879. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  40880. /*
  40881. * Restore 'caller' property for non-strict callee functions.
  40882. */
  40883. func = DUK_ACT_GET_FUNC(act);
  40884. if (func != NULL && !DUK_HOBJECT_HAS_STRICT(func)) {
  40885. duk_tval *tv_caller;
  40886. duk_tval tv_tmp;
  40887. duk_hobject *h_tmp;
  40888. tv_caller = duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_CALLER(thr));
  40889. /* The act->prev_caller should only be set if the entry for 'caller'
  40890. * exists (as it is only set in that case, and the property is not
  40891. * configurable), but handle all the cases anyway.
  40892. */
  40893. if (tv_caller) {
  40894. DUK_TVAL_SET_TVAL(&tv_tmp, tv_caller);
  40895. if (act->prev_caller) {
  40896. /* Just transfer the refcount from act->prev_caller to tv_caller,
  40897. * so no need for a refcount update. This is the expected case.
  40898. */
  40899. DUK_TVAL_SET_OBJECT(tv_caller, act->prev_caller);
  40900. act->prev_caller = NULL;
  40901. } else {
  40902. DUK_TVAL_SET_NULL(tv_caller); /* no incref needed */
  40903. DUK_ASSERT(act->prev_caller == NULL);
  40904. }
  40905. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  40906. } else {
  40907. h_tmp = act->prev_caller;
  40908. if (h_tmp) {
  40909. act->prev_caller = NULL;
  40910. DUK_HOBJECT_DECREF(thr, h_tmp); /* side effects */
  40911. }
  40912. }
  40913. act = thr->callstack + idx; /* avoid side effects */
  40914. DUK_ASSERT(act->prev_caller == NULL);
  40915. }
  40916. #endif
  40917. /*
  40918. * Unwind debugger state. If we unwind while stepping
  40919. * (either step over or step into), pause execution.
  40920. */
  40921. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  40922. heap = thr->heap;
  40923. if (heap->dbg_step_thread == thr &&
  40924. heap->dbg_step_csindex == idx) {
  40925. /* Pause for all step types: step into, step over, step out.
  40926. * This is the only place explicitly handling a step out.
  40927. */
  40928. DUK_HEAP_SET_PAUSED(heap);
  40929. DUK_ASSERT(heap->dbg_step_thread == NULL);
  40930. }
  40931. #endif
  40932. /*
  40933. * Close environment record(s) if they exist.
  40934. *
  40935. * Only variable environments are closed. If lex_env != var_env, it
  40936. * cannot currently contain any register bound declarations.
  40937. *
  40938. * Only environments created for a NEWENV function are closed. If an
  40939. * environment is created for e.g. an eval call, it must not be closed.
  40940. */
  40941. func = DUK_ACT_GET_FUNC(act);
  40942. if (func != NULL && !DUK_HOBJECT_HAS_NEWENV(func)) {
  40943. DUK_DDD(DUK_DDDPRINT("skip closing environments, envs not owned by this activation"));
  40944. goto skip_env_close;
  40945. }
  40946. /* func is NULL for lightfunc */
  40947. DUK_ASSERT(act->lex_env == act->var_env);
  40948. if (act->var_env != NULL) {
  40949. DUK_DDD(DUK_DDDPRINT("closing var_env record %p -> %!O",
  40950. (void *) act->var_env, (duk_heaphdr *) act->var_env));
  40951. duk_js_close_environment_record(thr, act->var_env, func, act->idx_bottom);
  40952. act = thr->callstack + idx; /* avoid side effect issues */
  40953. }
  40954. #if 0
  40955. if (act->lex_env != NULL) {
  40956. if (act->lex_env == act->var_env) {
  40957. /* common case, already closed, so skip */
  40958. DUK_DD(DUK_DDPRINT("lex_env and var_env are the same and lex_env "
  40959. "already closed -> skip closing lex_env"));
  40960. ;
  40961. } else {
  40962. DUK_DD(DUK_DDPRINT("closing lex_env record %p -> %!O",
  40963. (void *) act->lex_env, (duk_heaphdr *) act->lex_env));
  40964. duk_js_close_environment_record(thr, act->lex_env, DUK_ACT_GET_FUNC(act), act->idx_bottom);
  40965. act = thr->callstack + idx; /* avoid side effect issues */
  40966. }
  40967. }
  40968. #endif
  40969. DUK_ASSERT((act->lex_env == NULL) ||
  40970. ((duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->lex_env, DUK_HTHREAD_STRING_INT_CALLEE(thr)) == NULL) &&
  40971. (duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->lex_env, DUK_HTHREAD_STRING_INT_VARMAP(thr)) == NULL) &&
  40972. (duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->lex_env, DUK_HTHREAD_STRING_INT_THREAD(thr)) == NULL) &&
  40973. (duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->lex_env, DUK_HTHREAD_STRING_INT_REGBASE(thr)) == NULL)));
  40974. DUK_ASSERT((act->var_env == NULL) ||
  40975. ((duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->var_env, DUK_HTHREAD_STRING_INT_CALLEE(thr)) == NULL) &&
  40976. (duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->var_env, DUK_HTHREAD_STRING_INT_VARMAP(thr)) == NULL) &&
  40977. (duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->var_env, DUK_HTHREAD_STRING_INT_THREAD(thr)) == NULL) &&
  40978. (duk_hobject_find_existing_entry_tval_ptr(thr->heap, act->var_env, DUK_HTHREAD_STRING_INT_REGBASE(thr)) == NULL)));
  40979. skip_env_close:
  40980. /*
  40981. * Update preventcount
  40982. */
  40983. if (act->flags & DUK_ACT_FLAG_PREVENT_YIELD) {
  40984. DUK_ASSERT(thr->callstack_preventcount >= 1);
  40985. thr->callstack_preventcount--;
  40986. }
  40987. /*
  40988. * Reference count updates
  40989. *
  40990. * Note: careful manipulation of refcounts. The top is
  40991. * not updated yet, so all the activations are reachable
  40992. * for mark-and-sweep (which may be triggered by decref).
  40993. * However, the pointers are NULL so this is not an issue.
  40994. */
  40995. #ifdef DUK_USE_REFERENCE_COUNTING
  40996. tmp = act->var_env;
  40997. #endif
  40998. act->var_env = NULL;
  40999. #ifdef DUK_USE_REFERENCE_COUNTING
  41000. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  41001. act = thr->callstack + idx; /* avoid side effect issues */
  41002. #endif
  41003. #ifdef DUK_USE_REFERENCE_COUNTING
  41004. tmp = act->lex_env;
  41005. #endif
  41006. act->lex_env = NULL;
  41007. #ifdef DUK_USE_REFERENCE_COUNTING
  41008. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  41009. act = thr->callstack + idx; /* avoid side effect issues */
  41010. #endif
  41011. /* Note: this may cause a corner case situation where a finalizer
  41012. * may see a currently reachable activation whose 'func' is NULL.
  41013. */
  41014. #ifdef DUK_USE_REFERENCE_COUNTING
  41015. tmp = DUK_ACT_GET_FUNC(act);
  41016. #endif
  41017. act->func = NULL;
  41018. #ifdef DUK_USE_REFERENCE_COUNTING
  41019. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  41020. act = thr->callstack + idx; /* avoid side effect issues */
  41021. DUK_UNREF(act);
  41022. #endif
  41023. }
  41024. thr->callstack_top = new_top;
  41025. /*
  41026. * We could clear the book-keeping variables for the topmost activation,
  41027. * but don't do so now.
  41028. */
  41029. #if 0
  41030. if (thr->callstack_top > 0) {
  41031. duk_activation *act = thr->callstack + thr->callstack_top - 1;
  41032. act->idx_retval = 0;
  41033. }
  41034. #endif
  41035. /* Note: any entries above the callstack top are garbage and not zeroed.
  41036. * Also topmost activation idx_retval is garbage (not zeroed), and must
  41037. * be ignored.
  41038. */
  41039. }
  41040. DUK_INTERNAL void duk_hthread_catchstack_grow(duk_hthread *thr) {
  41041. duk_catcher *new_ptr;
  41042. duk_size_t old_size;
  41043. duk_size_t new_size;
  41044. DUK_ASSERT(thr != NULL);
  41045. DUK_ASSERT_DISABLE(thr->catchstack_top); /* avoid warning (unsigned) */
  41046. DUK_ASSERT(thr->catchstack_size >= thr->catchstack_top);
  41047. if (thr->catchstack_top < thr->catchstack_size) {
  41048. return;
  41049. }
  41050. old_size = thr->catchstack_size;
  41051. new_size = old_size + DUK_CATCHSTACK_GROW_STEP;
  41052. /* this is a bit approximate (errors out before max is reached); this is OK */
  41053. if (new_size >= thr->catchstack_max) {
  41054. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_CATCHSTACK_LIMIT);
  41055. }
  41056. DUK_DD(DUK_DDPRINT("growing catchstack %ld -> %ld", (long) old_size, (long) new_size));
  41057. /*
  41058. * Note: must use indirect variant of DUK_REALLOC() because underlying
  41059. * pointer may be changed by mark-and-sweep.
  41060. */
  41061. DUK_ASSERT(new_size > 0);
  41062. new_ptr = (duk_catcher *) DUK_REALLOC_INDIRECT(thr->heap, duk_hthread_get_catchstack_ptr, (void *) thr, sizeof(duk_catcher) * new_size);
  41063. if (!new_ptr) {
  41064. /* No need for a NULL/zero-size check because new_size > 0) */
  41065. DUK_ERROR(thr, DUK_ERR_ALLOC_ERROR, DUK_STR_REALLOC_FAILED);
  41066. }
  41067. thr->catchstack = new_ptr;
  41068. thr->catchstack_size = new_size;
  41069. /* note: any entries above the catchstack top are garbage and not zeroed */
  41070. }
  41071. DUK_INTERNAL void duk_hthread_catchstack_shrink_check(duk_hthread *thr) {
  41072. duk_size_t new_size;
  41073. duk_catcher *p;
  41074. DUK_ASSERT(thr != NULL);
  41075. DUK_ASSERT_DISABLE(thr->catchstack_top >= 0); /* avoid warning (unsigned) */
  41076. DUK_ASSERT(thr->catchstack_size >= thr->catchstack_top);
  41077. if (thr->catchstack_size - thr->catchstack_top < DUK_CATCHSTACK_SHRINK_THRESHOLD) {
  41078. return;
  41079. }
  41080. new_size = thr->catchstack_top + DUK_CATCHSTACK_SHRINK_SPARE;
  41081. DUK_ASSERT(new_size >= thr->catchstack_top);
  41082. DUK_DD(DUK_DDPRINT("shrinking catchstack %ld -> %ld", (long) thr->catchstack_size, (long) new_size));
  41083. /*
  41084. * Note: must use indirect variant of DUK_REALLOC() because underlying
  41085. * pointer may be changed by mark-and-sweep.
  41086. */
  41087. /* shrink failure is not fatal */
  41088. p = (duk_catcher *) DUK_REALLOC_INDIRECT(thr->heap, duk_hthread_get_catchstack_ptr, (void *) thr, sizeof(duk_catcher) * new_size);
  41089. if (p) {
  41090. thr->catchstack = p;
  41091. thr->catchstack_size = new_size;
  41092. } else {
  41093. /* Because new_size != 0, if condition doesn't need to be
  41094. * (p != NULL || new_size == 0).
  41095. */
  41096. DUK_ASSERT(new_size != 0);
  41097. DUK_D(DUK_DPRINT("catchstack shrink failed, ignoring"));
  41098. }
  41099. /* note: any entries above the catchstack top are garbage and not zeroed */
  41100. }
  41101. DUK_INTERNAL void duk_hthread_catchstack_unwind(duk_hthread *thr, duk_size_t new_top) {
  41102. duk_size_t idx;
  41103. DUK_DDD(DUK_DDDPRINT("unwind catchstack top of thread %p from %ld to %ld",
  41104. (void *) thr,
  41105. (thr != NULL ? (long) thr->catchstack_top : (long) -1),
  41106. (long) new_top));
  41107. DUK_ASSERT(thr);
  41108. DUK_ASSERT(thr->heap);
  41109. DUK_ASSERT_DISABLE(new_top >= 0); /* unsigned */
  41110. DUK_ASSERT((duk_size_t) new_top <= thr->catchstack_top); /* cannot grow */
  41111. /*
  41112. * Since there are no references in the catcher structure,
  41113. * unwinding is quite simple. The only thing we need to
  41114. * look out for is popping a possible lexical environment
  41115. * established for an active catch clause.
  41116. */
  41117. idx = thr->catchstack_top;
  41118. while (idx > new_top) {
  41119. duk_catcher *p;
  41120. duk_activation *act;
  41121. duk_hobject *env;
  41122. idx--;
  41123. DUK_ASSERT_DISABLE(idx >= 0); /* unsigned */
  41124. DUK_ASSERT((duk_size_t) idx < thr->catchstack_size);
  41125. p = thr->catchstack + idx;
  41126. if (DUK_CAT_HAS_LEXENV_ACTIVE(p)) {
  41127. DUK_DDD(DUK_DDDPRINT("unwinding catchstack idx %ld, callstack idx %ld, callstack top %ld: lexical environment active",
  41128. (long) idx, (long) p->callstack_index, (long) thr->callstack_top));
  41129. /* XXX: Here we have a nasty dependency: the need to manipulate
  41130. * the callstack means that catchstack must always be unwound by
  41131. * the caller before unwinding the callstack. This should be fixed
  41132. * later.
  41133. */
  41134. /* Note that multiple catchstack entries may refer to the same
  41135. * callstack entry.
  41136. */
  41137. act = thr->callstack + p->callstack_index;
  41138. DUK_ASSERT(act >= thr->callstack);
  41139. DUK_ASSERT(act < thr->callstack + thr->callstack_top);
  41140. DUK_DDD(DUK_DDDPRINT("catchstack_index=%ld, callstack_index=%ld, lex_env=%!iO",
  41141. (long) idx, (long) p->callstack_index,
  41142. (duk_heaphdr *) act->lex_env));
  41143. env = act->lex_env; /* current lex_env of the activation (created for catcher) */
  41144. DUK_ASSERT(env != NULL); /* must be, since env was created when catcher was created */
  41145. act->lex_env = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, env); /* prototype is lex_env before catcher created */
  41146. DUK_HOBJECT_DECREF(thr, env);
  41147. /* There is no need to decref anything else than 'env': if 'env'
  41148. * becomes unreachable, refzero will handle decref'ing its prototype.
  41149. */
  41150. }
  41151. }
  41152. thr->catchstack_top = new_top;
  41153. /* note: any entries above the catchstack top are garbage and not zeroed */
  41154. }
  41155. #line 1 "duk_js_call.c"
  41156. /*
  41157. * Call handling.
  41158. *
  41159. * The main work horse functions are:
  41160. * - duk_handle_call(): call to a C/Ecmascript functions
  41161. * - duk_handle_safe_call(): make a protected C call within current activation
  41162. * - duk_handle_ecma_call_setup(): Ecmascript-to-Ecmascript calls, including
  41163. * tail calls and coroutine resume
  41164. */
  41165. /* include removed: duk_internal.h */
  41166. /*
  41167. * Arguments object creation.
  41168. *
  41169. * Creating arguments objects is a bit finicky, see E5 Section 10.6 for the
  41170. * specific requirements. Much of the arguments object exotic behavior is
  41171. * implemented in duk_hobject_props.c, and is enabled by the object flag
  41172. * DUK_HOBJECT_FLAG_EXOTIC_ARGUMENTS.
  41173. */
  41174. DUK_LOCAL
  41175. void duk__create_arguments_object(duk_hthread *thr,
  41176. duk_hobject *func,
  41177. duk_hobject *varenv,
  41178. duk_idx_t idx_argbase, /* idx of first argument on stack */
  41179. duk_idx_t num_stack_args) { /* num args starting from idx_argbase */
  41180. duk_context *ctx = (duk_context *) thr;
  41181. duk_hobject *arg; /* 'arguments' */
  41182. duk_hobject *formals; /* formals for 'func' (may be NULL if func is a C function) */
  41183. duk_idx_t i_arg;
  41184. duk_idx_t i_map;
  41185. duk_idx_t i_mappednames;
  41186. duk_idx_t i_formals;
  41187. duk_idx_t i_argbase;
  41188. duk_idx_t n_formals;
  41189. duk_idx_t idx;
  41190. duk_bool_t need_map;
  41191. DUK_DDD(DUK_DDDPRINT("creating arguments object for func=%!iO, varenv=%!iO, "
  41192. "idx_argbase=%ld, num_stack_args=%ld",
  41193. (duk_heaphdr *) func, (duk_heaphdr *) varenv,
  41194. (long) idx_argbase, (long) num_stack_args));
  41195. DUK_ASSERT(thr != NULL);
  41196. DUK_ASSERT(func != NULL);
  41197. DUK_ASSERT(DUK_HOBJECT_IS_NONBOUND_FUNCTION(func));
  41198. DUK_ASSERT(varenv != NULL);
  41199. DUK_ASSERT(idx_argbase >= 0); /* assumed to bottom relative */
  41200. DUK_ASSERT(num_stack_args >= 0);
  41201. need_map = 0;
  41202. i_argbase = idx_argbase;
  41203. DUK_ASSERT(i_argbase >= 0);
  41204. duk_push_hobject(ctx, func);
  41205. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_FORMALS);
  41206. formals = duk_get_hobject(ctx, -1);
  41207. n_formals = 0;
  41208. if (formals) {
  41209. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_LENGTH);
  41210. n_formals = (duk_idx_t) duk_require_int(ctx, -1);
  41211. duk_pop(ctx);
  41212. }
  41213. duk_remove(ctx, -2); /* leave formals on stack for later use */
  41214. i_formals = duk_require_top_index(ctx);
  41215. DUK_ASSERT(n_formals >= 0);
  41216. DUK_ASSERT(formals != NULL || n_formals == 0);
  41217. DUK_DDD(DUK_DDDPRINT("func=%!O, formals=%!O, n_formals=%ld",
  41218. (duk_heaphdr *) func, (duk_heaphdr *) formals,
  41219. (long) n_formals));
  41220. /* [ ... formals ] */
  41221. /*
  41222. * Create required objects:
  41223. * - 'arguments' object: array-like, but not an array
  41224. * - 'map' object: internal object, tied to 'arguments'
  41225. * - 'mappedNames' object: temporary value used during construction
  41226. */
  41227. i_arg = duk_push_object_helper(ctx,
  41228. DUK_HOBJECT_FLAG_EXTENSIBLE |
  41229. DUK_HOBJECT_FLAG_ARRAY_PART |
  41230. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_ARGUMENTS),
  41231. DUK_BIDX_OBJECT_PROTOTYPE);
  41232. DUK_ASSERT(i_arg >= 0);
  41233. arg = duk_require_hobject(ctx, -1);
  41234. DUK_ASSERT(arg != NULL);
  41235. i_map = duk_push_object_helper(ctx,
  41236. DUK_HOBJECT_FLAG_EXTENSIBLE |
  41237. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT),
  41238. -1); /* no prototype */
  41239. DUK_ASSERT(i_map >= 0);
  41240. i_mappednames = duk_push_object_helper(ctx,
  41241. DUK_HOBJECT_FLAG_EXTENSIBLE |
  41242. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT),
  41243. -1); /* no prototype */
  41244. DUK_ASSERT(i_mappednames >= 0);
  41245. /* [... formals arguments map mappedNames] */
  41246. DUK_DDD(DUK_DDDPRINT("created arguments related objects: "
  41247. "arguments at index %ld -> %!O "
  41248. "map at index %ld -> %!O "
  41249. "mappednames at index %ld -> %!O",
  41250. (long) i_arg, (duk_heaphdr *) duk_get_hobject(ctx, i_arg),
  41251. (long) i_map, (duk_heaphdr *) duk_get_hobject(ctx, i_map),
  41252. (long) i_mappednames, (duk_heaphdr *) duk_get_hobject(ctx, i_mappednames)));
  41253. /*
  41254. * Init arguments properties, map, etc.
  41255. */
  41256. duk_push_int(ctx, num_stack_args);
  41257. duk_xdef_prop_stridx(ctx, i_arg, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_WC);
  41258. /*
  41259. * Init argument related properties
  41260. */
  41261. /* step 11 */
  41262. idx = num_stack_args - 1;
  41263. while (idx >= 0) {
  41264. DUK_DDD(DUK_DDDPRINT("arg idx %ld, argbase=%ld, argidx=%ld",
  41265. (long) idx, (long) i_argbase, (long) (i_argbase + idx)));
  41266. DUK_DDD(DUK_DDDPRINT("define arguments[%ld]=arg", (long) idx));
  41267. duk_dup(ctx, i_argbase + idx);
  41268. duk_xdef_prop_index_wec(ctx, i_arg, (duk_uarridx_t) idx);
  41269. DUK_DDD(DUK_DDDPRINT("defined arguments[%ld]=arg", (long) idx));
  41270. /* step 11.c is relevant only if non-strict (checked in 11.c.ii) */
  41271. if (!DUK_HOBJECT_HAS_STRICT(func) && idx < n_formals) {
  41272. DUK_ASSERT(formals != NULL);
  41273. DUK_DDD(DUK_DDDPRINT("strict function, index within formals (%ld < %ld)",
  41274. (long) idx, (long) n_formals));
  41275. duk_get_prop_index(ctx, i_formals, idx);
  41276. DUK_ASSERT(duk_is_string(ctx, -1));
  41277. duk_dup(ctx, -1); /* [... name name] */
  41278. if (!duk_has_prop(ctx, i_mappednames)) {
  41279. /* steps 11.c.ii.1 - 11.c.ii.4, but our internal book-keeping
  41280. * differs from the reference model
  41281. */
  41282. /* [... name] */
  41283. need_map = 1;
  41284. DUK_DDD(DUK_DDDPRINT("set mappednames[%s]=%ld",
  41285. (const char *) duk_get_string(ctx, -1),
  41286. (long) idx));
  41287. duk_dup(ctx, -1); /* name */
  41288. duk_push_uint(ctx, (duk_uint_t) idx); /* index */
  41289. duk_to_string(ctx, -1);
  41290. duk_xdef_prop_wec(ctx, i_mappednames); /* out of spec, must be configurable */
  41291. DUK_DDD(DUK_DDDPRINT("set map[%ld]=%s",
  41292. (long) idx,
  41293. duk_get_string(ctx, -1)));
  41294. duk_dup(ctx, -1); /* name */
  41295. duk_xdef_prop_index_wec(ctx, i_map, (duk_uarridx_t) idx); /* out of spec, must be configurable */
  41296. } else {
  41297. /* duk_has_prop() popped the second 'name' */
  41298. }
  41299. /* [... name] */
  41300. duk_pop(ctx); /* pop 'name' */
  41301. }
  41302. idx--;
  41303. }
  41304. DUK_DDD(DUK_DDDPRINT("actual arguments processed"));
  41305. /* step 12 */
  41306. if (need_map) {
  41307. DUK_DDD(DUK_DDDPRINT("adding 'map' and 'varenv' to arguments object"));
  41308. /* should never happen for a strict callee */
  41309. DUK_ASSERT(!DUK_HOBJECT_HAS_STRICT(func));
  41310. duk_dup(ctx, i_map);
  41311. duk_xdef_prop_stridx(ctx, i_arg, DUK_STRIDX_INT_MAP, DUK_PROPDESC_FLAGS_NONE); /* out of spec, don't care */
  41312. /* The variable environment for magic variable bindings needs to be
  41313. * given by the caller and recorded in the arguments object.
  41314. *
  41315. * See E5 Section 10.6, the creation of setters/getters.
  41316. *
  41317. * The variable environment also provides access to the callee, so
  41318. * an explicit (internal) callee property is not needed.
  41319. */
  41320. duk_push_hobject(ctx, varenv);
  41321. duk_xdef_prop_stridx(ctx, i_arg, DUK_STRIDX_INT_VARENV, DUK_PROPDESC_FLAGS_NONE); /* out of spec, don't care */
  41322. }
  41323. /* steps 13-14 */
  41324. if (DUK_HOBJECT_HAS_STRICT(func)) {
  41325. /*
  41326. * Note: callee/caller are throwers and are not deletable etc.
  41327. * They could be implemented as virtual properties, but currently
  41328. * there is no support for virtual properties which are accessors
  41329. * (only plain virtual properties). This would not be difficult
  41330. * to change in duk_hobject_props, but we can make the throwers
  41331. * normal, concrete properties just as easily.
  41332. *
  41333. * Note that the specification requires that the *same* thrower
  41334. * built-in object is used here! See E5 Section 10.6 main
  41335. * algoritm, step 14, and Section 13.2.3 which describes the
  41336. * thrower. See test case test-arguments-throwers.js.
  41337. */
  41338. DUK_DDD(DUK_DDDPRINT("strict function, setting caller/callee to throwers"));
  41339. duk_xdef_prop_stridx_thrower(ctx, i_arg, DUK_STRIDX_CALLER, DUK_PROPDESC_FLAGS_NONE);
  41340. duk_xdef_prop_stridx_thrower(ctx, i_arg, DUK_STRIDX_CALLEE, DUK_PROPDESC_FLAGS_NONE);
  41341. } else {
  41342. DUK_DDD(DUK_DDDPRINT("non-strict function, setting callee to actual value"));
  41343. duk_push_hobject(ctx, func);
  41344. duk_xdef_prop_stridx(ctx, i_arg, DUK_STRIDX_CALLEE, DUK_PROPDESC_FLAGS_WC);
  41345. }
  41346. /* set exotic behavior only after we're done */
  41347. if (need_map) {
  41348. /*
  41349. * Note: exotic behaviors are only enabled for arguments
  41350. * objects which have a parameter map (see E5 Section 10.6
  41351. * main algorithm, step 12).
  41352. *
  41353. * In particular, a non-strict arguments object with no
  41354. * mapped formals does *NOT* get exotic behavior, even
  41355. * for e.g. "caller" property. This seems counterintuitive
  41356. * but seems to be the case.
  41357. */
  41358. /* cannot be strict (never mapped variables) */
  41359. DUK_ASSERT(!DUK_HOBJECT_HAS_STRICT(func));
  41360. DUK_DDD(DUK_DDDPRINT("enabling exotic behavior for arguments object"));
  41361. DUK_HOBJECT_SET_EXOTIC_ARGUMENTS(arg);
  41362. } else {
  41363. DUK_DDD(DUK_DDDPRINT("not enabling exotic behavior for arguments object"));
  41364. }
  41365. /* nice log */
  41366. DUK_DDD(DUK_DDDPRINT("final arguments related objects: "
  41367. "arguments at index %ld -> %!O "
  41368. "map at index %ld -> %!O "
  41369. "mappednames at index %ld -> %!O",
  41370. (long) i_arg, (duk_heaphdr *) duk_get_hobject(ctx, i_arg),
  41371. (long) i_map, (duk_heaphdr *) duk_get_hobject(ctx, i_map),
  41372. (long) i_mappednames, (duk_heaphdr *) duk_get_hobject(ctx, i_mappednames)));
  41373. /* [args(n) [crud] formals arguments map mappednames] -> [args [crud] arguments] */
  41374. duk_pop_2(ctx);
  41375. duk_remove(ctx, -2);
  41376. }
  41377. /* Helper for creating the arguments object and adding it to the env record
  41378. * on top of the value stack. This helper has a very strict dependency on
  41379. * the shape of the input stack.
  41380. */
  41381. DUK_LOCAL
  41382. void duk__handle_createargs_for_call(duk_hthread *thr,
  41383. duk_hobject *func,
  41384. duk_hobject *env,
  41385. duk_idx_t num_stack_args) {
  41386. duk_context *ctx = (duk_context *) thr;
  41387. DUK_DDD(DUK_DDDPRINT("creating arguments object for function call"));
  41388. DUK_ASSERT(thr != NULL);
  41389. DUK_ASSERT(func != NULL);
  41390. DUK_ASSERT(env != NULL);
  41391. DUK_ASSERT(DUK_HOBJECT_HAS_CREATEARGS(func));
  41392. DUK_ASSERT(duk_get_top(ctx) >= num_stack_args + 1);
  41393. /* [... arg1 ... argN envobj] */
  41394. duk__create_arguments_object(thr,
  41395. func,
  41396. env,
  41397. duk_get_top(ctx) - num_stack_args - 1, /* idx_argbase */
  41398. num_stack_args);
  41399. /* [... arg1 ... argN envobj argobj] */
  41400. duk_xdef_prop_stridx(ctx,
  41401. -2,
  41402. DUK_STRIDX_LC_ARGUMENTS,
  41403. DUK_HOBJECT_HAS_STRICT(func) ? DUK_PROPDESC_FLAGS_E : /* strict: non-deletable, non-writable */
  41404. DUK_PROPDESC_FLAGS_WE); /* non-strict: non-deletable, writable */
  41405. /* [... arg1 ... argN envobj] */
  41406. }
  41407. /*
  41408. * Helper for handling a "bound function" chain when a call is being made.
  41409. *
  41410. * Follows the bound function chain until a non-bound function is found.
  41411. * Prepends the bound arguments to the value stack (at idx_func + 2),
  41412. * updating 'num_stack_args' in the process. The 'this' binding is also
  41413. * updated if necessary (at idx_func + 1). Note that for constructor calls
  41414. * the 'this' binding is never updated by [[BoundThis]].
  41415. *
  41416. * XXX: bound function chains could be collapsed at bound function creation
  41417. * time so that each bound function would point directly to a non-bound
  41418. * function. This would make call time handling much easier.
  41419. */
  41420. DUK_LOCAL
  41421. void duk__handle_bound_chain_for_call(duk_hthread *thr,
  41422. duk_idx_t idx_func,
  41423. duk_idx_t *p_num_stack_args, /* may be changed by call */
  41424. duk_bool_t is_constructor_call) {
  41425. duk_context *ctx = (duk_context *) thr;
  41426. duk_idx_t num_stack_args;
  41427. duk_tval *tv_func;
  41428. duk_hobject *func;
  41429. duk_uint_t sanity;
  41430. DUK_ASSERT(thr != NULL);
  41431. DUK_ASSERT(p_num_stack_args != NULL);
  41432. /* On entry, item at idx_func is a bound, non-lightweight function,
  41433. * but we don't rely on that below.
  41434. */
  41435. num_stack_args = *p_num_stack_args;
  41436. sanity = DUK_HOBJECT_BOUND_CHAIN_SANITY;
  41437. do {
  41438. duk_idx_t i, len;
  41439. tv_func = duk_require_tval(ctx, idx_func);
  41440. DUK_ASSERT(tv_func != NULL);
  41441. if (DUK_TVAL_IS_LIGHTFUNC(tv_func)) {
  41442. /* Lightweight function: never bound, so terminate. */
  41443. break;
  41444. } else if (DUK_TVAL_IS_OBJECT(tv_func)) {
  41445. func = DUK_TVAL_GET_OBJECT(tv_func);
  41446. if (!DUK_HOBJECT_HAS_BOUND(func)) {
  41447. /* Normal non-bound function. */
  41448. break;
  41449. }
  41450. } else {
  41451. /* Function.prototype.bind() should never let this happen,
  41452. * ugly error message is enough.
  41453. */
  41454. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR);
  41455. }
  41456. DUK_ASSERT(DUK_TVAL_GET_OBJECT(tv_func) != NULL);
  41457. /* XXX: this could be more compact by accessing the internal properties
  41458. * directly as own properties (they cannot be inherited, and are not
  41459. * externally visible).
  41460. */
  41461. DUK_DDD(DUK_DDDPRINT("bound function encountered, ptr=%p, num_stack_args=%ld: %!T",
  41462. (void *) DUK_TVAL_GET_OBJECT(tv_func), (long) num_stack_args, tv_func));
  41463. /* [ ... func this arg1 ... argN ] */
  41464. if (is_constructor_call) {
  41465. /* See: ecmascript-testcases/test-spec-bound-constructor.js */
  41466. DUK_DDD(DUK_DDDPRINT("constructor call: don't update this binding"));
  41467. } else {
  41468. duk_get_prop_stridx(ctx, idx_func, DUK_STRIDX_INT_THIS);
  41469. duk_replace(ctx, idx_func + 1); /* idx_this = idx_func + 1 */
  41470. }
  41471. /* [ ... func this arg1 ... argN ] */
  41472. /* XXX: duk_get_length? */
  41473. duk_get_prop_stridx(ctx, idx_func, DUK_STRIDX_INT_ARGS); /* -> [ ... func this arg1 ... argN _Args ] */
  41474. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_LENGTH); /* -> [ ... func this arg1 ... argN _Args length ] */
  41475. len = (duk_idx_t) duk_require_int(ctx, -1);
  41476. duk_pop(ctx);
  41477. for (i = 0; i < len; i++) {
  41478. /* XXX: very slow - better to bulk allocate a gap, and copy
  41479. * from args_array directly (we know it has a compact array
  41480. * part, etc).
  41481. */
  41482. /* [ ... func this <some bound args> arg1 ... argN _Args ] */
  41483. duk_get_prop_index(ctx, -1, i);
  41484. duk_insert(ctx, idx_func + 2 + i); /* idx_args = idx_func + 2 */
  41485. }
  41486. num_stack_args += len; /* must be updated to work properly (e.g. creation of 'arguments') */
  41487. duk_pop(ctx);
  41488. /* [ ... func this <bound args> arg1 ... argN ] */
  41489. duk_get_prop_stridx(ctx, idx_func, DUK_STRIDX_INT_TARGET);
  41490. duk_replace(ctx, idx_func); /* replace in stack */
  41491. DUK_DDD(DUK_DDDPRINT("bound function handled, num_stack_args=%ld, idx_func=%ld, curr func=%!T",
  41492. (long) num_stack_args, (long) idx_func, duk_get_tval(ctx, idx_func)));
  41493. } while (--sanity > 0);
  41494. if (sanity == 0) {
  41495. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_BOUND_CHAIN_LIMIT);
  41496. }
  41497. DUK_DDD(DUK_DDDPRINT("final non-bound function is: %!T", duk_get_tval(ctx, idx_func)));
  41498. #ifdef DUK_USE_ASSERTIONS
  41499. tv_func = duk_require_tval(ctx, idx_func);
  41500. DUK_ASSERT(DUK_TVAL_IS_LIGHTFUNC(tv_func) || DUK_TVAL_IS_OBJECT(tv_func));
  41501. if (DUK_TVAL_IS_OBJECT(tv_func)) {
  41502. func = DUK_TVAL_GET_OBJECT(tv_func);
  41503. DUK_ASSERT(func != NULL);
  41504. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func));
  41505. DUK_ASSERT(DUK_HOBJECT_HAS_COMPILEDFUNCTION(func) ||
  41506. DUK_HOBJECT_HAS_NATIVEFUNCTION(func));
  41507. }
  41508. #endif
  41509. /* write back */
  41510. *p_num_stack_args = num_stack_args;
  41511. }
  41512. /*
  41513. * Helper for setting up var_env and lex_env of an activation,
  41514. * assuming it does NOT have the DUK_HOBJECT_FLAG_NEWENV flag.
  41515. */
  41516. DUK_LOCAL
  41517. void duk__handle_oldenv_for_call(duk_hthread *thr,
  41518. duk_hobject *func,
  41519. duk_activation *act) {
  41520. duk_tval *tv;
  41521. DUK_ASSERT(thr != NULL);
  41522. DUK_ASSERT(func != NULL);
  41523. DUK_ASSERT(act != NULL);
  41524. DUK_ASSERT(!DUK_HOBJECT_HAS_NEWENV(func));
  41525. DUK_ASSERT(!DUK_HOBJECT_HAS_CREATEARGS(func));
  41526. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_INT_LEXENV(thr));
  41527. if (tv) {
  41528. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  41529. DUK_ASSERT(DUK_HOBJECT_IS_ENV(DUK_TVAL_GET_OBJECT(tv)));
  41530. act->lex_env = DUK_TVAL_GET_OBJECT(tv);
  41531. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_INT_VARENV(thr));
  41532. if (tv) {
  41533. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  41534. DUK_ASSERT(DUK_HOBJECT_IS_ENV(DUK_TVAL_GET_OBJECT(tv)));
  41535. act->var_env = DUK_TVAL_GET_OBJECT(tv);
  41536. } else {
  41537. act->var_env = act->lex_env;
  41538. }
  41539. } else {
  41540. act->lex_env = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  41541. act->var_env = act->lex_env;
  41542. }
  41543. DUK_HOBJECT_INCREF_ALLOWNULL(thr, act->lex_env);
  41544. DUK_HOBJECT_INCREF_ALLOWNULL(thr, act->var_env);
  41545. }
  41546. /*
  41547. * Helper for updating callee 'caller' property.
  41548. */
  41549. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  41550. DUK_LOCAL void duk__update_func_caller_prop(duk_hthread *thr, duk_hobject *func) {
  41551. duk_tval *tv_caller;
  41552. duk_hobject *h_tmp;
  41553. duk_activation *act_callee;
  41554. duk_activation *act_caller;
  41555. DUK_ASSERT(thr != NULL);
  41556. DUK_ASSERT(func != NULL);
  41557. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func)); /* bound chain resolved */
  41558. DUK_ASSERT(thr->callstack_top >= 1);
  41559. if (DUK_HOBJECT_HAS_STRICT(func)) {
  41560. /* Strict functions don't get their 'caller' updated. */
  41561. return;
  41562. }
  41563. act_callee = thr->callstack + thr->callstack_top - 1;
  41564. act_caller = (thr->callstack_top >= 2 ? act_callee - 1 : NULL);
  41565. /* Backup 'caller' property and update its value. */
  41566. tv_caller = duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_CALLER(thr));
  41567. if (tv_caller) {
  41568. /* If caller is global/eval code, 'caller' should be set to
  41569. * 'null'.
  41570. *
  41571. * XXX: there is no exotic flag to infer this correctly now.
  41572. * The NEWENV flag is used now which works as intended for
  41573. * everything (global code, non-strict eval code, and functions)
  41574. * except strict eval code. Bound functions are never an issue
  41575. * because 'func' has been resolved to a non-bound function.
  41576. */
  41577. if (act_caller) {
  41578. /* act_caller->func may be NULL in some finalization cases,
  41579. * just treat like we don't know the caller.
  41580. */
  41581. if (act_caller->func && !DUK_HOBJECT_HAS_NEWENV(act_caller->func)) {
  41582. /* Setting to NULL causes 'caller' to be set to
  41583. * 'null' as desired.
  41584. */
  41585. act_caller = NULL;
  41586. }
  41587. }
  41588. if (DUK_TVAL_IS_OBJECT(tv_caller)) {
  41589. h_tmp = DUK_TVAL_GET_OBJECT(tv_caller);
  41590. DUK_ASSERT(h_tmp != NULL);
  41591. act_callee->prev_caller = h_tmp;
  41592. /* Previous value doesn't need refcount changes because its ownership
  41593. * is transferred to prev_caller.
  41594. */
  41595. if (act_caller) {
  41596. DUK_ASSERT(act_caller->func != NULL);
  41597. DUK_TVAL_SET_OBJECT(tv_caller, act_caller->func);
  41598. DUK_TVAL_INCREF(thr, tv_caller);
  41599. } else {
  41600. DUK_TVAL_SET_NULL(tv_caller); /* no incref */
  41601. }
  41602. } else {
  41603. /* 'caller' must only take on 'null' or function value */
  41604. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_caller));
  41605. DUK_ASSERT(act_callee->prev_caller == NULL);
  41606. if (act_caller && act_caller->func) {
  41607. /* Tolerate act_caller->func == NULL which happens in
  41608. * some finalization cases; treat like unknown caller.
  41609. */
  41610. DUK_TVAL_SET_OBJECT(tv_caller, act_caller->func);
  41611. DUK_TVAL_INCREF(thr, tv_caller);
  41612. } else {
  41613. DUK_TVAL_SET_NULL(tv_caller); /* no incref */
  41614. }
  41615. }
  41616. }
  41617. }
  41618. #endif /* DUK_USE_NONSTD_FUNC_CALLER_PROPERTY */
  41619. /*
  41620. * Determine the effective 'this' binding and coerce the current value
  41621. * on the valstack to the effective one (in-place, at idx_this).
  41622. *
  41623. * The current this value in the valstack (at idx_this) represents either:
  41624. * - the caller's requested 'this' binding; or
  41625. * - a 'this' binding accumulated from the bound function chain
  41626. *
  41627. * The final 'this' binding for the target function may still be
  41628. * different, and is determined as described in E5 Section 10.4.3.
  41629. *
  41630. * For global and eval code (E5 Sections 10.4.1 and 10.4.2), we assume
  41631. * that the caller has provided the correct 'this' binding explicitly
  41632. * when calling, i.e.:
  41633. *
  41634. * - global code: this=global object
  41635. * - direct eval: this=copy from eval() caller's this binding
  41636. * - other eval: this=global object
  41637. *
  41638. * Note: this function may cause a recursive function call with arbitrary
  41639. * side effects, because ToObject() may be called.
  41640. */
  41641. DUK_LOCAL
  41642. void duk__coerce_effective_this_binding(duk_hthread *thr,
  41643. duk_hobject *func,
  41644. duk_idx_t idx_this) {
  41645. duk_context *ctx = (duk_context *) thr;
  41646. duk_small_int_t strict;
  41647. if (func) {
  41648. strict = DUK_HOBJECT_HAS_STRICT(func);
  41649. } else {
  41650. /* Lightfuncs are always considered strict. */
  41651. strict = 1;
  41652. }
  41653. if (strict) {
  41654. DUK_DDD(DUK_DDDPRINT("this binding: strict -> use directly"));
  41655. } else {
  41656. duk_tval *tv_this = duk_require_tval(ctx, idx_this);
  41657. duk_hobject *obj_global;
  41658. if (DUK_TVAL_IS_OBJECT(tv_this)) {
  41659. DUK_DDD(DUK_DDDPRINT("this binding: non-strict, object -> use directly"));
  41660. } else if (DUK_TVAL_IS_LIGHTFUNC(tv_this)) {
  41661. /* Lightfuncs are treated like objects and not coerced. */
  41662. DUK_DDD(DUK_DDDPRINT("this binding: non-strict, lightfunc -> use directly"));
  41663. } else if (DUK_TVAL_IS_UNDEFINED(tv_this) || DUK_TVAL_IS_NULL(tv_this)) {
  41664. DUK_DDD(DUK_DDDPRINT("this binding: non-strict, undefined/null -> use global object"));
  41665. obj_global = thr->builtins[DUK_BIDX_GLOBAL];
  41666. if (obj_global) {
  41667. duk_push_hobject(ctx, obj_global);
  41668. } else {
  41669. /*
  41670. * This may only happen if built-ins are being "torn down".
  41671. * This behavior is out of specification scope.
  41672. */
  41673. DUK_D(DUK_DPRINT("this binding: wanted to use global object, but it is NULL -> using undefined instead"));
  41674. duk_push_undefined(ctx);
  41675. }
  41676. duk_replace(ctx, idx_this);
  41677. } else {
  41678. DUK_DDD(DUK_DDDPRINT("this binding: non-strict, not object/undefined/null -> use ToObject(value)"));
  41679. duk_to_object(ctx, idx_this); /* may have side effects */
  41680. }
  41681. }
  41682. }
  41683. /*
  41684. * Shared helper for non-bound func lookup.
  41685. *
  41686. * Returns duk_hobject * to the final non-bound function (NULL for lightfunc).
  41687. */
  41688. DUK_LOCAL
  41689. duk_hobject *duk__nonbound_func_lookup(duk_context *ctx,
  41690. duk_idx_t idx_func,
  41691. duk_idx_t *out_num_stack_args,
  41692. duk_tval **out_tv_func,
  41693. duk_small_uint_t call_flags) {
  41694. duk_hthread *thr = (duk_hthread *) ctx;
  41695. duk_tval *tv_func;
  41696. duk_hobject *func;
  41697. for (;;) {
  41698. /* Use loop to minimize code size of relookup after bound function case */
  41699. tv_func = duk_get_tval(ctx, idx_func);
  41700. DUK_ASSERT(tv_func != NULL);
  41701. if (DUK_TVAL_IS_OBJECT(tv_func)) {
  41702. func = DUK_TVAL_GET_OBJECT(tv_func);
  41703. if (!DUK_HOBJECT_IS_CALLABLE(func)) {
  41704. goto not_callable_error;
  41705. }
  41706. if (DUK_HOBJECT_HAS_BOUND(func)) {
  41707. duk__handle_bound_chain_for_call(thr, idx_func, out_num_stack_args, call_flags & DUK_CALL_FLAG_CONSTRUCTOR_CALL);
  41708. /* The final object may be a normal function or a lightfunc.
  41709. * We need to re-lookup tv_func because it may have changed
  41710. * (also value stack may have been resized). Loop again to
  41711. * do that; we're guaranteed not to come here again.
  41712. */
  41713. DUK_ASSERT(DUK_TVAL_IS_OBJECT(duk_require_tval(ctx, idx_func)) ||
  41714. DUK_TVAL_IS_LIGHTFUNC(duk_require_tval(ctx, idx_func)));
  41715. continue;
  41716. }
  41717. } else if (DUK_TVAL_IS_LIGHTFUNC(tv_func)) {
  41718. func = NULL;
  41719. } else {
  41720. goto not_callable_error;
  41721. }
  41722. break;
  41723. }
  41724. DUK_ASSERT((DUK_TVAL_IS_OBJECT(tv_func) && DUK_HOBJECT_IS_CALLABLE(DUK_TVAL_GET_OBJECT(tv_func))) ||
  41725. DUK_TVAL_IS_LIGHTFUNC(tv_func));
  41726. DUK_ASSERT(func == NULL || !DUK_HOBJECT_HAS_BOUND(func));
  41727. DUK_ASSERT(func == NULL || (DUK_HOBJECT_IS_COMPILEDFUNCTION(func) ||
  41728. DUK_HOBJECT_IS_NATIVEFUNCTION(func)));
  41729. *out_tv_func = tv_func;
  41730. return func;
  41731. not_callable_error:
  41732. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_CALLABLE);
  41733. DUK_UNREACHABLE();
  41734. return NULL; /* never executed */
  41735. }
  41736. /*
  41737. * Value stack resize and stack top adjustment helper
  41738. *
  41739. * XXX: This should all be merged to duk_valstack_resize_raw().
  41740. */
  41741. DUK_LOCAL
  41742. void duk__adjust_valstack_and_top(duk_hthread *thr, duk_idx_t num_stack_args, duk_idx_t idx_args, duk_idx_t nregs, duk_idx_t nargs, duk_hobject *func) {
  41743. duk_context *ctx = (duk_context *) thr;
  41744. duk_size_t vs_min_size;
  41745. duk_bool_t adjusted_top = 0;
  41746. vs_min_size = (thr->valstack_bottom - thr->valstack) + /* bottom of current func */
  41747. idx_args; /* bottom of new func */
  41748. if (nregs >= 0) {
  41749. DUK_ASSERT(nargs >= 0);
  41750. DUK_ASSERT(nregs >= nargs);
  41751. vs_min_size += nregs;
  41752. } else {
  41753. /* 'func' wants stack "as is" */
  41754. vs_min_size += num_stack_args; /* num entries of new func at entry */
  41755. }
  41756. if (func == NULL || DUK_HOBJECT_IS_NATIVEFUNCTION(func)) {
  41757. vs_min_size += DUK_VALSTACK_API_ENTRY_MINIMUM; /* Duktape/C API guaranteed entries (on top of args) */
  41758. }
  41759. vs_min_size += DUK_VALSTACK_INTERNAL_EXTRA; /* + spare */
  41760. /* XXX: Awkward fix for GH-107: we can't resize the value stack to
  41761. * a size smaller than the current top, so the order of the resize
  41762. * and adjusting the stack top depends on the current vs. final size
  41763. * of the value stack. Ideally duk_valstack_resize_raw() would have
  41764. * a combined algorithm to avoid this.
  41765. */
  41766. if (vs_min_size < (duk_size_t) (thr->valstack_top - thr->valstack)) {
  41767. DUK_DDD(DUK_DDDPRINT(("final size smaller, set top before resize")));
  41768. DUK_ASSERT(nregs >= 0); /* can't happen when keeping current stack size */
  41769. duk_set_top(ctx, idx_args + nargs); /* clamp anything above nargs */
  41770. duk_set_top(ctx, idx_args + nregs); /* extend with undefined */
  41771. adjusted_top = 1;
  41772. }
  41773. (void) duk_valstack_resize_raw((duk_context *) thr,
  41774. vs_min_size,
  41775. DUK_VSRESIZE_FLAG_SHRINK | /* flags */
  41776. 0 /* no compact */ |
  41777. DUK_VSRESIZE_FLAG_THROW);
  41778. if (!adjusted_top) {
  41779. if (nregs >= 0) {
  41780. DUK_ASSERT(nregs >= nargs);
  41781. duk_set_top(ctx, idx_args + nargs); /* clamp anything above nargs */
  41782. duk_set_top(ctx, idx_args + nregs); /* extend with undefined */
  41783. }
  41784. }
  41785. }
  41786. /*
  41787. * Helper for making various kinds of calls.
  41788. *
  41789. * Call flags:
  41790. *
  41791. * DUK_CALL_FLAG_PROTECTED <--> protected call
  41792. * DUK_CALL_FLAG_IGNORE_RECLIMIT <--> ignore C recursion limit,
  41793. * for errhandler calls
  41794. * DUK_CALL_FLAG_CONSTRUCTOR_CALL <--> for 'new Foo()' calls
  41795. *
  41796. * Input stack:
  41797. *
  41798. * [ func this arg1 ... argN ]
  41799. *
  41800. * Output stack:
  41801. *
  41802. * [ retval ] (DUK_EXEC_SUCCESS)
  41803. * [ errobj ] (DUK_EXEC_ERROR (normal error), protected call)
  41804. *
  41805. * Even when executing a protected call an error may be thrown in rare cases.
  41806. * For instance, if we run out of memory when setting up the return stack
  41807. * after a caught error, the out of memory is propagated to the caller.
  41808. * Similarly, API errors (such as invalid input stack shape and invalid
  41809. * indices) cause an error to propagate out of this function. If there is
  41810. * no catchpoint for this error, the fatal error handler is called.
  41811. *
  41812. * See 'execution.txt'.
  41813. *
  41814. * The allowed thread states for making a call are:
  41815. * - thr matches heap->curr_thread, and thr is already RUNNING
  41816. * - thr does not match heap->curr_thread (may be NULL or other),
  41817. * and thr is INACTIVE (in this case, a setjmp() catchpoint is
  41818. * always used for thread book-keeping to work properly)
  41819. *
  41820. * Like elsewhere, gotos are used to keep indent level minimal and
  41821. * avoiding a dozen helpers with awkward plumbing.
  41822. *
  41823. * Note: setjmp() and local variables have a nasty interaction,
  41824. * see execution.txt; non-volatile locals modified after setjmp()
  41825. * call are not guaranteed to keep their value.
  41826. */
  41827. DUK_INTERNAL
  41828. duk_int_t duk_handle_call(duk_hthread *thr,
  41829. duk_idx_t num_stack_args,
  41830. duk_small_uint_t call_flags) {
  41831. duk_context *ctx = (duk_context *) thr;
  41832. duk_size_t entry_valstack_bottom_index;
  41833. duk_size_t entry_valstack_end;
  41834. duk_size_t entry_callstack_top;
  41835. duk_size_t entry_catchstack_top;
  41836. duk_int_t entry_call_recursion_depth;
  41837. duk_hthread *entry_curr_thread;
  41838. duk_uint_fast8_t entry_thread_state;
  41839. volatile duk_bool_t need_setjmp;
  41840. duk_jmpbuf * volatile old_jmpbuf_ptr = NULL; /* ptr is volatile (not the target) */
  41841. duk_idx_t idx_func; /* valstack index of 'func' and retval (relative to entry valstack_bottom) */
  41842. duk_idx_t idx_args; /* valstack index of start of args (arg1) (relative to entry valstack_bottom) */
  41843. duk_idx_t nargs; /* # argument registers target function wants (< 0 => "as is") */
  41844. duk_idx_t nregs; /* # total registers target function wants on entry (< 0 => "as is") */
  41845. duk_hobject *func; /* 'func' on stack (borrowed reference) */
  41846. duk_tval *tv_func; /* duk_tval ptr for 'func' on stack (borrowed reference) or tv_func_copy */
  41847. duk_tval tv_func_copy; /* to avoid relookups */
  41848. duk_activation *act;
  41849. duk_hobject *env;
  41850. duk_jmpbuf our_jmpbuf;
  41851. duk_tval tv_tmp;
  41852. duk_int_t retval = DUK_EXEC_ERROR;
  41853. duk_ret_t rc;
  41854. DUK_ASSERT(thr != NULL);
  41855. DUK_ASSERT(ctx != NULL);
  41856. DUK_ASSERT(num_stack_args >= 0);
  41857. /* XXX: currently NULL allocations are not supported; remove if later allowed */
  41858. DUK_ASSERT(thr->valstack != NULL);
  41859. DUK_ASSERT(thr->callstack != NULL);
  41860. DUK_ASSERT(thr->catchstack != NULL);
  41861. /*
  41862. * Preliminaries, required by setjmp() handler.
  41863. *
  41864. * Must be careful not to throw an unintended error here.
  41865. *
  41866. * Note: careful with indices like '-x'; if 'x' is zero, it
  41867. * refers to valstack_bottom.
  41868. */
  41869. entry_valstack_bottom_index = (duk_size_t) (thr->valstack_bottom - thr->valstack);
  41870. entry_valstack_end = (duk_size_t) (thr->valstack_end - thr->valstack);
  41871. entry_callstack_top = thr->callstack_top;
  41872. entry_catchstack_top = thr->catchstack_top;
  41873. entry_call_recursion_depth = thr->heap->call_recursion_depth;
  41874. entry_curr_thread = thr->heap->curr_thread; /* Note: may be NULL if first call */
  41875. entry_thread_state = thr->state;
  41876. idx_func = duk_normalize_index(ctx, -num_stack_args - 2); /* idx_func must be valid, note: non-throwing! */
  41877. idx_args = idx_func + 2; /* idx_args is not necessarily valid if num_stack_args == 0 (idx_args then equals top) */
  41878. /* Need a setjmp() catchpoint if a protected call OR if we need to
  41879. * do mandatory cleanup.
  41880. */
  41881. need_setjmp = ((call_flags & DUK_CALL_FLAG_PROTECTED) != 0) || (thr->heap->curr_thread != thr);
  41882. DUK_DD(DUK_DDPRINT("duk_handle_call: thr=%p, num_stack_args=%ld, "
  41883. "call_flags=0x%08lx (protected=%ld, ignorerec=%ld, constructor=%ld), need_setjmp=%ld, "
  41884. "valstack_top=%ld, idx_func=%ld, idx_args=%ld, rec_depth=%ld/%ld, "
  41885. "entry_valstack_bottom_index=%ld, entry_callstack_top=%ld, entry_catchstack_top=%ld, "
  41886. "entry_call_recursion_depth=%ld, entry_curr_thread=%p, entry_thread_state=%ld",
  41887. (void *) thr,
  41888. (long) num_stack_args,
  41889. (unsigned long) call_flags,
  41890. (long) ((call_flags & DUK_CALL_FLAG_PROTECTED) != 0 ? 1 : 0),
  41891. (long) ((call_flags & DUK_CALL_FLAG_IGNORE_RECLIMIT) != 0 ? 1 : 0),
  41892. (long) ((call_flags & DUK_CALL_FLAG_CONSTRUCTOR_CALL) != 0 ? 1 : 0),
  41893. (long) need_setjmp,
  41894. (long) duk_get_top(ctx),
  41895. (long) idx_func,
  41896. (long) idx_args,
  41897. (long) thr->heap->call_recursion_depth,
  41898. (long) thr->heap->call_recursion_limit,
  41899. (long) entry_valstack_bottom_index,
  41900. (long) entry_callstack_top,
  41901. (long) entry_catchstack_top,
  41902. (long) entry_call_recursion_depth,
  41903. (void *) entry_curr_thread,
  41904. (long) entry_thread_state));
  41905. /* XXX: Multiple tv_func lookups are now avoided by making a local
  41906. * copy of tv_func. Another approach would be to compute an offset
  41907. * for tv_func from valstack bottom and recomputing the tv_func
  41908. * pointer quickly as valstack + offset instead of calling duk_get_tval().
  41909. */
  41910. if (idx_func < 0 || idx_args < 0) {
  41911. /*
  41912. * Since stack indices are not reliable, we can't do anything useful
  41913. * here. Invoke the existing setjmp catcher, or if it doesn't exist,
  41914. * call the fatal error handler.
  41915. */
  41916. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  41917. }
  41918. /*
  41919. * Setup a setjmp() catchpoint first because even the call setup
  41920. * may fail.
  41921. */
  41922. if (!need_setjmp) {
  41923. DUK_DDD(DUK_DDDPRINT("don't need a setjmp catchpoint"));
  41924. goto handle_call;
  41925. }
  41926. old_jmpbuf_ptr = thr->heap->lj.jmpbuf_ptr;
  41927. thr->heap->lj.jmpbuf_ptr = &our_jmpbuf;
  41928. if (DUK_SETJMP(thr->heap->lj.jmpbuf_ptr->jb) == 0) {
  41929. DUK_DDD(DUK_DDDPRINT("setjmp catchpoint setup complete"));
  41930. goto handle_call;
  41931. }
  41932. /*
  41933. * Error during setup, call, or postprocessing of the call.
  41934. * The error value is in heap->lj.value1.
  41935. *
  41936. * Note: any local variables accessed here must have their value
  41937. * assigned *before* the setjmp() call, OR they must be declared
  41938. * volatile. Otherwise their value is not guaranteed to be correct.
  41939. *
  41940. * The following are such variables:
  41941. * - duk_handle_call() parameters
  41942. * - entry_*
  41943. * - idx_func
  41944. * - idx_args
  41945. *
  41946. * The very first thing we do is restore the previous setjmp catcher.
  41947. * This means that any error in error handling will propagate outwards
  41948. * instead of causing a setjmp() re-entry above. The *only* actual
  41949. * errors that should happen here are allocation errors.
  41950. */
  41951. DUK_DDD(DUK_DDDPRINT("error caught during protected duk_handle_call(): %!T",
  41952. (duk_tval *) &thr->heap->lj.value1));
  41953. DUK_ASSERT(thr->heap->lj.type == DUK_LJ_TYPE_THROW);
  41954. DUK_ASSERT(thr->callstack_top >= entry_callstack_top);
  41955. DUK_ASSERT(thr->catchstack_top >= entry_catchstack_top);
  41956. /*
  41957. * Restore previous setjmp catchpoint
  41958. */
  41959. /* Note: either pointer may be NULL (at entry), so don't assert */
  41960. DUK_DDD(DUK_DDDPRINT("restore jmpbuf_ptr: %p -> %p",
  41961. (void *) (thr && thr->heap ? thr->heap->lj.jmpbuf_ptr : NULL),
  41962. (void *) old_jmpbuf_ptr));
  41963. thr->heap->lj.jmpbuf_ptr = old_jmpbuf_ptr;
  41964. if (!(call_flags & DUK_CALL_FLAG_PROTECTED)) {
  41965. /*
  41966. * Caller did not request a protected call but a setjmp
  41967. * catchpoint was set up to allow cleanup. So, clean up
  41968. * and rethrow.
  41969. *
  41970. * We must restore curr_thread here to ensure that its
  41971. * current value doesn't end up pointing to a thread object
  41972. * which has been freed. This is now a problem because some
  41973. * call sites (namely duk_safe_call()) *first* unwind stacks
  41974. * and only then deal with curr_thread. If those call sites
  41975. * were fixed, this wouldn't matter here.
  41976. *
  41977. * Note: this case happens e.g. when heap->curr_thread is
  41978. * NULL on entry.
  41979. */
  41980. DUK_DDD(DUK_DDDPRINT("call is not protected -> clean up and rethrow"));
  41981. DUK_HEAP_SWITCH_THREAD(thr->heap, entry_curr_thread); /* may be NULL */
  41982. thr->state = entry_thread_state;
  41983. DUK_ASSERT((thr->state == DUK_HTHREAD_STATE_INACTIVE && thr->heap->curr_thread == NULL) || /* first call */
  41984. (thr->state == DUK_HTHREAD_STATE_INACTIVE && thr->heap->curr_thread != NULL) || /* other call */
  41985. (thr->state == DUK_HTHREAD_STATE_RUNNING && thr->heap->curr_thread == thr)); /* current thread */
  41986. /* XXX: should setjmp catcher be responsible for this instead? */
  41987. thr->heap->call_recursion_depth = entry_call_recursion_depth;
  41988. duk_err_longjmp(thr);
  41989. DUK_UNREACHABLE();
  41990. }
  41991. duk_hthread_catchstack_unwind(thr, entry_catchstack_top);
  41992. duk_hthread_callstack_unwind(thr, entry_callstack_top);
  41993. thr->valstack_bottom = thr->valstack + entry_valstack_bottom_index;
  41994. /* [ ... func this (crud) errobj ] */
  41995. /* XXX: is there space? better implementation: write directly over
  41996. * 'func' slot to avoid valstack grow issues.
  41997. */
  41998. duk_push_tval(ctx, &thr->heap->lj.value1);
  41999. /* [ ... func this (crud) errobj ] */
  42000. duk_replace(ctx, idx_func);
  42001. duk_set_top(ctx, idx_func + 1);
  42002. /* [ ... errobj ] */
  42003. /* Ensure there is internal valstack spare before we exit; this may
  42004. * throw an alloc error. The same guaranteed size must be available
  42005. * as before the call. This is not optimal now: we store the valstack
  42006. * allocated size during entry; this value may be higher than the
  42007. * minimal guarantee for an application.
  42008. */
  42009. (void) duk_valstack_resize_raw((duk_context *) thr,
  42010. entry_valstack_end, /* same as during entry */
  42011. DUK_VSRESIZE_FLAG_SHRINK | /* flags */
  42012. DUK_VSRESIZE_FLAG_COMPACT |
  42013. DUK_VSRESIZE_FLAG_THROW);
  42014. /* Note: currently a second setjmp restoration is done at the target;
  42015. * this is OK, but could be refactored away.
  42016. */
  42017. retval = DUK_EXEC_ERROR;
  42018. goto shrink_and_finished;
  42019. handle_call:
  42020. /*
  42021. * Thread state check and book-keeping.
  42022. */
  42023. if (thr == thr->heap->curr_thread) {
  42024. /* same thread */
  42025. if (thr->state != DUK_HTHREAD_STATE_RUNNING) {
  42026. /* should actually never happen, but check anyway */
  42027. goto thread_state_error;
  42028. }
  42029. } else {
  42030. /* different thread */
  42031. DUK_ASSERT(thr->heap->curr_thread == NULL ||
  42032. thr->heap->curr_thread->state == DUK_HTHREAD_STATE_RUNNING);
  42033. if (thr->state != DUK_HTHREAD_STATE_INACTIVE) {
  42034. goto thread_state_error;
  42035. }
  42036. DUK_HEAP_SWITCH_THREAD(thr->heap, thr);
  42037. thr->state = DUK_HTHREAD_STATE_RUNNING;
  42038. /* Note: multiple threads may be simultaneously in the RUNNING
  42039. * state, but not in the same "resume chain".
  42040. */
  42041. }
  42042. DUK_ASSERT(thr->heap->curr_thread == thr);
  42043. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_RUNNING);
  42044. /*
  42045. * C call recursion depth check, which provides a reasonable upper
  42046. * bound on maximum C stack size (arbitrary C stack growth is only
  42047. * possible by recursive handle_call / handle_safe_call calls).
  42048. */
  42049. DUK_ASSERT(thr->heap->call_recursion_depth >= 0);
  42050. DUK_ASSERT(thr->heap->call_recursion_depth <= thr->heap->call_recursion_limit);
  42051. if (call_flags & DUK_CALL_FLAG_IGNORE_RECLIMIT) {
  42052. DUK_DD(DUK_DDPRINT("ignoring reclimit for this call (probably an errhandler call)"));
  42053. } else {
  42054. if (thr->heap->call_recursion_depth >= thr->heap->call_recursion_limit) {
  42055. /* XXX: error message is a bit misleading: we reached a recursion
  42056. * limit which is also essentially the same as a C callstack limit
  42057. * (except perhaps with some relaxed threading assumptions).
  42058. */
  42059. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_C_CALLSTACK_LIMIT);
  42060. }
  42061. thr->heap->call_recursion_depth++;
  42062. }
  42063. /*
  42064. * Check the function type, handle bound function chains, and prepare
  42065. * parameters for the rest of the call handling. Also figure out the
  42066. * effective 'this' binding, which replaces the current value at
  42067. * idx_func + 1.
  42068. *
  42069. * If the target function is a 'bound' one, follow the chain of 'bound'
  42070. * functions until a non-bound function is found. During this process,
  42071. * bound arguments are 'prepended' to existing ones, and the "this"
  42072. * binding is overridden. See E5 Section 15.3.4.5.1.
  42073. *
  42074. * Lightfunc detection happens here too. Note that lightweight functions
  42075. * can be wrapped by (non-lightweight) bound functions so we must resolve
  42076. * the bound function chain first.
  42077. */
  42078. func = duk__nonbound_func_lookup(ctx, idx_func, &num_stack_args, &tv_func, call_flags);
  42079. DUK_TVAL_SET_TVAL(&tv_func_copy, tv_func);
  42080. tv_func = &tv_func_copy; /* local copy to avoid relookups */
  42081. DUK_ASSERT(func == NULL || !DUK_HOBJECT_HAS_BOUND(func));
  42082. DUK_ASSERT(func == NULL || (DUK_HOBJECT_IS_COMPILEDFUNCTION(func) ||
  42083. DUK_HOBJECT_IS_NATIVEFUNCTION(func)));
  42084. duk__coerce_effective_this_binding(thr, func, idx_func + 1);
  42085. DUK_DDD(DUK_DDDPRINT("effective 'this' binding is: %!T",
  42086. (duk_tval *) duk_get_tval(ctx, idx_func + 1)));
  42087. /* These base values are never used, but if the compiler doesn't know
  42088. * that DUK_ERROR() won't return, these are needed to silence warnings.
  42089. * On the other hand, scan-build will warn about the values not being
  42090. * used, so add a DUK_UNREF.
  42091. */
  42092. nargs = 0; DUK_UNREF(nargs);
  42093. nregs = 0; DUK_UNREF(nregs);
  42094. if (func == NULL) {
  42095. duk_small_uint_t lf_flags;
  42096. DUK_DDD(DUK_DDDPRINT("lightfunc call handling"));
  42097. DUK_ASSERT(DUK_TVAL_IS_LIGHTFUNC(tv_func));
  42098. lf_flags = DUK_TVAL_GET_LIGHTFUNC_FLAGS(tv_func);
  42099. nargs = DUK_LFUNC_FLAGS_GET_NARGS(lf_flags);
  42100. if (nargs == DUK_LFUNC_NARGS_VARARGS) {
  42101. nargs = -1; /* vararg */
  42102. }
  42103. nregs = nargs;
  42104. } else if (DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  42105. nargs = ((duk_hcompiledfunction *) func)->nargs;
  42106. nregs = ((duk_hcompiledfunction *) func)->nregs;
  42107. DUK_ASSERT(nregs >= nargs);
  42108. } else if (DUK_HOBJECT_IS_NATIVEFUNCTION(func)) {
  42109. /* Note: nargs (and nregs) may be negative for a native,
  42110. * function, which indicates that the function wants the
  42111. * input stack "as is" (i.e. handles "vararg" arguments).
  42112. */
  42113. nargs = ((duk_hnativefunction *) func)->nargs;
  42114. nregs = nargs;
  42115. } else {
  42116. /* XXX: this should be an assert */
  42117. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_NOT_CALLABLE);
  42118. }
  42119. /* [ ... func this arg1 ... argN ] */
  42120. /*
  42121. * Setup a preliminary activation.
  42122. *
  42123. * Don't touch valstack_bottom or valstack_top yet so that Duktape API
  42124. * calls work normally.
  42125. */
  42126. duk_hthread_callstack_grow(thr);
  42127. if (thr->callstack_top > 0) {
  42128. /*
  42129. * Update idx_retval of current activation.
  42130. *
  42131. * Although it might seem this is not necessary (bytecode executor
  42132. * does this for Ecmascript-to-Ecmascript calls; other calls are
  42133. * handled here), this turns out to be necessary for handling yield
  42134. * and resume. For them, an Ecmascript-to-native call happens, and
  42135. * the Ecmascript call's idx_retval must be set for things to work.
  42136. */
  42137. (thr->callstack + thr->callstack_top - 1)->idx_retval = entry_valstack_bottom_index + idx_func;
  42138. }
  42139. DUK_ASSERT(thr->callstack_top < thr->callstack_size);
  42140. act = thr->callstack + thr->callstack_top;
  42141. thr->callstack_top++;
  42142. DUK_ASSERT(thr->callstack_top <= thr->callstack_size);
  42143. DUK_ASSERT(thr->valstack_top > thr->valstack_bottom); /* at least effective 'this' */
  42144. DUK_ASSERT(func == NULL || !DUK_HOBJECT_HAS_BOUND(func));
  42145. act->flags = 0;
  42146. if (func == NULL || DUK_HOBJECT_HAS_STRICT(func)) {
  42147. act->flags |= DUK_ACT_FLAG_STRICT;
  42148. }
  42149. if (call_flags & DUK_CALL_FLAG_CONSTRUCTOR_CALL) {
  42150. act->flags |= DUK_ACT_FLAG_CONSTRUCT;
  42151. /*act->flags |= DUK_ACT_FLAG_PREVENT_YIELD;*/
  42152. }
  42153. if (func == NULL || DUK_HOBJECT_IS_NATIVEFUNCTION(func)) {
  42154. /*act->flags |= DUK_ACT_FLAG_PREVENT_YIELD;*/
  42155. }
  42156. if (call_flags & DUK_CALL_FLAG_DIRECT_EVAL) {
  42157. act->flags |= DUK_ACT_FLAG_DIRECT_EVAL;
  42158. }
  42159. /* As a first approximation, all calls except Ecmascript-to-Ecmascript
  42160. * calls prevent a yield.
  42161. */
  42162. act->flags |= DUK_ACT_FLAG_PREVENT_YIELD;
  42163. act->func = func; /* NULL for lightfunc */
  42164. act->var_env = NULL;
  42165. act->lex_env = NULL;
  42166. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  42167. act->prev_caller = NULL;
  42168. #endif
  42169. act->pc = 0;
  42170. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  42171. act->prev_line = 0;
  42172. #endif
  42173. act->idx_bottom = entry_valstack_bottom_index + idx_args;
  42174. #if 0 /* topmost activation idx_retval is considered garbage, no need to init */
  42175. act->idx_retval = 0;
  42176. #endif
  42177. DUK_TVAL_SET_TVAL(&act->tv_func, tv_func); /* borrowed, no refcount */
  42178. if (act->flags & DUK_ACT_FLAG_PREVENT_YIELD) {
  42179. /* duk_hthread_callstack_unwind() will decrease this on unwind */
  42180. thr->callstack_preventcount++;
  42181. }
  42182. /* XXX: Is this INCREF necessary? 'func' is always a borrowed
  42183. * reference reachable through the value stack? If changed, stack
  42184. * unwind code also needs to be fixed to match.
  42185. */
  42186. DUK_HOBJECT_INCREF_ALLOWNULL(thr, func); /* act->func */
  42187. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  42188. if (func) {
  42189. duk__update_func_caller_prop(thr, func);
  42190. }
  42191. act = thr->callstack + thr->callstack_top - 1;
  42192. #endif
  42193. /* [... func this arg1 ... argN] */
  42194. /*
  42195. * Environment record creation and 'arguments' object creation.
  42196. * Named function expression name binding is handled by the
  42197. * compiler; the compiled function's parent env will contain
  42198. * the (immutable) binding already.
  42199. *
  42200. * This handling is now identical for C and Ecmascript functions.
  42201. * C functions always have the 'NEWENV' flag set, so their
  42202. * environment record initialization is delayed (which is good).
  42203. *
  42204. * Delayed creation (on demand) is handled in duk_js_var.c.
  42205. */
  42206. DUK_ASSERT(func == NULL || !DUK_HOBJECT_HAS_BOUND(func)); /* bound function chain has already been resolved */
  42207. if (func != NULL && !DUK_HOBJECT_HAS_NEWENV(func)) {
  42208. /* use existing env (e.g. for non-strict eval); cannot have
  42209. * an own 'arguments' object (but can refer to the existing one)
  42210. */
  42211. DUK_ASSERT(!DUK_HOBJECT_HAS_CREATEARGS(func));
  42212. duk__handle_oldenv_for_call(thr, func, act);
  42213. DUK_ASSERT(act->lex_env != NULL);
  42214. DUK_ASSERT(act->var_env != NULL);
  42215. goto env_done;
  42216. }
  42217. DUK_ASSERT(func == NULL || DUK_HOBJECT_HAS_NEWENV(func));
  42218. if (func == NULL || !DUK_HOBJECT_HAS_CREATEARGS(func)) {
  42219. /* no need to create environment record now; leave as NULL */
  42220. DUK_ASSERT(act->lex_env == NULL);
  42221. DUK_ASSERT(act->var_env == NULL);
  42222. goto env_done;
  42223. }
  42224. /* third arg: absolute index (to entire valstack) of idx_bottom of new activation */
  42225. env = duk_create_activation_environment_record(thr, func, act->idx_bottom);
  42226. DUK_ASSERT(env != NULL);
  42227. /* [... func this arg1 ... argN envobj] */
  42228. DUK_ASSERT(DUK_HOBJECT_HAS_CREATEARGS(func));
  42229. duk__handle_createargs_for_call(thr, func, env, num_stack_args);
  42230. /* [... func this arg1 ... argN envobj] */
  42231. act->lex_env = env;
  42232. act->var_env = env;
  42233. DUK_HOBJECT_INCREF(thr, env);
  42234. DUK_HOBJECT_INCREF(thr, env); /* XXX: incref by count (2) directly */
  42235. duk_pop(ctx);
  42236. env_done:
  42237. /* [... func this arg1 ... argN] */
  42238. /*
  42239. * Setup value stack: clamp to 'nargs', fill up to 'nregs'
  42240. *
  42241. * Value stack may either grow or shrink, depending on the
  42242. * number of func registers and the number of actual arguments.
  42243. * If nregs >= 0, func wants args clamped to 'nargs'; else it
  42244. * wants all args (= 'num_stack_args').
  42245. */
  42246. duk__adjust_valstack_and_top(thr,
  42247. num_stack_args,
  42248. idx_args,
  42249. nregs,
  42250. nargs,
  42251. func);
  42252. /*
  42253. * Determine call type; then setup activation and call
  42254. */
  42255. if (func != NULL && DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  42256. goto ecmascript_call;
  42257. } else {
  42258. goto native_call;
  42259. }
  42260. DUK_UNREACHABLE();
  42261. /*
  42262. * Native (C) call
  42263. */
  42264. native_call:
  42265. /*
  42266. * Shift to new valstack_bottom.
  42267. */
  42268. thr->valstack_bottom = thr->valstack_bottom + idx_args;
  42269. /* keep current valstack_top */
  42270. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  42271. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  42272. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  42273. DUK_ASSERT(func == NULL || ((duk_hnativefunction *) func)->func != NULL);
  42274. /* [... func this | arg1 ... argN] ('this' must precede new bottom) */
  42275. /*
  42276. * Actual function call and return value check.
  42277. *
  42278. * Return values:
  42279. * 0 success, no return value (default to 'undefined')
  42280. * 1 success, one return value on top of stack
  42281. * < 0 error, throw a "magic" error
  42282. * other invalid
  42283. */
  42284. if (func) {
  42285. rc = ((duk_hnativefunction *) func)->func((duk_context *) thr);
  42286. } else {
  42287. duk_c_function funcptr = DUK_TVAL_GET_LIGHTFUNC_FUNCPTR(tv_func);
  42288. rc = funcptr((duk_context *) thr);
  42289. }
  42290. if (rc < 0) {
  42291. duk_error_throw_from_negative_rc(thr, rc);
  42292. DUK_UNREACHABLE();
  42293. } else if (rc > 1) {
  42294. DUK_ERROR(thr, DUK_ERR_API_ERROR, "c function returned invalid rc");
  42295. }
  42296. DUK_ASSERT(rc == 0 || rc == 1);
  42297. /*
  42298. * Unwind stack(s) and shift back to old valstack_bottom.
  42299. */
  42300. DUK_ASSERT(thr->catchstack_top == entry_catchstack_top);
  42301. DUK_ASSERT(thr->callstack_top == entry_callstack_top + 1);
  42302. #if 0 /* should be no need to unwind */
  42303. duk_hthread_catchstack_unwind(thr, entry_catchstack_top);
  42304. #endif
  42305. duk_hthread_callstack_unwind(thr, entry_callstack_top);
  42306. thr->valstack_bottom = thr->valstack + entry_valstack_bottom_index;
  42307. /* keep current valstack_top */
  42308. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  42309. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  42310. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  42311. DUK_ASSERT(thr->valstack_top - thr->valstack_bottom >= idx_func + 1);
  42312. /*
  42313. * Manipulate value stack so that return value is on top
  42314. * (pushing an 'undefined' if necessary).
  42315. */
  42316. /* XXX: should this happen in the callee's activation or after unwinding? */
  42317. if (rc == 0) {
  42318. duk_require_stack(ctx, 1);
  42319. duk_push_undefined(ctx);
  42320. }
  42321. /* [... func this (crud) retval] */
  42322. DUK_DDD(DUK_DDDPRINT("native call retval -> %!T (rc=%ld)",
  42323. (duk_tval *) duk_get_tval(ctx, -1), (long) rc));
  42324. duk_replace(ctx, idx_func);
  42325. duk_set_top(ctx, idx_func + 1);
  42326. /* [... retval] */
  42327. /* Ensure there is internal valstack spare before we exit; this may
  42328. * throw an alloc error. The same guaranteed size must be available
  42329. * as before the call. This is not optimal now: we store the valstack
  42330. * allocated size during entry; this value may be higher than the
  42331. * minimal guarantee for an application.
  42332. */
  42333. (void) duk_valstack_resize_raw((duk_context *) thr,
  42334. entry_valstack_end, /* same as during entry */
  42335. DUK_VSRESIZE_FLAG_SHRINK | /* flags */
  42336. DUK_VSRESIZE_FLAG_COMPACT |
  42337. DUK_VSRESIZE_FLAG_THROW);
  42338. /*
  42339. * Shrink checks and return with success.
  42340. */
  42341. retval = DUK_EXEC_SUCCESS;
  42342. goto shrink_and_finished;
  42343. /*
  42344. * Ecmascript call
  42345. */
  42346. ecmascript_call:
  42347. /*
  42348. * Shift to new valstack_bottom.
  42349. */
  42350. thr->valstack_bottom = thr->valstack_bottom + idx_args;
  42351. /* keep current valstack_top */
  42352. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  42353. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  42354. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  42355. /* [... func this | arg1 ... argN] ('this' must precede new bottom) */
  42356. /*
  42357. * Bytecode executor call.
  42358. *
  42359. * Execute bytecode, handling any recursive function calls and
  42360. * thread resumptions. Returns when execution would return from
  42361. * the entry level activation. When the executor returns, a
  42362. * single return value is left on the stack top.
  42363. *
  42364. * The only possible longjmp() is an error (DUK_LJ_TYPE_THROW),
  42365. * other types are handled internally by the executor.
  42366. *
  42367. */
  42368. DUK_DDD(DUK_DDDPRINT("entering bytecode execution"));
  42369. duk_js_execute_bytecode(thr);
  42370. DUK_DDD(DUK_DDDPRINT("returned from bytecode execution"));
  42371. /*
  42372. * Unwind stack(s) and shift back to old valstack_bottom.
  42373. */
  42374. DUK_ASSERT(thr->callstack_top == entry_callstack_top + 1);
  42375. duk_hthread_catchstack_unwind(thr, entry_catchstack_top);
  42376. duk_hthread_callstack_unwind(thr, entry_callstack_top);
  42377. thr->valstack_bottom = thr->valstack + entry_valstack_bottom_index;
  42378. /* keep current valstack_top */
  42379. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  42380. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  42381. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  42382. DUK_ASSERT(thr->valstack_top - thr->valstack_bottom >= idx_func + 1);
  42383. /*
  42384. * Manipulate value stack so that return value is on top.
  42385. */
  42386. /* [... func this (crud) retval] */
  42387. duk_replace(ctx, idx_func);
  42388. duk_set_top(ctx, idx_func + 1);
  42389. /* [... retval] */
  42390. /* Ensure there is internal valstack spare before we exit; this may
  42391. * throw an alloc error. The same guaranteed size must be available
  42392. * as before the call. This is not optimal now: we store the valstack
  42393. * allocated size during entry; this value may be higher than the
  42394. * minimal guarantee for an application.
  42395. */
  42396. (void) duk_valstack_resize_raw((duk_context *) thr,
  42397. entry_valstack_end, /* same as during entry */
  42398. DUK_VSRESIZE_FLAG_SHRINK | /* flags */
  42399. DUK_VSRESIZE_FLAG_COMPACT |
  42400. DUK_VSRESIZE_FLAG_THROW);
  42401. /*
  42402. * Shrink checks and return with success.
  42403. */
  42404. retval = DUK_EXEC_SUCCESS;
  42405. goto shrink_and_finished;
  42406. shrink_and_finished:
  42407. #if defined(DUK_OPT_FASTINT)
  42408. /* Explicit check for fastint downgrade. */
  42409. {
  42410. duk_tval *tv_fi;
  42411. tv_fi = duk_get_tval(ctx, -1);
  42412. DUK_ASSERT(tv_fi != NULL);
  42413. DUK_TVAL_CHKFAST_INPLACE(tv_fi);
  42414. }
  42415. #endif
  42416. /* these are "soft" shrink checks, whose failures are ignored */
  42417. /* XXX: would be nice if fast path was inlined */
  42418. duk_hthread_catchstack_shrink_check(thr);
  42419. duk_hthread_callstack_shrink_check(thr);
  42420. goto finished;
  42421. finished:
  42422. if (need_setjmp) {
  42423. /* Note: either pointer may be NULL (at entry), so don't assert;
  42424. * this is now done potentially twice, which is OK
  42425. */
  42426. DUK_DDD(DUK_DDDPRINT("restore jmpbuf_ptr: %p -> %p (possibly already done)",
  42427. (void *) (thr && thr->heap ? thr->heap->lj.jmpbuf_ptr : NULL),
  42428. (void *) old_jmpbuf_ptr));
  42429. thr->heap->lj.jmpbuf_ptr = old_jmpbuf_ptr;
  42430. /* These are just convenience "wiping" of state */
  42431. thr->heap->lj.type = DUK_LJ_TYPE_UNKNOWN;
  42432. thr->heap->lj.iserror = 0;
  42433. /* Side effects should not be an issue here: tv_tmp is local and
  42434. * thr->heap (and thr->heap->lj) have a stable pointer. Finalizer
  42435. * runs etc capture even out-of-memory errors so nothing should
  42436. * throw here.
  42437. */
  42438. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value1);
  42439. DUK_TVAL_SET_UNDEFINED_UNUSED(&thr->heap->lj.value1);
  42440. DUK_TVAL_DECREF(thr, &tv_tmp);
  42441. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value2);
  42442. DUK_TVAL_SET_UNDEFINED_UNUSED(&thr->heap->lj.value2);
  42443. DUK_TVAL_DECREF(thr, &tv_tmp);
  42444. DUK_DDD(DUK_DDDPRINT("setjmp catchpoint torn down"));
  42445. }
  42446. DUK_HEAP_SWITCH_THREAD(thr->heap, entry_curr_thread); /* may be NULL */
  42447. thr->state = (duk_uint8_t) entry_thread_state;
  42448. DUK_ASSERT((thr->state == DUK_HTHREAD_STATE_INACTIVE && thr->heap->curr_thread == NULL) || /* first call */
  42449. (thr->state == DUK_HTHREAD_STATE_INACTIVE && thr->heap->curr_thread != NULL) || /* other call */
  42450. (thr->state == DUK_HTHREAD_STATE_RUNNING && thr->heap->curr_thread == thr)); /* current thread */
  42451. thr->heap->call_recursion_depth = entry_call_recursion_depth;
  42452. return retval;
  42453. thread_state_error:
  42454. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "invalid thread state for call (%ld)", (long) thr->state);
  42455. DUK_UNREACHABLE();
  42456. return DUK_EXEC_ERROR; /* never executed */
  42457. }
  42458. /*
  42459. * Manipulate value stack so that exactly 'num_stack_rets' return
  42460. * values are at 'idx_retbase' in every case, assuming there are
  42461. * 'rc' return values on top of stack.
  42462. *
  42463. * This is a bit tricky, because the called C function operates in
  42464. * the same activation record and may have e.g. popped the stack
  42465. * empty (below idx_retbase).
  42466. */
  42467. DUK_LOCAL void duk__safe_call_adjust_valstack(duk_hthread *thr, duk_idx_t idx_retbase, duk_idx_t num_stack_rets, duk_idx_t num_actual_rets) {
  42468. duk_context *ctx = (duk_context *) thr;
  42469. duk_idx_t idx_rcbase;
  42470. DUK_ASSERT(thr != NULL);
  42471. DUK_ASSERT(idx_retbase >= 0);
  42472. DUK_ASSERT(num_stack_rets >= 0);
  42473. DUK_ASSERT(num_actual_rets >= 0);
  42474. idx_rcbase = duk_get_top(ctx) - num_actual_rets; /* base of known return values */
  42475. DUK_DDD(DUK_DDDPRINT("adjust valstack after func call: "
  42476. "num_stack_rets=%ld, num_actual_rets=%ld, stack_top=%ld, idx_retbase=%ld, idx_rcbase=%ld",
  42477. (long) num_stack_rets, (long) num_actual_rets, (long) duk_get_top(ctx),
  42478. (long) idx_retbase, (long) idx_rcbase));
  42479. DUK_ASSERT(idx_rcbase >= 0); /* caller must check */
  42480. /* ensure space for final configuration (idx_retbase + num_stack_rets) and
  42481. * intermediate configurations
  42482. */
  42483. duk_require_stack_top(ctx,
  42484. (idx_rcbase > idx_retbase ? idx_rcbase : idx_retbase) +
  42485. num_stack_rets);
  42486. /* chop extra retvals away / extend with undefined */
  42487. duk_set_top(ctx, idx_rcbase + num_stack_rets);
  42488. if (idx_rcbase >= idx_retbase) {
  42489. duk_idx_t count = idx_rcbase - idx_retbase;
  42490. duk_idx_t i;
  42491. DUK_DDD(DUK_DDDPRINT("elements at/after idx_retbase have enough to cover func retvals "
  42492. "(idx_retbase=%ld, idx_rcbase=%ld)", (long) idx_retbase, (long) idx_rcbase));
  42493. /* nuke values at idx_retbase to get the first retval (initially
  42494. * at idx_rcbase) to idx_retbase
  42495. */
  42496. DUK_ASSERT(count >= 0);
  42497. for (i = 0; i < count; i++) {
  42498. /* XXX: inefficient; block remove primitive */
  42499. duk_remove(ctx, idx_retbase);
  42500. }
  42501. } else {
  42502. duk_idx_t count = idx_retbase - idx_rcbase;
  42503. duk_idx_t i;
  42504. DUK_DDD(DUK_DDDPRINT("not enough elements at/after idx_retbase to cover func retvals "
  42505. "(idx_retbase=%ld, idx_rcbase=%ld)", (long) idx_retbase, (long) idx_rcbase));
  42506. /* insert 'undefined' values at idx_rcbase to get the
  42507. * return values to idx_retbase
  42508. */
  42509. DUK_ASSERT(count > 0);
  42510. for (i = 0; i < count; i++) {
  42511. /* XXX: inefficient; block insert primitive */
  42512. duk_push_undefined(ctx);
  42513. duk_insert(ctx, idx_rcbase);
  42514. }
  42515. }
  42516. }
  42517. /*
  42518. * Make a "C protected call" within the current activation.
  42519. *
  42520. * The allowed thread states for making a call are the same as for
  42521. * duk_handle_call().
  42522. *
  42523. * Note that like duk_handle_call(), even if this call is protected,
  42524. * there are a few situations where the current (pre-entry) setjmp
  42525. * catcher (or a fatal error handler if no such catcher exists) is
  42526. * invoked:
  42527. *
  42528. * - Blatant API argument errors (e.g. num_stack_args is invalid,
  42529. * so we can't form a reasonable return stack)
  42530. *
  42531. * - Errors during error handling, e.g. failure to reallocate
  42532. * space in the value stack due to an alloc error
  42533. *
  42534. * Such errors propagate outwards, ultimately to the fatal error
  42535. * handler if nothing else.
  42536. */
  42537. /* XXX: bump preventcount by one for the duration of this call? */
  42538. DUK_INTERNAL
  42539. duk_int_t duk_handle_safe_call(duk_hthread *thr,
  42540. duk_safe_call_function func,
  42541. duk_idx_t num_stack_args,
  42542. duk_idx_t num_stack_rets) {
  42543. duk_context *ctx = (duk_context *) thr;
  42544. duk_size_t entry_valstack_bottom_index;
  42545. duk_size_t entry_callstack_top;
  42546. duk_size_t entry_catchstack_top;
  42547. duk_int_t entry_call_recursion_depth;
  42548. duk_hthread *entry_curr_thread;
  42549. duk_uint_fast8_t entry_thread_state;
  42550. duk_jmpbuf *old_jmpbuf_ptr = NULL;
  42551. duk_jmpbuf our_jmpbuf;
  42552. duk_tval tv_tmp;
  42553. duk_idx_t idx_retbase;
  42554. duk_int_t retval;
  42555. duk_ret_t rc;
  42556. DUK_ASSERT(thr != NULL);
  42557. DUK_ASSERT(ctx != NULL);
  42558. /* Note: careful with indices like '-x'; if 'x' is zero, it refers to bottom */
  42559. entry_valstack_bottom_index = (duk_size_t) (thr->valstack_bottom - thr->valstack);
  42560. entry_callstack_top = thr->callstack_top;
  42561. entry_catchstack_top = thr->catchstack_top;
  42562. entry_call_recursion_depth = thr->heap->call_recursion_depth;
  42563. entry_curr_thread = thr->heap->curr_thread; /* Note: may be NULL if first call */
  42564. entry_thread_state = thr->state;
  42565. idx_retbase = duk_get_top(ctx) - num_stack_args; /* Note: not a valid stack index if num_stack_args == 0 */
  42566. /* Note: cannot portably debug print a function pointer, hence 'func' not printed! */
  42567. DUK_DD(DUK_DDPRINT("duk_handle_safe_call: thr=%p, num_stack_args=%ld, num_stack_rets=%ld, "
  42568. "valstack_top=%ld, idx_retbase=%ld, rec_depth=%ld/%ld, "
  42569. "entry_valstack_bottom_index=%ld, entry_callstack_top=%ld, entry_catchstack_top=%ld, "
  42570. "entry_call_recursion_depth=%ld, entry_curr_thread=%p, entry_thread_state=%ld",
  42571. (void *) thr,
  42572. (long) num_stack_args,
  42573. (long) num_stack_rets,
  42574. (long) duk_get_top(ctx),
  42575. (long) idx_retbase,
  42576. (long) thr->heap->call_recursion_depth,
  42577. (long) thr->heap->call_recursion_limit,
  42578. (long) entry_valstack_bottom_index,
  42579. (long) entry_callstack_top,
  42580. (long) entry_catchstack_top,
  42581. (long) entry_call_recursion_depth,
  42582. (void *) entry_curr_thread,
  42583. (long) entry_thread_state));
  42584. if (idx_retbase < 0) {
  42585. /*
  42586. * Since stack indices are not reliable, we can't do anything useful
  42587. * here. Invoke the existing setjmp catcher, or if it doesn't exist,
  42588. * call the fatal error handler.
  42589. */
  42590. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  42591. }
  42592. /* setjmp catchpoint setup */
  42593. old_jmpbuf_ptr = thr->heap->lj.jmpbuf_ptr;
  42594. thr->heap->lj.jmpbuf_ptr = &our_jmpbuf;
  42595. if (DUK_SETJMP(thr->heap->lj.jmpbuf_ptr->jb) == 0) {
  42596. goto handle_call;
  42597. }
  42598. /*
  42599. * Error during call. The error value is at heap->lj.value1.
  42600. *
  42601. * Careful with variable accesses here; must be assigned to before
  42602. * setjmp() or be declared volatile. See duk_handle_call().
  42603. *
  42604. * The following are such variables:
  42605. * - duk_handle_safe_call() parameters
  42606. * - entry_*
  42607. * - idx_retbase
  42608. *
  42609. * The very first thing we do is restore the previous setjmp catcher.
  42610. * This means that any error in error handling will propagate outwards
  42611. * instead of causing a setjmp() re-entry above. The *only* actual
  42612. * errors that should happen here are allocation errors.
  42613. */
  42614. DUK_DDD(DUK_DDDPRINT("error caught during protected duk_handle_safe_call()"));
  42615. DUK_ASSERT(thr->heap->lj.type == DUK_LJ_TYPE_THROW);
  42616. DUK_ASSERT(thr->callstack_top >= entry_callstack_top);
  42617. DUK_ASSERT(thr->catchstack_top >= entry_catchstack_top);
  42618. /* Note: either pointer may be NULL (at entry), so don't assert;
  42619. * these are now restored twice which is OK.
  42620. */
  42621. thr->heap->lj.jmpbuf_ptr = old_jmpbuf_ptr;
  42622. duk_hthread_catchstack_unwind(thr, entry_catchstack_top);
  42623. duk_hthread_callstack_unwind(thr, entry_callstack_top);
  42624. thr->valstack_bottom = thr->valstack + entry_valstack_bottom_index;
  42625. /* [ ... | (crud) ] */
  42626. /* XXX: space in valstack? see discussion in duk_handle_call. */
  42627. duk_push_tval(ctx, &thr->heap->lj.value1);
  42628. /* [ ... | (crud) errobj ] */
  42629. DUK_ASSERT(duk_get_top(ctx) >= 1); /* at least errobj must be on stack */
  42630. /* check that the valstack has space for the final amount and any
  42631. * intermediate space needed; this is unoptimal but should be safe
  42632. */
  42633. duk_require_stack_top(ctx, idx_retbase + num_stack_rets); /* final configuration */
  42634. duk_require_stack(ctx, num_stack_rets);
  42635. duk__safe_call_adjust_valstack(thr, idx_retbase, num_stack_rets, 1); /* 1 = num actual 'return values' */
  42636. /* [ ... | ] or [ ... | errobj (M * undefined)] where M = num_stack_rets - 1 */
  42637. retval = DUK_EXEC_ERROR;
  42638. goto shrink_and_finished;
  42639. /*
  42640. * Handle call (inside setjmp)
  42641. */
  42642. handle_call:
  42643. DUK_DDD(DUK_DDDPRINT("safe_call setjmp catchpoint setup complete"));
  42644. /*
  42645. * Thread state check and book-keeping.
  42646. */
  42647. if (thr == thr->heap->curr_thread) {
  42648. /* same thread */
  42649. if (thr->state != DUK_HTHREAD_STATE_RUNNING) {
  42650. /* should actually never happen, but check anyway */
  42651. goto thread_state_error;
  42652. }
  42653. } else {
  42654. /* different thread */
  42655. DUK_ASSERT(thr->heap->curr_thread == NULL ||
  42656. thr->heap->curr_thread->state == DUK_HTHREAD_STATE_RUNNING);
  42657. if (thr->state != DUK_HTHREAD_STATE_INACTIVE) {
  42658. goto thread_state_error;
  42659. }
  42660. DUK_HEAP_SWITCH_THREAD(thr->heap, thr);
  42661. thr->state = DUK_HTHREAD_STATE_RUNNING;
  42662. /* Note: multiple threads may be simultaneously in the RUNNING
  42663. * state, but not in the same "resume chain".
  42664. */
  42665. }
  42666. DUK_ASSERT(thr->heap->curr_thread == thr);
  42667. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_RUNNING);
  42668. /*
  42669. * Recursion limit check.
  42670. *
  42671. * Note: there is no need for an "ignore recursion limit" flag
  42672. * for duk_handle_safe_call now.
  42673. */
  42674. DUK_ASSERT(thr->heap->call_recursion_depth >= 0);
  42675. DUK_ASSERT(thr->heap->call_recursion_depth <= thr->heap->call_recursion_limit);
  42676. if (thr->heap->call_recursion_depth >= thr->heap->call_recursion_limit) {
  42677. /* XXX: error message is a bit misleading: we reached a recursion
  42678. * limit which is also essentially the same as a C callstack limit
  42679. * (except perhaps with some relaxed threading assumptions).
  42680. */
  42681. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_C_CALLSTACK_LIMIT);
  42682. }
  42683. thr->heap->call_recursion_depth++;
  42684. /*
  42685. * Valstack spare check
  42686. */
  42687. duk_require_stack(ctx, 0); /* internal spare */
  42688. /*
  42689. * Make the C call
  42690. */
  42691. rc = func(ctx);
  42692. DUK_DDD(DUK_DDDPRINT("safe_call, func rc=%ld", (long) rc));
  42693. /*
  42694. * Valstack manipulation for results
  42695. */
  42696. /* we're running inside the caller's activation, so no change in call/catch stack or valstack bottom */
  42697. DUK_ASSERT(thr->callstack_top == entry_callstack_top);
  42698. DUK_ASSERT(thr->catchstack_top == entry_catchstack_top);
  42699. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  42700. DUK_ASSERT((duk_size_t) (thr->valstack_bottom - thr->valstack) == entry_valstack_bottom_index);
  42701. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  42702. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  42703. if (rc < 0) {
  42704. duk_error_throw_from_negative_rc(thr, rc);
  42705. }
  42706. DUK_ASSERT(rc >= 0);
  42707. if (duk_get_top(ctx) < rc) {
  42708. DUK_ERROR(thr, DUK_ERR_API_ERROR, "not enough stack values for safe_call rc");
  42709. }
  42710. duk__safe_call_adjust_valstack(thr, idx_retbase, num_stack_rets, rc);
  42711. /* Note: no need from callstack / catchstack shrink check */
  42712. retval = DUK_EXEC_SUCCESS;
  42713. goto finished;
  42714. shrink_and_finished:
  42715. /* these are "soft" shrink checks, whose failures are ignored */
  42716. /* XXX: would be nice if fast path was inlined */
  42717. duk_hthread_catchstack_shrink_check(thr);
  42718. duk_hthread_callstack_shrink_check(thr);
  42719. goto finished;
  42720. finished:
  42721. /* Note: either pointer may be NULL (at entry), so don't assert */
  42722. thr->heap->lj.jmpbuf_ptr = old_jmpbuf_ptr;
  42723. /* These are just convenience "wiping" of state */
  42724. thr->heap->lj.type = DUK_LJ_TYPE_UNKNOWN;
  42725. thr->heap->lj.iserror = 0;
  42726. /* Side effects should not be an issue here: tv_tmp is local and
  42727. * thr->heap (and thr->heap->lj) have a stable pointer. Finalizer
  42728. * runs etc capture even out-of-memory errors so nothing should
  42729. * throw here.
  42730. */
  42731. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value1);
  42732. DUK_TVAL_SET_UNDEFINED_UNUSED(&thr->heap->lj.value1);
  42733. DUK_TVAL_DECREF(thr, &tv_tmp);
  42734. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value2);
  42735. DUK_TVAL_SET_UNDEFINED_UNUSED(&thr->heap->lj.value2);
  42736. DUK_TVAL_DECREF(thr, &tv_tmp);
  42737. DUK_DDD(DUK_DDDPRINT("setjmp catchpoint torn down"));
  42738. /* XXX: because we unwind stacks above, thr->heap->curr_thread is at
  42739. * risk of pointing to an already freed thread. This was indeed the
  42740. * case in test-bug-multithread-valgrind.c, until duk_handle_call()
  42741. * was fixed to restore thr->heap->curr_thread before rethrowing an
  42742. * uncaught error.
  42743. */
  42744. DUK_HEAP_SWITCH_THREAD(thr->heap, entry_curr_thread); /* may be NULL */
  42745. thr->state = (duk_uint8_t) entry_thread_state;
  42746. DUK_ASSERT((thr->state == DUK_HTHREAD_STATE_INACTIVE && thr->heap->curr_thread == NULL) || /* first call */
  42747. (thr->state == DUK_HTHREAD_STATE_INACTIVE && thr->heap->curr_thread != NULL) || /* other call */
  42748. (thr->state == DUK_HTHREAD_STATE_RUNNING && thr->heap->curr_thread == thr)); /* current thread */
  42749. thr->heap->call_recursion_depth = entry_call_recursion_depth;
  42750. /* stack discipline consistency check */
  42751. DUK_ASSERT(duk_get_top(ctx) == idx_retbase + num_stack_rets);
  42752. return retval;
  42753. thread_state_error:
  42754. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "invalid thread state for safe_call (%ld)", (long) thr->state);
  42755. DUK_UNREACHABLE();
  42756. return DUK_EXEC_ERROR; /* never executed */
  42757. }
  42758. /*
  42759. * Helper for handling an Ecmascript-to-Ecmascript call or an Ecmascript
  42760. * function (initial) Duktape.Thread.resume().
  42761. *
  42762. * Compared to normal calls handled by duk_handle_call(), there are a
  42763. * bunch of differences:
  42764. *
  42765. * - the call is never protected
  42766. * - there is no C recursion depth increase (hence an "ignore recursion
  42767. * limit" flag is not applicable)
  42768. * - instead of making the call, this helper just performs the thread
  42769. * setup and returns; the bytecode executor then restarts execution
  42770. * internally
  42771. * - ecmascript functions are never 'vararg' functions (they access
  42772. * varargs through the 'arguments' object)
  42773. *
  42774. * The callstack of the target contains an earlier Ecmascript call in case
  42775. * of an Ecmascript-to-Ecmascript call (whose idx_retval is updated), or
  42776. * is empty in case of an initial Duktape.Thread.resume().
  42777. *
  42778. * The first thing to do here is to figure out whether an ecma-to-ecma
  42779. * call is actually possible. It's not always the case if the target is
  42780. * a bound function; the final function may be native. In that case,
  42781. * return an error so caller can fall back to a normal call path.
  42782. */
  42783. DUK_INTERNAL
  42784. duk_bool_t duk_handle_ecma_call_setup(duk_hthread *thr,
  42785. duk_idx_t num_stack_args,
  42786. duk_small_uint_t call_flags) {
  42787. duk_context *ctx = (duk_context *) thr;
  42788. duk_size_t entry_valstack_bottom_index;
  42789. duk_idx_t idx_func; /* valstack index of 'func' and retval (relative to entry valstack_bottom) */
  42790. duk_idx_t idx_args; /* valstack index of start of args (arg1) (relative to entry valstack_bottom) */
  42791. duk_idx_t nargs; /* # argument registers target function wants (< 0 => never for ecma calls) */
  42792. duk_idx_t nregs; /* # total registers target function wants on entry (< 0 => never for ecma calls) */
  42793. duk_hobject *func; /* 'func' on stack (borrowed reference) */
  42794. duk_tval *tv_func; /* duk_tval ptr for 'func' on stack (borrowed reference) */
  42795. duk_activation *act;
  42796. duk_hobject *env;
  42797. duk_bool_t use_tailcall;
  42798. DUK_ASSERT(thr != NULL);
  42799. DUK_ASSERT(ctx != NULL);
  42800. DUK_ASSERT(!((call_flags & DUK_CALL_FLAG_IS_RESUME) != 0 && (call_flags & DUK_CALL_FLAG_IS_TAILCALL) != 0));
  42801. /* XXX: assume these? */
  42802. DUK_ASSERT(thr->valstack != NULL);
  42803. DUK_ASSERT(thr->callstack != NULL);
  42804. DUK_ASSERT(thr->catchstack != NULL);
  42805. /* no need to handle thread state book-keeping here */
  42806. DUK_ASSERT((call_flags & DUK_CALL_FLAG_IS_RESUME) != 0 ||
  42807. (thr->state == DUK_HTHREAD_STATE_RUNNING &&
  42808. thr->heap->curr_thread == thr));
  42809. /* if a tailcall:
  42810. * - an Ecmascript activation must be on top of the callstack
  42811. * - there cannot be any active catchstack entries
  42812. */
  42813. #ifdef DUK_USE_ASSERTIONS
  42814. if (call_flags & DUK_CALL_FLAG_IS_TAILCALL) {
  42815. duk_size_t our_callstack_index;
  42816. duk_size_t i;
  42817. DUK_ASSERT(thr->callstack_top >= 1);
  42818. our_callstack_index = thr->callstack_top - 1;
  42819. DUK_ASSERT_DISABLE(our_callstack_index >= 0);
  42820. DUK_ASSERT(our_callstack_index < thr->callstack_size);
  42821. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + our_callstack_index) != NULL);
  42822. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + our_callstack_index)));
  42823. /* No entry in the catchstack which would actually catch a
  42824. * throw can refer to the callstack entry being reused.
  42825. * There *can* be catchstack entries referring to the current
  42826. * callstack entry as long as they don't catch (e.g. label sites).
  42827. */
  42828. for (i = 0; i < thr->catchstack_top; i++) {
  42829. DUK_ASSERT(thr->catchstack[i].callstack_index < our_callstack_index || /* refer to callstack entries below current */
  42830. DUK_CAT_GET_TYPE(thr->catchstack + i) == DUK_CAT_TYPE_LABEL); /* or a non-catching entry */
  42831. }
  42832. }
  42833. #endif /* DUK_USE_ASSERTIONS */
  42834. entry_valstack_bottom_index = (duk_size_t) (thr->valstack_bottom - thr->valstack);
  42835. idx_func = duk_normalize_index(thr, -num_stack_args - 2);
  42836. idx_args = idx_func + 2;
  42837. DUK_DD(DUK_DDPRINT("handle_ecma_call_setup: thr=%p, "
  42838. "num_stack_args=%ld, call_flags=0x%08lx (resume=%ld, tailcall=%ld), "
  42839. "idx_func=%ld, idx_args=%ld, entry_valstack_bottom_index=%ld",
  42840. (void *) thr,
  42841. (long) num_stack_args,
  42842. (unsigned long) call_flags,
  42843. (long) ((call_flags & DUK_CALL_FLAG_IS_RESUME) != 0 ? 1 : 0),
  42844. (long) ((call_flags & DUK_CALL_FLAG_IS_TAILCALL) != 0 ? 1 : 0),
  42845. (long) idx_func,
  42846. (long) idx_args,
  42847. (long) entry_valstack_bottom_index));
  42848. if (idx_func < 0 || idx_args < 0) {
  42849. /* XXX: assert? compiler is responsible for this never happening */
  42850. DUK_ERROR(thr, DUK_ERR_API_ERROR, DUK_STR_INVALID_CALL_ARGS);
  42851. }
  42852. /*
  42853. * Check the function type, handle bound function chains, and prepare
  42854. * parameters for the rest of the call handling. Also figure out the
  42855. * effective 'this' binding, which replaces the current value at
  42856. * idx_func + 1.
  42857. *
  42858. * If the target function is a 'bound' one, follow the chain of 'bound'
  42859. * functions until a non-bound function is found. During this process,
  42860. * bound arguments are 'prepended' to existing ones, and the "this"
  42861. * binding is overridden. See E5 Section 15.3.4.5.1.
  42862. *
  42863. * If the final target function cannot be handled by an ecma-to-ecma
  42864. * call, return to the caller with a return value indicating this case.
  42865. * The bound chain is resolved and the caller can resume with a plain
  42866. * function call.
  42867. */
  42868. func = duk__nonbound_func_lookup(ctx, idx_func, &num_stack_args, &tv_func, call_flags);
  42869. if (func == NULL || !DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  42870. DUK_DDD(DUK_DDDPRINT("final target is a lightfunc/nativefunc, cannot do ecma-to-ecma call"));
  42871. return 0;
  42872. }
  42873. /* XXX: tv_func is not actually needed */
  42874. DUK_ASSERT(func != NULL);
  42875. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func));
  42876. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(func));
  42877. duk__coerce_effective_this_binding(thr, func, idx_func + 1);
  42878. DUK_DDD(DUK_DDDPRINT("effective 'this' binding is: %!T",
  42879. duk_get_tval(ctx, idx_func + 1)));
  42880. nargs = ((duk_hcompiledfunction *) func)->nargs;
  42881. nregs = ((duk_hcompiledfunction *) func)->nregs;
  42882. DUK_ASSERT(nregs >= nargs);
  42883. /* [ ... func this arg1 ... argN ] */
  42884. /*
  42885. * Preliminary activation record and valstack manipulation.
  42886. * The concrete actions depend on whether the we're dealing
  42887. * with a tailcall (reuse an existing activation), a resume,
  42888. * or a normal call.
  42889. *
  42890. * The basic actions, in varying order, are:
  42891. *
  42892. * - Check stack size for call handling
  42893. * - Grow call stack if necessary (non-tail-calls)
  42894. * - Update current activation (idx_retval) if necessary
  42895. * (non-tail, non-resume calls)
  42896. * - Move start of args (idx_args) to valstack bottom
  42897. * (tail calls)
  42898. *
  42899. * Don't touch valstack_bottom or valstack_top yet so that Duktape API
  42900. * calls work normally.
  42901. */
  42902. /* XXX: some overlapping code; cleanup */
  42903. use_tailcall = call_flags & DUK_CALL_FLAG_IS_TAILCALL;
  42904. #if !defined(DUK_USE_TAILCALL)
  42905. DUK_ASSERT(use_tailcall == 0); /* compiler ensures this */
  42906. #endif
  42907. if (use_tailcall) {
  42908. /* tailcall cannot be flagged to resume calls, and a
  42909. * previous frame must exist
  42910. */
  42911. DUK_ASSERT(thr->callstack_top >= 1);
  42912. DUK_ASSERT((call_flags & DUK_CALL_FLAG_IS_RESUME) == 0);
  42913. act = thr->callstack + thr->callstack_top - 1;
  42914. if (act->flags & DUK_ACT_FLAG_PREVENT_YIELD) {
  42915. /* See: test-bug-tailcall-preventyield-assert.c. */
  42916. DUK_DDD(DUK_DDDPRINT("tailcall prevented by current activation having DUK_ACT_FLAG_PREVENTYIELD"));
  42917. use_tailcall = 0;
  42918. } else if (DUK_HOBJECT_HAS_NOTAIL(func)) {
  42919. DUK_D(DUK_DPRINT("tailcall prevented by function having a notail flag"));
  42920. use_tailcall = 0;
  42921. }
  42922. }
  42923. if (use_tailcall) {
  42924. duk_tval *tv1, *tv2;
  42925. duk_tval tv_tmp;
  42926. duk_size_t cs_index;
  42927. duk_int_t i_stk; /* must be signed for loop structure */
  42928. duk_idx_t i_arg;
  42929. /*
  42930. * Tailcall handling
  42931. *
  42932. * Although the callstack entry is reused, we need to explicitly unwind
  42933. * the current activation (or simulate an unwind). In particular, the
  42934. * current activation must be closed, otherwise something like
  42935. * test-bug-reduce-judofyr.js results. Also catchstack needs be unwound
  42936. * because there may be non-error-catching label entries in valid tailcalls.
  42937. */
  42938. DUK_DDD(DUK_DDDPRINT("is tailcall, reusing activation at callstack top, at index %ld",
  42939. (long) (thr->callstack_top - 1)));
  42940. /* 'act' already set above */
  42941. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func));
  42942. DUK_ASSERT(!DUK_HOBJECT_HAS_NATIVEFUNCTION(func));
  42943. DUK_ASSERT(DUK_HOBJECT_HAS_COMPILEDFUNCTION(func));
  42944. DUK_ASSERT((act->flags & DUK_ACT_FLAG_PREVENT_YIELD) == 0);
  42945. /* Unwind catchstack entries referring to the callstack entry we're reusing */
  42946. cs_index = thr->callstack_top - 1;
  42947. DUK_ASSERT(thr->catchstack_top <= DUK_INT_MAX); /* catchstack limits */
  42948. for (i_stk = (duk_int_t) (thr->catchstack_top - 1); i_stk >= 0; i_stk--) {
  42949. duk_catcher *cat = thr->catchstack + i_stk;
  42950. if (cat->callstack_index != cs_index) {
  42951. /* 'i' is the first entry we'll keep */
  42952. break;
  42953. }
  42954. }
  42955. duk_hthread_catchstack_unwind(thr, i_stk + 1);
  42956. /* Unwind the topmost callstack entry before reusing it */
  42957. DUK_ASSERT(thr->callstack_top > 0);
  42958. duk_hthread_callstack_unwind(thr, thr->callstack_top - 1);
  42959. /* Then reuse the unwound activation; callstack was not shrunk so there is always space */
  42960. thr->callstack_top++;
  42961. DUK_ASSERT(thr->callstack_top <= thr->callstack_size);
  42962. act = thr->callstack + thr->callstack_top - 1;
  42963. /* Start filling in the activation */
  42964. act->func = func; /* don't want an intermediate exposed state with func == NULL */
  42965. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  42966. act->prev_caller = NULL;
  42967. #endif
  42968. act->pc = 0; /* don't want an intermediate exposed state with invalid pc */
  42969. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  42970. act->prev_line = 0;
  42971. #endif
  42972. DUK_TVAL_SET_OBJECT(&act->tv_func, func); /* borrowed, no refcount */
  42973. #ifdef DUK_USE_REFERENCE_COUNTING
  42974. DUK_HOBJECT_INCREF(thr, func);
  42975. act = thr->callstack + thr->callstack_top - 1; /* side effects (currently none though) */
  42976. #endif
  42977. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  42978. #ifdef DUK_USE_TAILCALL
  42979. #error incorrect options: tailcalls enabled with function caller property
  42980. #endif
  42981. /* XXX: this doesn't actually work properly for tail calls, so
  42982. * tail calls are disabled when DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  42983. * is in use.
  42984. */
  42985. duk__update_func_caller_prop(thr, func);
  42986. act = thr->callstack + thr->callstack_top - 1;
  42987. #endif
  42988. act->flags = (DUK_HOBJECT_HAS_STRICT(func) ?
  42989. DUK_ACT_FLAG_STRICT | DUK_ACT_FLAG_TAILCALLED :
  42990. DUK_ACT_FLAG_TAILCALLED);
  42991. DUK_ASSERT(DUK_ACT_GET_FUNC(act) == func); /* already updated */
  42992. DUK_ASSERT(act->var_env == NULL); /* already NULLed (by unwind) */
  42993. DUK_ASSERT(act->lex_env == NULL); /* already NULLed (by unwind) */
  42994. DUK_ASSERT(act->pc == 0); /* already zeroed */
  42995. act->idx_bottom = entry_valstack_bottom_index; /* tail call -> reuse current "frame" */
  42996. DUK_ASSERT(nregs >= 0);
  42997. #if 0 /* topmost activation idx_retval is considered garbage, no need to init */
  42998. act->idx_retval = 0;
  42999. #endif
  43000. /*
  43001. * Manipulate valstack so that args are on the current bottom and the
  43002. * previous caller's 'this' binding (which is the value preceding the
  43003. * current bottom) is replaced with the new 'this' binding:
  43004. *
  43005. * [ ... this_old | (crud) func this_new arg1 ... argN ]
  43006. * --> [ ... this_new | arg1 ... argN ]
  43007. *
  43008. * For tailcalling to work properly, the valstack bottom must not grow
  43009. * here; otherwise crud would accumulate on the valstack.
  43010. */
  43011. tv1 = thr->valstack_bottom - 1;
  43012. tv2 = thr->valstack_bottom + idx_func + 1;
  43013. DUK_ASSERT(tv1 >= thr->valstack && tv1 < thr->valstack_top); /* tv1 is -below- valstack_bottom */
  43014. DUK_ASSERT(tv2 >= thr->valstack_bottom && tv2 < thr->valstack_top);
  43015. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  43016. DUK_TVAL_SET_TVAL(tv1, tv2);
  43017. DUK_TVAL_INCREF(thr, tv1);
  43018. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  43019. for (i_arg = 0; i_arg < idx_args; i_arg++) {
  43020. /* XXX: block removal API primitive */
  43021. /* Note: 'func' is popped from valstack here, but it is
  43022. * already reachable from the activation.
  43023. */
  43024. duk_remove(ctx, 0);
  43025. }
  43026. idx_func = 0; DUK_UNREF(idx_func); /* really 'not applicable' anymore, should not be referenced after this */
  43027. idx_args = 0;
  43028. /* [ ... this_new | arg1 ... argN ] */
  43029. } else {
  43030. DUK_DDD(DUK_DDDPRINT("not a tailcall, pushing a new activation to callstack, to index %ld",
  43031. (long) (thr->callstack_top)));
  43032. duk_hthread_callstack_grow(thr);
  43033. if (call_flags & DUK_CALL_FLAG_IS_RESUME) {
  43034. DUK_DDD(DUK_DDDPRINT("is resume -> no update to current activation (may not even exist)"));
  43035. } else {
  43036. DUK_DDD(DUK_DDDPRINT("update to current activation idx_retval"));
  43037. DUK_ASSERT(thr->callstack_top < thr->callstack_size);
  43038. DUK_ASSERT(thr->callstack_top >= 1);
  43039. act = thr->callstack + thr->callstack_top - 1;
  43040. DUK_ASSERT(DUK_ACT_GET_FUNC(act) != NULL);
  43041. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(act)));
  43042. act->idx_retval = entry_valstack_bottom_index + idx_func;
  43043. }
  43044. DUK_ASSERT(thr->callstack_top < thr->callstack_size);
  43045. act = thr->callstack + thr->callstack_top;
  43046. thr->callstack_top++;
  43047. DUK_ASSERT(thr->callstack_top <= thr->callstack_size);
  43048. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func));
  43049. DUK_ASSERT(!DUK_HOBJECT_HAS_NATIVEFUNCTION(func));
  43050. DUK_ASSERT(DUK_HOBJECT_HAS_COMPILEDFUNCTION(func));
  43051. act->flags = (DUK_HOBJECT_HAS_STRICT(func) ?
  43052. DUK_ACT_FLAG_STRICT :
  43053. 0);
  43054. act->func = func;
  43055. act->var_env = NULL;
  43056. act->lex_env = NULL;
  43057. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  43058. act->prev_caller = NULL;
  43059. #endif
  43060. act->pc = 0;
  43061. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  43062. act->prev_line = 0;
  43063. #endif
  43064. act->idx_bottom = entry_valstack_bottom_index + idx_args;
  43065. DUK_ASSERT(nregs >= 0);
  43066. #if 0 /* topmost activation idx_retval is considered garbage, no need to init */
  43067. act->idx_retval = 0;
  43068. #endif
  43069. DUK_TVAL_SET_OBJECT(&act->tv_func, func); /* borrowed, no refcount */
  43070. DUK_HOBJECT_INCREF(thr, func); /* act->func */
  43071. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  43072. duk__update_func_caller_prop(thr, func);
  43073. act = thr->callstack + thr->callstack_top - 1;
  43074. #endif
  43075. }
  43076. /* [... func this arg1 ... argN] (not tail call)
  43077. * [this | arg1 ... argN] (tail call)
  43078. *
  43079. * idx_args updated to match
  43080. */
  43081. /*
  43082. * Environment record creation and 'arguments' object creation.
  43083. * Named function expression name binding is handled by the
  43084. * compiler; the compiled function's parent env will contain
  43085. * the (immutable) binding already.
  43086. *
  43087. * Delayed creation (on demand) is handled in duk_js_var.c.
  43088. */
  43089. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func)); /* bound function chain has already been resolved */
  43090. if (!DUK_HOBJECT_HAS_NEWENV(func)) {
  43091. /* use existing env (e.g. for non-strict eval); cannot have
  43092. * an own 'arguments' object (but can refer to the existing one)
  43093. */
  43094. duk__handle_oldenv_for_call(thr, func, act);
  43095. DUK_ASSERT(act->lex_env != NULL);
  43096. DUK_ASSERT(act->var_env != NULL);
  43097. goto env_done;
  43098. }
  43099. DUK_ASSERT(DUK_HOBJECT_HAS_NEWENV(func));
  43100. if (!DUK_HOBJECT_HAS_CREATEARGS(func)) {
  43101. /* no need to create environment record now; leave as NULL */
  43102. DUK_ASSERT(act->lex_env == NULL);
  43103. DUK_ASSERT(act->var_env == NULL);
  43104. goto env_done;
  43105. }
  43106. /* third arg: absolute index (to entire valstack) of idx_bottom of new activation */
  43107. env = duk_create_activation_environment_record(thr, func, act->idx_bottom);
  43108. DUK_ASSERT(env != NULL);
  43109. /* [... arg1 ... argN envobj] */
  43110. /* original input stack before nargs/nregs handling must be
  43111. * intact for 'arguments' object
  43112. */
  43113. DUK_ASSERT(DUK_HOBJECT_HAS_CREATEARGS(func));
  43114. duk__handle_createargs_for_call(thr, func, env, num_stack_args);
  43115. /* [... arg1 ... argN envobj] */
  43116. act->lex_env = env;
  43117. act->var_env = env;
  43118. DUK_HOBJECT_INCREF(thr, act->lex_env);
  43119. DUK_HOBJECT_INCREF(thr, act->var_env);
  43120. duk_pop(ctx);
  43121. env_done:
  43122. /* [... arg1 ... argN] */
  43123. /*
  43124. * Setup value stack: clamp to 'nargs', fill up to 'nregs'
  43125. */
  43126. duk__adjust_valstack_and_top(thr,
  43127. num_stack_args,
  43128. idx_args,
  43129. nregs,
  43130. nargs,
  43131. func);
  43132. /*
  43133. * Shift to new valstack_bottom.
  43134. */
  43135. thr->valstack_bottom = thr->valstack_bottom + idx_args;
  43136. /* keep current valstack_top */
  43137. DUK_ASSERT(thr->valstack_bottom >= thr->valstack);
  43138. DUK_ASSERT(thr->valstack_top >= thr->valstack_bottom);
  43139. DUK_ASSERT(thr->valstack_end >= thr->valstack_top);
  43140. /*
  43141. * Return to bytecode executor, which will resume execution from
  43142. * the topmost activation.
  43143. */
  43144. return 1;
  43145. }
  43146. #line 1 "duk_js_compiler.c"
  43147. /*
  43148. * Ecmascript compiler.
  43149. *
  43150. * Parses an input string and generates a function template result.
  43151. * Compilation may happen in multiple contexts (global code, eval
  43152. * code, function code).
  43153. *
  43154. * The parser uses a traditional top-down recursive parsing for the
  43155. * statement level, and an operator precedence based top-down approach
  43156. * for the expression level. The attempt is to minimize the C stack
  43157. * depth. Bytecode is generated directly without an intermediate
  43158. * representation (tree), at the cost of needing two passes over each
  43159. * function.
  43160. *
  43161. * The top-down recursive parser functions are named "duk__parse_XXX".
  43162. *
  43163. * Recursion limits are in key functions to prevent arbitrary C recursion:
  43164. * function body parsing, statement parsing, and expression parsing.
  43165. *
  43166. * See doc/compiler.txt for discussion on the design.
  43167. *
  43168. * A few typing notes:
  43169. *
  43170. * - duk_regconst_t: unsigned, no marker value for "none"
  43171. * - duk_reg_t: signed, < 0 = none
  43172. * - PC values: duk_int_t, negative values used as markers
  43173. */
  43174. /* include removed: duk_internal.h */
  43175. /* if highest bit of a register number is set, it refers to a constant instead */
  43176. #define DUK__CONST_MARKER DUK_JS_CONST_MARKER
  43177. /* for array and object literals */
  43178. #define DUK__MAX_ARRAY_INIT_VALUES 20
  43179. #define DUK__MAX_OBJECT_INIT_PAIRS 10
  43180. /* XXX: hack, remove when const lookup is not O(n) */
  43181. #define DUK__GETCONST_MAX_CONSTS_CHECK 256
  43182. /* These limits are based on bytecode limits. Max temps is limited
  43183. * by duk_hcompiledfunction nargs/nregs fields being 16 bits.
  43184. */
  43185. #define DUK__MAX_CONSTS DUK_BC_BC_MAX
  43186. #define DUK__MAX_FUNCS DUK_BC_BC_MAX
  43187. #define DUK__MAX_TEMPS 0xffffL
  43188. #define DUK__RECURSION_INCREASE(comp_ctx,thr) do { \
  43189. DUK_DDD(DUK_DDDPRINT("RECURSION INCREASE: %s:%ld", (const char *) DUK_FILE_MACRO, (long) DUK_LINE_MACRO)); \
  43190. duk__recursion_increase((comp_ctx)); \
  43191. } while (0)
  43192. #define DUK__RECURSION_DECREASE(comp_ctx,thr) do { \
  43193. DUK_DDD(DUK_DDDPRINT("RECURSION DECREASE: %s:%ld", (const char *) DUK_FILE_MACRO, (long) DUK_LINE_MACRO)); \
  43194. duk__recursion_decrease((comp_ctx)); \
  43195. } while (0)
  43196. /* Value stack slot limits: these are quite approximate right now, and
  43197. * because they overlap in control flow, some could be eliminated.
  43198. */
  43199. #define DUK__COMPILE_ENTRY_SLOTS 8
  43200. #define DUK__FUNCTION_INIT_REQUIRE_SLOTS 16
  43201. #define DUK__FUNCTION_BODY_REQUIRE_SLOTS 16
  43202. #define DUK__PARSE_STATEMENTS_SLOTS 16
  43203. #define DUK__PARSE_EXPR_SLOTS 16
  43204. /* Temporary structure used to pass a stack allocated region through
  43205. * duk_safe_call().
  43206. */
  43207. typedef struct {
  43208. duk_small_uint_t flags;
  43209. duk_compiler_ctx comp_ctx_alloc;
  43210. duk_lexer_point lex_pt_alloc;
  43211. } duk__compiler_stkstate;
  43212. /*
  43213. * Prototypes
  43214. */
  43215. /* lexing */
  43216. DUK_LOCAL_DECL void duk__advance_helper(duk_compiler_ctx *comp_ctx, duk_small_int_t expect);
  43217. DUK_LOCAL_DECL void duk__advance_expect(duk_compiler_ctx *comp_ctx, duk_small_int_t expect);
  43218. DUK_LOCAL_DECL void duk__advance(duk_compiler_ctx *ctx);
  43219. /* function helpers */
  43220. DUK_LOCAL_DECL void duk__init_func_valstack_slots(duk_compiler_ctx *comp_ctx);
  43221. DUK_LOCAL_DECL void duk__reset_func_for_pass2(duk_compiler_ctx *comp_ctx);
  43222. DUK_LOCAL_DECL void duk__init_varmap_and_prologue_for_pass2(duk_compiler_ctx *comp_ctx, duk_reg_t *out_stmt_value_reg);
  43223. DUK_LOCAL_DECL void duk__convert_to_func_template(duk_compiler_ctx *comp_ctx, duk_bool_t force_no_namebind);
  43224. DUK_LOCAL_DECL duk_int_t duk__cleanup_varmap(duk_compiler_ctx *comp_ctx);
  43225. /* code emission */
  43226. DUK_LOCAL_DECL duk_int_t duk__get_current_pc(duk_compiler_ctx *comp_ctx);
  43227. DUK_LOCAL_DECL duk_compiler_instr *duk__get_instr_ptr(duk_compiler_ctx *comp_ctx, duk_int_t pc);
  43228. DUK_LOCAL_DECL void duk__emit(duk_compiler_ctx *comp_ctx, duk_instr_t ins);
  43229. #if 0 /* unused */
  43230. DUK_LOCAL_DECL void duk__emit_op_only(duk_compiler_ctx *comp_ctx, duk_small_uint_t op);
  43231. #endif
  43232. DUK_LOCAL_DECL void duk__emit_a_b_c(duk_compiler_ctx *comp_ctx, duk_small_uint_t op_flags, duk_regconst_t a, duk_regconst_t b, duk_regconst_t c);
  43233. DUK_LOCAL_DECL void duk__emit_a_b(duk_compiler_ctx *comp_ctx, duk_small_uint_t op_flags, duk_regconst_t a, duk_regconst_t b);
  43234. #if 0 /* unused */
  43235. DUK_LOCAL_DECL void duk__emit_a(duk_compiler_ctx *comp_ctx, duk_small_uint_t op_flags, duk_regconst_t a);
  43236. #endif
  43237. DUK_LOCAL_DECL void duk__emit_a_bc(duk_compiler_ctx *comp_ctx, duk_small_uint_t op_flags, duk_regconst_t a, duk_regconst_t bc);
  43238. DUK_LOCAL_DECL void duk__emit_abc(duk_compiler_ctx *comp_ctx, duk_small_uint_t op, duk_regconst_t abc);
  43239. DUK_LOCAL_DECL void duk__emit_extraop_b_c(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop_flags, duk_regconst_t b, duk_regconst_t c);
  43240. DUK_LOCAL_DECL void duk__emit_extraop_b(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop_flags, duk_regconst_t b);
  43241. DUK_LOCAL_DECL void duk__emit_extraop_bc(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop, duk_regconst_t bc);
  43242. DUK_LOCAL_DECL void duk__emit_extraop_only(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop_flags);
  43243. DUK_LOCAL_DECL void duk__emit_load_int32(duk_compiler_ctx *comp_ctx, duk_reg_t reg, duk_int32_t val);
  43244. DUK_LOCAL_DECL void duk__emit_load_int32_noshuffle(duk_compiler_ctx *comp_ctx, duk_reg_t reg, duk_int32_t val);
  43245. DUK_LOCAL_DECL void duk__emit_jump(duk_compiler_ctx *comp_ctx, duk_int_t target_pc);
  43246. DUK_LOCAL_DECL duk_int_t duk__emit_jump_empty(duk_compiler_ctx *comp_ctx);
  43247. DUK_LOCAL_DECL void duk__insert_jump_entry(duk_compiler_ctx *comp_ctx, duk_int_t jump_pc);
  43248. DUK_LOCAL_DECL void duk__patch_jump(duk_compiler_ctx *comp_ctx, duk_int_t jump_pc, duk_int_t target_pc);
  43249. DUK_LOCAL_DECL void duk__patch_jump_here(duk_compiler_ctx *comp_ctx, duk_int_t jump_pc);
  43250. DUK_LOCAL_DECL void duk__patch_trycatch(duk_compiler_ctx *comp_ctx, duk_int_t trycatch_pc, duk_regconst_t reg_catch, duk_regconst_t const_varname, duk_small_uint_t flags);
  43251. DUK_LOCAL_DECL void duk__emit_if_false_skip(duk_compiler_ctx *comp_ctx, duk_regconst_t regconst);
  43252. DUK_LOCAL_DECL void duk__emit_if_true_skip(duk_compiler_ctx *comp_ctx, duk_regconst_t regconst);
  43253. DUK_LOCAL_DECL void duk__emit_invalid(duk_compiler_ctx *comp_ctx);
  43254. /* ivalue/ispec helpers */
  43255. DUK_LOCAL_DECL void duk__copy_ispec(duk_compiler_ctx *comp_ctx, duk_ispec *src, duk_ispec *dst);
  43256. DUK_LOCAL_DECL void duk__copy_ivalue(duk_compiler_ctx *comp_ctx, duk_ivalue *src, duk_ivalue *dst);
  43257. DUK_LOCAL_DECL duk_bool_t duk__is_whole_get_int32(duk_double_t x, duk_int32_t *ival);
  43258. DUK_LOCAL_DECL duk_reg_t duk__alloctemps(duk_compiler_ctx *comp_ctx, duk_small_int_t num);
  43259. DUK_LOCAL_DECL duk_reg_t duk__alloctemp(duk_compiler_ctx *comp_ctx);
  43260. DUK_LOCAL_DECL void duk__settemp_checkmax(duk_compiler_ctx *comp_ctx, duk_reg_t temp_next);
  43261. DUK_LOCAL_DECL duk_regconst_t duk__getconst(duk_compiler_ctx *comp_ctx);
  43262. DUK_LOCAL_DECL
  43263. duk_regconst_t duk__ispec_toregconst_raw(duk_compiler_ctx *comp_ctx,
  43264. duk_ispec *x,
  43265. duk_reg_t forced_reg,
  43266. duk_small_uint_t flags);
  43267. DUK_LOCAL_DECL void duk__ispec_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ispec *x, duk_reg_t forced_reg);
  43268. DUK_LOCAL_DECL void duk__ivalue_toplain_raw(duk_compiler_ctx *comp_ctx, duk_ivalue *x, duk_reg_t forced_reg);
  43269. DUK_LOCAL_DECL void duk__ivalue_toplain(duk_compiler_ctx *comp_ctx, duk_ivalue *x);
  43270. DUK_LOCAL_DECL void duk__ivalue_toplain_ignore(duk_compiler_ctx *comp_ctx, duk_ivalue *x);
  43271. DUK_LOCAL_DECL
  43272. duk_regconst_t duk__ivalue_toregconst_raw(duk_compiler_ctx *comp_ctx,
  43273. duk_ivalue *x,
  43274. duk_reg_t forced_reg,
  43275. duk_small_uint_t flags);
  43276. DUK_LOCAL_DECL duk_reg_t duk__ivalue_toreg(duk_compiler_ctx *comp_ctx, duk_ivalue *x);
  43277. #if 0 /* unused */
  43278. DUK_LOCAL_DECL duk_reg_t duk__ivalue_totempreg(duk_compiler_ctx *comp_ctx, duk_ivalue *x);
  43279. #endif
  43280. DUK_LOCAL_DECL void duk__ivalue_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ivalue *x, duk_int_t forced_reg);
  43281. DUK_LOCAL_DECL duk_regconst_t duk__ivalue_toregconst(duk_compiler_ctx *comp_ctx, duk_ivalue *x);
  43282. /* identifier handling */
  43283. DUK_LOCAL_DECL duk_reg_t duk__lookup_active_register_binding(duk_compiler_ctx *comp_ctx);
  43284. DUK_LOCAL_DECL duk_bool_t duk__lookup_lhs(duk_compiler_ctx *ctx, duk_reg_t *out_reg_varbind, duk_regconst_t *out_rc_varname);
  43285. /* label handling */
  43286. DUK_LOCAL_DECL void duk__add_label(duk_compiler_ctx *comp_ctx, duk_hstring *h_label, duk_int_t pc_label, duk_int_t label_id);
  43287. DUK_LOCAL_DECL void duk__update_label_flags(duk_compiler_ctx *comp_ctx, duk_int_t label_id, duk_small_uint_t flags);
  43288. DUK_LOCAL_DECL void duk__lookup_active_label(duk_compiler_ctx *comp_ctx, duk_hstring *h_label, duk_bool_t is_break, duk_int_t *out_label_id, duk_int_t *out_label_catch_depth, duk_int_t *out_label_pc, duk_bool_t *out_is_closest);
  43289. DUK_LOCAL_DECL void duk__reset_labels_to_length(duk_compiler_ctx *comp_ctx, duk_int_t len);
  43290. /* top-down expression parser */
  43291. DUK_LOCAL_DECL void duk__expr_nud(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43292. DUK_LOCAL_DECL void duk__expr_led(duk_compiler_ctx *comp_ctx, duk_ivalue *left, duk_ivalue *res);
  43293. DUK_LOCAL_DECL duk_small_uint_t duk__expr_lbp(duk_compiler_ctx *comp_ctx);
  43294. DUK_LOCAL_DECL duk_bool_t duk__expr_is_empty(duk_compiler_ctx *comp_ctx);
  43295. /* exprtop is the top level variant which resets nud/led counts */
  43296. DUK_LOCAL_DECL void duk__expr(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43297. DUK_LOCAL_DECL void duk__exprtop(duk_compiler_ctx *ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43298. /* convenience helpers */
  43299. DUK_LOCAL_DECL duk_reg_t duk__expr_toreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43300. #if 0 /* unused */
  43301. DUK_LOCAL_DECL duk_reg_t duk__expr_totempreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43302. #endif
  43303. DUK_LOCAL_DECL void duk__expr_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags, duk_reg_t forced_reg);
  43304. DUK_LOCAL_DECL duk_regconst_t duk__expr_toregconst(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43305. DUK_LOCAL_DECL void duk__expr_toplain(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43306. DUK_LOCAL_DECL void duk__expr_toplain_ignore(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43307. DUK_LOCAL_DECL duk_reg_t duk__exprtop_toreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43308. #if 0 /* unused */
  43309. DUK_LOCAL_DECL duk_reg_t duk__exprtop_totempreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43310. DUK_LOCAL_DECL void duk__exprtop_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags, duk_reg_t forced_reg);
  43311. #endif
  43312. DUK_LOCAL_DECL duk_regconst_t duk__exprtop_toregconst(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43313. #if 0 /* unused */
  43314. DUK_LOCAL_DECL void duk__exprtop_toplain_ignore(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags);
  43315. #endif
  43316. /* expression parsing helpers */
  43317. DUK_LOCAL_DECL duk_int_t duk__parse_arguments(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43318. DUK_LOCAL_DECL void duk__nud_array_literal(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43319. DUK_LOCAL_DECL void duk__nud_object_literal(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43320. DUK_LOCAL_DECL duk_bool_t duk__nud_object_literal_key_check(duk_compiler_ctx *comp_ctx, duk_small_uint_t new_key_flags);
  43321. /* statement parsing */
  43322. DUK_LOCAL_DECL void duk__parse_var_decl(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t expr_flags, duk_reg_t *out_reg_varbind, duk_regconst_t *out_rc_varname);
  43323. DUK_LOCAL_DECL void duk__parse_var_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43324. DUK_LOCAL_DECL void duk__parse_for_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site);
  43325. DUK_LOCAL_DECL void duk__parse_switch_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site);
  43326. DUK_LOCAL_DECL void duk__parse_if_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43327. DUK_LOCAL_DECL void duk__parse_do_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site);
  43328. DUK_LOCAL_DECL void duk__parse_while_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site);
  43329. DUK_LOCAL_DECL void duk__parse_break_or_continue_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43330. DUK_LOCAL_DECL void duk__parse_return_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43331. DUK_LOCAL_DECL void duk__parse_throw_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43332. DUK_LOCAL_DECL void duk__parse_try_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43333. DUK_LOCAL_DECL void duk__parse_with_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res);
  43334. DUK_LOCAL_DECL void duk__parse_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_bool_t allow_source_elem);
  43335. DUK_LOCAL_DECL duk_int_t duk__stmt_label_site(duk_compiler_ctx *comp_ctx, duk_int_t label_id);
  43336. DUK_LOCAL_DECL void duk__parse_stmts(duk_compiler_ctx *comp_ctx, duk_bool_t allow_source_elem, duk_bool_t expect_eof);
  43337. DUK_LOCAL_DECL void duk__parse_func_body(duk_compiler_ctx *comp_ctx, duk_bool_t expect_eof, duk_bool_t implicit_return_value, duk_small_int_t expect_token);
  43338. DUK_LOCAL_DECL void duk__parse_func_formals(duk_compiler_ctx *comp_ctx);
  43339. DUK_LOCAL_DECL void duk__parse_func_like_raw(duk_compiler_ctx *comp_ctx, duk_bool_t is_decl, duk_bool_t is_setget);
  43340. DUK_LOCAL_DECL duk_int_t duk__parse_func_like_fnum(duk_compiler_ctx *comp_ctx, duk_bool_t is_decl, duk_bool_t is_setget);
  43341. /*
  43342. * Parser control values for tokens. The token table is ordered by the
  43343. * DUK_TOK_XXX defines.
  43344. *
  43345. * The binding powers are for lbp() use (i.e. for use in led() context).
  43346. * Binding powers are positive for typing convenience, and bits at the
  43347. * top should be reserved for flags. Binding power step must be higher
  43348. * than 1 so that binding power "lbp - 1" can be used for right associative
  43349. * operators. Currently a step of 2 is used (which frees one more bit for
  43350. * flags).
  43351. */
  43352. /* XXX: actually single step levels would work just fine, clean up */
  43353. /* binding power "levels" (see doc/compiler.txt) */
  43354. #define DUK__BP_INVALID 0 /* always terminates led() */
  43355. #define DUK__BP_EOF 2
  43356. #define DUK__BP_CLOSING 4 /* token closes expression, e.g. ')', ']' */
  43357. #define DUK__BP_FOR_EXPR DUK__BP_CLOSING /* bp to use when parsing a top level Expression */
  43358. #define DUK__BP_COMMA 6
  43359. #define DUK__BP_ASSIGNMENT 8
  43360. #define DUK__BP_CONDITIONAL 10
  43361. #define DUK__BP_LOR 12
  43362. #define DUK__BP_LAND 14
  43363. #define DUK__BP_BOR 16
  43364. #define DUK__BP_BXOR 18
  43365. #define DUK__BP_BAND 20
  43366. #define DUK__BP_EQUALITY 22
  43367. #define DUK__BP_RELATIONAL 24
  43368. #define DUK__BP_SHIFT 26
  43369. #define DUK__BP_ADDITIVE 28
  43370. #define DUK__BP_MULTIPLICATIVE 30
  43371. #define DUK__BP_POSTFIX 32
  43372. #define DUK__BP_CALL 34
  43373. #define DUK__BP_MEMBER 36
  43374. #define DUK__TOKEN_LBP_BP_MASK 0x1f
  43375. #define DUK__TOKEN_LBP_FLAG_NO_REGEXP (1 << 5) /* regexp literal must not follow this token */
  43376. #define DUK__TOKEN_LBP_FLAG_TERMINATES (1 << 6) /* terminates expression; e.g. post-increment/-decrement */
  43377. #define DUK__TOKEN_LBP_FLAG_UNUSED (1 << 7) /* spare */
  43378. #define DUK__TOKEN_LBP_GET_BP(x) ((duk_small_uint_t) (((x) & DUK__TOKEN_LBP_BP_MASK) * 2))
  43379. #define DUK__MK_LBP(bp) ((bp) >> 1) /* bp is assumed to be even */
  43380. #define DUK__MK_LBP_FLAGS(bp,flags) (((bp) >> 1) | (flags))
  43381. DUK_LOCAL const duk_uint8_t duk__token_lbp[] = {
  43382. DUK__MK_LBP(DUK__BP_EOF), /* DUK_TOK_EOF */
  43383. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_LINETERM */
  43384. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_COMMENT */
  43385. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_IDENTIFIER */
  43386. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_BREAK */
  43387. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_CASE */
  43388. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_CATCH */
  43389. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_CONTINUE */
  43390. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_DEBUGGER */
  43391. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_DEFAULT */
  43392. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_DELETE */
  43393. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_DO */
  43394. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_ELSE */
  43395. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_FINALLY */
  43396. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_FOR */
  43397. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_FUNCTION */
  43398. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_IF */
  43399. DUK__MK_LBP(DUK__BP_RELATIONAL), /* DUK_TOK_IN */
  43400. DUK__MK_LBP(DUK__BP_RELATIONAL), /* DUK_TOK_INSTANCEOF */
  43401. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_NEW */
  43402. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_RETURN */
  43403. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_SWITCH */
  43404. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_THIS */
  43405. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_THROW */
  43406. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_TRY */
  43407. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_TYPEOF */
  43408. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_VAR */
  43409. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_VOID */
  43410. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_WHILE */
  43411. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_WITH */
  43412. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_CLASS */
  43413. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_CONST */
  43414. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_ENUM */
  43415. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_EXPORT */
  43416. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_EXTENDS */
  43417. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_IMPORT */
  43418. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_SUPER */
  43419. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_NULL */
  43420. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_TRUE */
  43421. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_FALSE */
  43422. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_GET */
  43423. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_SET */
  43424. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_IMPLEMENTS */
  43425. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_INTERFACE */
  43426. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_LET */
  43427. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_PACKAGE */
  43428. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_PRIVATE */
  43429. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_PROTECTED */
  43430. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_PUBLIC */
  43431. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_STATIC */
  43432. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_YIELD */
  43433. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_LCURLY */
  43434. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_RCURLY */
  43435. DUK__MK_LBP(DUK__BP_MEMBER), /* DUK_TOK_LBRACKET */
  43436. DUK__MK_LBP_FLAGS(DUK__BP_CLOSING, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_RBRACKET */
  43437. DUK__MK_LBP(DUK__BP_CALL), /* DUK_TOK_LPAREN */
  43438. DUK__MK_LBP_FLAGS(DUK__BP_CLOSING, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_RPAREN */
  43439. DUK__MK_LBP(DUK__BP_MEMBER), /* DUK_TOK_PERIOD */
  43440. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_SEMICOLON */
  43441. DUK__MK_LBP(DUK__BP_COMMA), /* DUK_TOK_COMMA */
  43442. DUK__MK_LBP(DUK__BP_RELATIONAL), /* DUK_TOK_LT */
  43443. DUK__MK_LBP(DUK__BP_RELATIONAL), /* DUK_TOK_GT */
  43444. DUK__MK_LBP(DUK__BP_RELATIONAL), /* DUK_TOK_LE */
  43445. DUK__MK_LBP(DUK__BP_RELATIONAL), /* DUK_TOK_GE */
  43446. DUK__MK_LBP(DUK__BP_EQUALITY), /* DUK_TOK_EQ */
  43447. DUK__MK_LBP(DUK__BP_EQUALITY), /* DUK_TOK_NEQ */
  43448. DUK__MK_LBP(DUK__BP_EQUALITY), /* DUK_TOK_SEQ */
  43449. DUK__MK_LBP(DUK__BP_EQUALITY), /* DUK_TOK_SNEQ */
  43450. DUK__MK_LBP(DUK__BP_ADDITIVE), /* DUK_TOK_ADD */
  43451. DUK__MK_LBP(DUK__BP_ADDITIVE), /* DUK_TOK_SUB */
  43452. DUK__MK_LBP(DUK__BP_MULTIPLICATIVE), /* DUK_TOK_MUL */
  43453. DUK__MK_LBP(DUK__BP_MULTIPLICATIVE), /* DUK_TOK_DIV */
  43454. DUK__MK_LBP(DUK__BP_MULTIPLICATIVE), /* DUK_TOK_MOD */
  43455. DUK__MK_LBP(DUK__BP_POSTFIX), /* DUK_TOK_INCREMENT */
  43456. DUK__MK_LBP(DUK__BP_POSTFIX), /* DUK_TOK_DECREMENT */
  43457. DUK__MK_LBP(DUK__BP_SHIFT), /* DUK_TOK_ALSHIFT */
  43458. DUK__MK_LBP(DUK__BP_SHIFT), /* DUK_TOK_ARSHIFT */
  43459. DUK__MK_LBP(DUK__BP_SHIFT), /* DUK_TOK_RSHIFT */
  43460. DUK__MK_LBP(DUK__BP_BAND), /* DUK_TOK_BAND */
  43461. DUK__MK_LBP(DUK__BP_BOR), /* DUK_TOK_BOR */
  43462. DUK__MK_LBP(DUK__BP_BXOR), /* DUK_TOK_BXOR */
  43463. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_LNOT */
  43464. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_BNOT */
  43465. DUK__MK_LBP(DUK__BP_LAND), /* DUK_TOK_LAND */
  43466. DUK__MK_LBP(DUK__BP_LOR), /* DUK_TOK_LOR */
  43467. DUK__MK_LBP(DUK__BP_CONDITIONAL), /* DUK_TOK_QUESTION */
  43468. DUK__MK_LBP(DUK__BP_INVALID), /* DUK_TOK_COLON */
  43469. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_EQUALSIGN */
  43470. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_ADD_EQ */
  43471. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_SUB_EQ */
  43472. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_MUL_EQ */
  43473. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_DIV_EQ */
  43474. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_MOD_EQ */
  43475. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_ALSHIFT_EQ */
  43476. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_ARSHIFT_EQ */
  43477. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_RSHIFT_EQ */
  43478. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_BAND_EQ */
  43479. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_BOR_EQ */
  43480. DUK__MK_LBP(DUK__BP_ASSIGNMENT), /* DUK_TOK_BXOR_EQ */
  43481. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_NUMBER */
  43482. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_STRING */
  43483. DUK__MK_LBP_FLAGS(DUK__BP_INVALID, DUK__TOKEN_LBP_FLAG_NO_REGEXP), /* DUK_TOK_REGEXP */
  43484. };
  43485. /*
  43486. * Misc helpers
  43487. */
  43488. DUK_LOCAL void duk__recursion_increase(duk_compiler_ctx *comp_ctx) {
  43489. DUK_ASSERT(comp_ctx != NULL);
  43490. DUK_ASSERT(comp_ctx->recursion_depth >= 0);
  43491. if (comp_ctx->recursion_depth >= comp_ctx->recursion_limit) {
  43492. DUK_ERROR(comp_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_COMPILER_RECURSION_LIMIT);
  43493. }
  43494. comp_ctx->recursion_depth++;
  43495. }
  43496. DUK_LOCAL void duk__recursion_decrease(duk_compiler_ctx *comp_ctx) {
  43497. DUK_ASSERT(comp_ctx != NULL);
  43498. DUK_ASSERT(comp_ctx->recursion_depth > 0);
  43499. comp_ctx->recursion_depth--;
  43500. }
  43501. DUK_LOCAL duk_bool_t duk__hstring_is_eval_or_arguments(duk_compiler_ctx *comp_ctx, duk_hstring *h) {
  43502. DUK_UNREF(comp_ctx);
  43503. DUK_ASSERT(h != NULL);
  43504. return DUK_HSTRING_HAS_EVAL_OR_ARGUMENTS(h);
  43505. }
  43506. DUK_LOCAL duk_bool_t duk__hstring_is_eval_or_arguments_in_strict_mode(duk_compiler_ctx *comp_ctx, duk_hstring *h) {
  43507. DUK_ASSERT(h != NULL);
  43508. return (comp_ctx->curr_func.is_strict &&
  43509. DUK_HSTRING_HAS_EVAL_OR_ARGUMENTS(h));
  43510. }
  43511. /*
  43512. * Parser duk__advance() token eating functions
  43513. */
  43514. /* XXX: valstack handling is awkward. Add a valstack helper which
  43515. * avoids dup():ing; valstack_copy(src, dst)?
  43516. */
  43517. DUK_LOCAL void duk__advance_helper(duk_compiler_ctx *comp_ctx, duk_small_int_t expect) {
  43518. duk_hthread *thr = comp_ctx->thr;
  43519. duk_context *ctx = (duk_context *) thr;
  43520. duk_bool_t regexp;
  43521. DUK_ASSERT(comp_ctx->curr_token.t >= 0 && comp_ctx->curr_token.t <= DUK_TOK_MAXVAL); /* MAXVAL is inclusive */
  43522. /*
  43523. * Use current token to decide whether a RegExp can follow.
  43524. *
  43525. * We can use either 't' or 't_nores'; the latter would not
  43526. * recognize keywords. Some keywords can be followed by a
  43527. * RegExp (e.g. "return"), so using 't' is better. This is
  43528. * not trivial, see doc/compiler.txt.
  43529. */
  43530. regexp = 1;
  43531. if (duk__token_lbp[comp_ctx->curr_token.t] & DUK__TOKEN_LBP_FLAG_NO_REGEXP) {
  43532. regexp = 0;
  43533. }
  43534. if (comp_ctx->curr_func.reject_regexp_in_adv) {
  43535. comp_ctx->curr_func.reject_regexp_in_adv = 0;
  43536. regexp = 0;
  43537. }
  43538. if (expect >= 0 && comp_ctx->curr_token.t != expect) {
  43539. DUK_D(DUK_DPRINT("parse error: expect=%ld, got=%ld",
  43540. (long) expect, (long) comp_ctx->curr_token.t));
  43541. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_PARSE_ERROR);
  43542. }
  43543. /* make current token the previous; need to fiddle with valstack "backing store" */
  43544. DUK_MEMCPY(&comp_ctx->prev_token, &comp_ctx->curr_token, sizeof(duk_token));
  43545. duk_copy(ctx, comp_ctx->tok11_idx, comp_ctx->tok21_idx);
  43546. duk_copy(ctx, comp_ctx->tok12_idx, comp_ctx->tok22_idx);
  43547. /* parse new token */
  43548. duk_lexer_parse_js_input_element(&comp_ctx->lex,
  43549. &comp_ctx->curr_token,
  43550. comp_ctx->curr_func.is_strict,
  43551. regexp);
  43552. DUK_DDD(DUK_DDDPRINT("advance: curr: tok=%ld/%ld,%ld,term=%ld,%!T,%!T "
  43553. "prev: tok=%ld/%ld,%ld,term=%ld,%!T,%!T",
  43554. (long) comp_ctx->curr_token.t,
  43555. (long) comp_ctx->curr_token.t_nores,
  43556. (long) comp_ctx->curr_token.start_line,
  43557. (long) comp_ctx->curr_token.lineterm,
  43558. (duk_tval *) duk_get_tval(ctx, comp_ctx->tok11_idx),
  43559. (duk_tval *) duk_get_tval(ctx, comp_ctx->tok12_idx),
  43560. (long) comp_ctx->prev_token.t,
  43561. (long) comp_ctx->prev_token.t_nores,
  43562. (long) comp_ctx->prev_token.start_line,
  43563. (long) comp_ctx->prev_token.lineterm,
  43564. (duk_tval *) duk_get_tval(ctx, comp_ctx->tok21_idx),
  43565. (duk_tval *) duk_get_tval(ctx, comp_ctx->tok22_idx)));
  43566. }
  43567. /* advance, expecting current token to be a specific token; parse next token in regexp context */
  43568. DUK_LOCAL void duk__advance_expect(duk_compiler_ctx *comp_ctx, duk_small_int_t expect) {
  43569. duk__advance_helper(comp_ctx, expect);
  43570. }
  43571. /* advance, whatever the current token is; parse next token in regexp context */
  43572. DUK_LOCAL void duk__advance(duk_compiler_ctx *comp_ctx) {
  43573. duk__advance_helper(comp_ctx, -1);
  43574. }
  43575. /*
  43576. * Helpers for duk_compiler_func.
  43577. */
  43578. /* init function state: inits valstack allocations */
  43579. DUK_LOCAL void duk__init_func_valstack_slots(duk_compiler_ctx *comp_ctx) {
  43580. duk_compiler_func *func = &comp_ctx->curr_func;
  43581. duk_hthread *thr = comp_ctx->thr;
  43582. duk_context *ctx = (duk_context *) thr;
  43583. duk_idx_t entry_top;
  43584. entry_top = duk_get_top(ctx);
  43585. DUK_MEMZERO(func, sizeof(*func)); /* intentional overlap with earlier memzero */
  43586. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  43587. func->h_name = NULL;
  43588. func->h_code = NULL;
  43589. func->h_consts = NULL;
  43590. func->h_funcs = NULL;
  43591. func->h_decls = NULL;
  43592. func->h_labelnames = NULL;
  43593. func->h_labelinfos = NULL;
  43594. func->h_argnames = NULL;
  43595. func->h_varmap = NULL;
  43596. #endif
  43597. duk_require_stack(ctx, DUK__FUNCTION_INIT_REQUIRE_SLOTS);
  43598. /* XXX: getter for dynamic buffer */
  43599. duk_push_dynamic_buffer(ctx, 0);
  43600. func->code_idx = entry_top + 0;
  43601. func->h_code = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, entry_top + 0);
  43602. DUK_ASSERT(func->h_code != NULL);
  43603. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(func->h_code));
  43604. duk_push_array(ctx);
  43605. func->consts_idx = entry_top + 1;
  43606. func->h_consts = duk_get_hobject(ctx, entry_top + 1);
  43607. DUK_ASSERT(func->h_consts != NULL);
  43608. duk_push_array(ctx);
  43609. func->funcs_idx = entry_top + 2;
  43610. func->h_funcs = duk_get_hobject(ctx, entry_top + 2);
  43611. DUK_ASSERT(func->h_funcs != NULL);
  43612. DUK_ASSERT(func->fnum_next == 0);
  43613. duk_push_array(ctx);
  43614. func->decls_idx = entry_top + 3;
  43615. func->h_decls = duk_get_hobject(ctx, entry_top + 3);
  43616. DUK_ASSERT(func->h_decls != NULL);
  43617. duk_push_array(ctx);
  43618. func->labelnames_idx = entry_top + 4;
  43619. func->h_labelnames = duk_get_hobject(ctx, entry_top + 4);
  43620. DUK_ASSERT(func->h_labelnames != NULL);
  43621. duk_push_dynamic_buffer(ctx, 0);
  43622. func->labelinfos_idx = entry_top + 5;
  43623. func->h_labelinfos = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, entry_top + 5);
  43624. DUK_ASSERT(func->h_labelinfos != NULL);
  43625. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(func->h_labelinfos));
  43626. duk_push_array(ctx);
  43627. func->argnames_idx = entry_top + 6;
  43628. func->h_argnames = duk_get_hobject(ctx, entry_top + 6);
  43629. DUK_ASSERT(func->h_argnames != NULL);
  43630. duk_push_object_internal(ctx);
  43631. func->varmap_idx = entry_top + 7;
  43632. func->h_varmap = duk_get_hobject(ctx, entry_top + 7);
  43633. DUK_ASSERT(func->h_varmap != NULL);
  43634. }
  43635. /* reset function state (prepare for pass 2) */
  43636. DUK_LOCAL void duk__reset_func_for_pass2(duk_compiler_ctx *comp_ctx) {
  43637. duk_compiler_func *func = &comp_ctx->curr_func;
  43638. duk_hthread *thr = comp_ctx->thr;
  43639. duk_context *ctx = (duk_context *) thr;
  43640. /* XXX: reset buffers while keeping existing spare */
  43641. duk_hbuffer_reset(thr, func->h_code);
  43642. duk_hobject_set_length_zero(thr, func->h_consts);
  43643. /* keep func->h_funcs; inner functions are not reparsed to avoid O(depth^2) parsing */
  43644. func->fnum_next = 0;
  43645. /* duk_hobject_set_length_zero(thr, func->h_funcs); */
  43646. duk_hobject_set_length_zero(thr, func->h_labelnames);
  43647. duk_hbuffer_reset(thr, func->h_labelinfos);
  43648. /* keep func->h_argnames; it is fixed for all passes */
  43649. /* truncated in case pass 3 needed */
  43650. duk_push_object_internal(ctx);
  43651. duk_replace(ctx, func->varmap_idx);
  43652. func->h_varmap = duk_get_hobject(ctx, func->varmap_idx);
  43653. DUK_ASSERT(func->h_varmap != NULL);
  43654. }
  43655. /* cleanup varmap from any null entries, compact it, etc; returns number
  43656. * of final entries after cleanup.
  43657. */
  43658. DUK_LOCAL duk_int_t duk__cleanup_varmap(duk_compiler_ctx *comp_ctx) {
  43659. duk_hthread *thr = comp_ctx->thr;
  43660. duk_context *ctx = (duk_context *) thr;
  43661. duk_hobject *h_varmap;
  43662. duk_hstring *h_key;
  43663. duk_tval *tv;
  43664. duk_uint32_t i, e_next;
  43665. duk_int_t ret;
  43666. /* [ ... varmap ] */
  43667. h_varmap = duk_get_hobject(ctx, -1);
  43668. DUK_ASSERT(h_varmap != NULL);
  43669. ret = 0;
  43670. e_next = DUK_HOBJECT_GET_ENEXT(h_varmap);
  43671. for (i = 0; i < e_next; i++) {
  43672. h_key = DUK_HOBJECT_E_GET_KEY(thr->heap, h_varmap, i);
  43673. if (!h_key) {
  43674. continue;
  43675. }
  43676. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, h_varmap, i));
  43677. /* The entries can either be register numbers or 'null' values.
  43678. * Thus, no need to DECREF them and get side effects. DECREF'ing
  43679. * the keys (strings) can cause memory to be freed but no side
  43680. * effects as strings don't have finalizers. This is why we can
  43681. * rely on the object properties not changing from underneath us.
  43682. */
  43683. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, h_varmap, i);
  43684. if (!DUK_TVAL_IS_NUMBER(tv)) {
  43685. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv));
  43686. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  43687. DUK_HOBJECT_E_SET_KEY(thr->heap, h_varmap, i, NULL);
  43688. DUK_HSTRING_DECREF(thr, h_key);
  43689. } else {
  43690. ret++;
  43691. }
  43692. }
  43693. duk_compact(ctx, -1);
  43694. return ret;
  43695. }
  43696. /* convert duk_compiler_func into a function template, leaving the result
  43697. * on top of stack.
  43698. */
  43699. /* XXX: awkward and bloated asm -- use faster internal accesses */
  43700. DUK_LOCAL void duk__convert_to_func_template(duk_compiler_ctx *comp_ctx, duk_bool_t force_no_namebind) {
  43701. duk_compiler_func *func = &comp_ctx->curr_func;
  43702. duk_hthread *thr = comp_ctx->thr;
  43703. duk_context *ctx = (duk_context *) thr;
  43704. duk_hcompiledfunction *h_res;
  43705. duk_hbuffer_fixed *h_data;
  43706. duk_size_t consts_count;
  43707. duk_size_t funcs_count;
  43708. duk_size_t code_count;
  43709. duk_size_t code_size;
  43710. duk_size_t data_size;
  43711. duk_size_t i;
  43712. duk_tval *p_const;
  43713. duk_hobject **p_func;
  43714. duk_instr_t *p_instr;
  43715. duk_compiler_instr *q_instr;
  43716. duk_tval *tv;
  43717. DUK_DDD(DUK_DDDPRINT("converting duk_compiler_func to function/template"));
  43718. DUK_DD(DUK_DDPRINT("code=%!xO consts=%!O funcs=%!O",
  43719. (duk_heaphdr *) func->h_code,
  43720. (duk_heaphdr *) func->h_consts,
  43721. (duk_heaphdr *) func->h_funcs));
  43722. /*
  43723. * Push result object and init its flags
  43724. */
  43725. /* Valstack should suffice here, required on function valstack init */
  43726. (void) duk_push_compiledfunction(ctx);
  43727. h_res = (duk_hcompiledfunction *) duk_get_hobject(ctx, -1); /* XXX: specific getter */
  43728. DUK_ASSERT(h_res != NULL);
  43729. if (func->is_function) {
  43730. DUK_DDD(DUK_DDDPRINT("function -> set NEWENV"));
  43731. DUK_HOBJECT_SET_NEWENV((duk_hobject *) h_res);
  43732. if (!func->is_arguments_shadowed) {
  43733. /* arguments object would be accessible; note that shadowing
  43734. * bindings are arguments or function declarations, neither
  43735. * of which are deletable, so this is safe.
  43736. */
  43737. if (func->id_access_arguments || func->may_direct_eval) {
  43738. DUK_DDD(DUK_DDDPRINT("function may access 'arguments' object directly or "
  43739. "indirectly -> set CREATEARGS"));
  43740. DUK_HOBJECT_SET_CREATEARGS((duk_hobject *) h_res);
  43741. }
  43742. }
  43743. } else if (func->is_eval && func->is_strict) {
  43744. DUK_DDD(DUK_DDDPRINT("strict eval code -> set NEWENV"));
  43745. DUK_HOBJECT_SET_NEWENV((duk_hobject *) h_res);
  43746. } else {
  43747. /* non-strict eval: env is caller's env or global env (direct vs. indirect call)
  43748. * global code: env is is global env
  43749. */
  43750. DUK_DDD(DUK_DDDPRINT("non-strict eval code or global code -> no NEWENV"));
  43751. DUK_ASSERT(!DUK_HOBJECT_HAS_NEWENV((duk_hobject *) h_res));
  43752. }
  43753. if (func->is_function && !func->is_decl && func->h_name != NULL && !force_no_namebind) {
  43754. /* Object literal set/get functions have a name (property
  43755. * name) but must not have a lexical name binding, see
  43756. * test-bug-getset-func-name.js.
  43757. */
  43758. DUK_DDD(DUK_DDDPRINT("function expression with a name -> set NAMEBINDING"));
  43759. DUK_HOBJECT_SET_NAMEBINDING((duk_hobject *) h_res);
  43760. }
  43761. if (func->is_strict) {
  43762. DUK_DDD(DUK_DDDPRINT("function is strict -> set STRICT"));
  43763. DUK_HOBJECT_SET_STRICT((duk_hobject *) h_res);
  43764. }
  43765. if (func->is_notail) {
  43766. DUK_DDD(DUK_DDDPRINT("function is notail -> set NOTAIL"));
  43767. DUK_HOBJECT_SET_NOTAIL((duk_hobject *) h_res);
  43768. }
  43769. /*
  43770. * Build function fixed size 'data' buffer, which contains bytecode,
  43771. * constants, and inner function references.
  43772. *
  43773. * During the building phase 'data' is reachable but incomplete.
  43774. * Only incref's occur during building (no refzero or GC happens),
  43775. * so the building process is atomic.
  43776. */
  43777. consts_count = duk_hobject_get_length(comp_ctx->thr, func->h_consts);
  43778. funcs_count = duk_hobject_get_length(comp_ctx->thr, func->h_funcs) / 3;
  43779. code_count = DUK_HBUFFER_GET_SIZE(func->h_code) / sizeof(duk_compiler_instr);
  43780. code_size = code_count * sizeof(duk_instr_t);
  43781. data_size = consts_count * sizeof(duk_tval) +
  43782. funcs_count * sizeof(duk_hobject *) +
  43783. code_size;
  43784. DUK_DDD(DUK_DDDPRINT("consts_count=%ld, funcs_count=%ld, code_size=%ld -> "
  43785. "data_size=%ld*%ld + %ld*%ld + %ld = %ld",
  43786. (long) consts_count, (long) funcs_count, (long) code_size,
  43787. (long) consts_count, (long) sizeof(duk_tval),
  43788. (long) funcs_count, (long) sizeof(duk_hobject *),
  43789. (long) code_size, (long) data_size));
  43790. duk_push_fixed_buffer(ctx, data_size);
  43791. h_data = (duk_hbuffer_fixed *) duk_get_hbuffer(ctx, -1);
  43792. DUK_ASSERT(h_data != NULL);
  43793. DUK_HCOMPILEDFUNCTION_SET_DATA(thr->heap, h_res, (duk_hbuffer *) h_data);
  43794. DUK_HEAPHDR_INCREF(thr, h_data);
  43795. p_const = (duk_tval *) DUK_HBUFFER_FIXED_GET_DATA_PTR(thr->heap, h_data);
  43796. for (i = 0; i < consts_count; i++) {
  43797. DUK_ASSERT(i <= DUK_UARRIDX_MAX); /* const limits */
  43798. tv = duk_hobject_find_existing_array_entry_tval_ptr(thr->heap, func->h_consts, (duk_uarridx_t) i);
  43799. DUK_ASSERT(tv != NULL);
  43800. DUK_TVAL_SET_TVAL(p_const, tv);
  43801. p_const++;
  43802. DUK_TVAL_INCREF(thr, tv); /* may be a string constant */
  43803. DUK_DDD(DUK_DDDPRINT("constant: %!T", (duk_tval *) tv));
  43804. }
  43805. p_func = (duk_hobject **) p_const;
  43806. DUK_HCOMPILEDFUNCTION_SET_FUNCS(thr->heap, h_res, p_func);
  43807. for (i = 0; i < funcs_count; i++) {
  43808. duk_hobject *h;
  43809. DUK_ASSERT(i * 3 <= DUK_UARRIDX_MAX); /* func limits */
  43810. tv = duk_hobject_find_existing_array_entry_tval_ptr(thr->heap, func->h_funcs, (duk_uarridx_t) (i * 3));
  43811. DUK_ASSERT(tv != NULL);
  43812. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  43813. h = DUK_TVAL_GET_OBJECT(tv);
  43814. DUK_ASSERT(h != NULL);
  43815. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(h));
  43816. *p_func++ = h;
  43817. DUK_HOBJECT_INCREF(thr, h);
  43818. DUK_DDD(DUK_DDDPRINT("inner function: %p -> %!iO",
  43819. (void *) h, (duk_heaphdr *) h));
  43820. }
  43821. p_instr = (duk_instr_t *) p_func;
  43822. DUK_HCOMPILEDFUNCTION_SET_BYTECODE(thr->heap, h_res, p_instr);
  43823. /* copy bytecode instructions one at a time */
  43824. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(func->h_code));
  43825. q_instr = (duk_compiler_instr *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, func->h_code);
  43826. for (i = 0; i < code_count; i++) {
  43827. p_instr[i] = q_instr[i].ins;
  43828. }
  43829. /* Note: 'q_instr' is still used below */
  43830. DUK_ASSERT((duk_uint8_t *) (p_instr + code_count) == DUK_HBUFFER_FIXED_GET_DATA_PTR(thr->heap, h_data) + data_size);
  43831. duk_pop(ctx); /* 'data' (and everything in it) is reachable through h_res now */
  43832. /*
  43833. * Init object properties
  43834. *
  43835. * Properties should be added in decreasing order of access frequency.
  43836. * (Not very critical for function templates.)
  43837. */
  43838. DUK_DDD(DUK_DDDPRINT("init function properties"));
  43839. /* [ ... res ] */
  43840. /* _Varmap: omitted if function is guaranteed not to do slow path identifier
  43841. * accesses or if it would turn out to be empty of actual register mappings
  43842. * after a cleanup. When debugging is enabled, we always need the varmap to
  43843. * be able to lookup variables at any point.
  43844. */
  43845. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  43846. if (1) {
  43847. #else
  43848. if (func->id_access_slow || /* directly uses slow accesses */
  43849. func->may_direct_eval || /* may indirectly slow access through a direct eval */
  43850. funcs_count > 0) { /* has inner functions which may slow access (XXX: this can be optimized by looking at the inner functions) */
  43851. #endif
  43852. duk_int_t num_used;
  43853. duk_dup(ctx, func->varmap_idx);
  43854. num_used = duk__cleanup_varmap(comp_ctx);
  43855. DUK_DDD(DUK_DDDPRINT("cleaned up varmap: %!T (num_used=%ld)",
  43856. (duk_tval *) duk_get_tval(ctx, -1), (long) num_used));
  43857. if (num_used > 0) {
  43858. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_VARMAP, DUK_PROPDESC_FLAGS_NONE);
  43859. } else {
  43860. DUK_DDD(DUK_DDDPRINT("varmap is empty after cleanup -> no need to add"));
  43861. duk_pop(ctx);
  43862. }
  43863. }
  43864. /* _Formals: omitted if function is guaranteed not to need a (non-strict) arguments object */
  43865. if (1) {
  43866. /* XXX: Add a proper condition. If formals list is omitted, recheck
  43867. * handling for 'length' in duk_js_push_closure(); it currently relies
  43868. * on _Formals being set. Removal may need to be conditional to debugging
  43869. * being enabled/disabled too.
  43870. */
  43871. duk_dup(ctx, func->argnames_idx);
  43872. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_FORMALS, DUK_PROPDESC_FLAGS_NONE);
  43873. }
  43874. /* name */
  43875. if (func->h_name) {
  43876. duk_push_hstring(ctx, func->h_name);
  43877. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_NAME, DUK_PROPDESC_FLAGS_NONE);
  43878. }
  43879. /* _Source */
  43880. #if defined(DUK_USE_NONSTD_FUNC_SOURCE_PROPERTY)
  43881. if (0) {
  43882. /* XXX: Currently function source code is not stored, as it is not
  43883. * required by the standard. Source code should not be stored by
  43884. * default (user should enable it explicitly), and the source should
  43885. * probably be compressed with a trivial text compressor; average
  43886. * compression of 20-30% is quite easy to achieve even with a trivial
  43887. * compressor (RLE + backwards lookup).
  43888. *
  43889. * Debugging needs source code to be useful: sometimes input code is
  43890. * not found in files as it may be generated and then eval()'d, given
  43891. * by dynamic C code, etc.
  43892. *
  43893. * Other issues:
  43894. *
  43895. * - Need tokenizer indices for start and end to substring
  43896. * - Always normalize function declaration part?
  43897. * - If we keep _Formals, only need to store body
  43898. */
  43899. /*
  43900. * For global or eval code this is straightforward. For functions
  43901. * created with the Function constructor we only get the source for
  43902. * the body and must manufacture the "function ..." part.
  43903. *
  43904. * For instance, for constructed functions (v8):
  43905. *
  43906. * > a = new Function("foo", "bar", "print(foo)");
  43907. * [Function]
  43908. * > a.toString()
  43909. * 'function anonymous(foo,bar) {\nprint(foo)\n}'
  43910. *
  43911. * Similarly for e.g. getters (v8):
  43912. *
  43913. * > x = { get a(foo,bar) { print(foo); } }
  43914. * { a: [Getter] }
  43915. * > Object.getOwnPropertyDescriptor(x, 'a').get.toString()
  43916. * 'function a(foo,bar) { print(foo); }'
  43917. */
  43918. #if 0
  43919. duk_push_string(ctx, "XXX");
  43920. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_SOURCE, DUK_PROPDESC_FLAGS_NONE);
  43921. #endif
  43922. }
  43923. #endif /* DUK_USE_NONSTD_FUNC_SOURCE_PROPERTY */
  43924. /* _Pc2line */
  43925. #if defined(DUK_USE_PC2LINE)
  43926. if (1) {
  43927. /*
  43928. * Size-optimized pc->line mapping.
  43929. */
  43930. DUK_ASSERT(code_count <= DUK_COMPILER_MAX_BYTECODE_LENGTH);
  43931. duk_hobject_pc2line_pack(thr, q_instr, (duk_uint_fast32_t) code_count); /* -> pushes fixed buffer */
  43932. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_INT_PC2LINE, DUK_PROPDESC_FLAGS_NONE);
  43933. /* XXX: if assertions enabled, walk through all valid PCs
  43934. * and check line mapping.
  43935. */
  43936. }
  43937. #endif /* DUK_USE_PC2LINE */
  43938. /* fileName */
  43939. if (comp_ctx->h_filename) {
  43940. /*
  43941. * Source filename (or equivalent), for identifying thrown errors.
  43942. */
  43943. duk_push_hstring(ctx, comp_ctx->h_filename);
  43944. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_FILE_NAME, DUK_PROPDESC_FLAGS_NONE);
  43945. }
  43946. /*
  43947. * Init remaining result fields
  43948. *
  43949. * 'nregs' controls how large a register frame is allocated.
  43950. *
  43951. * 'nargs' controls how many formal arguments are written to registers:
  43952. * r0, ... r(nargs-1). The remaining registers are initialized to
  43953. * undefined.
  43954. */
  43955. DUK_ASSERT(func->temp_max >= 0);
  43956. h_res->nregs = func->temp_max;
  43957. h_res->nargs = duk_hobject_get_length(thr, func->h_argnames);
  43958. DUK_ASSERT(h_res->nregs >= h_res->nargs); /* pass2 allocation handles this */
  43959. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  43960. h_res->start_line = (duk_uint32_t) func->min_line;
  43961. h_res->end_line = (duk_uint32_t) func->max_line;
  43962. #endif
  43963. DUK_DD(DUK_DDPRINT("converted function: %!ixT",
  43964. (duk_tval *) duk_get_tval(ctx, -1)));
  43965. /*
  43966. * Compact the function template.
  43967. */
  43968. duk_compact(ctx, -1);
  43969. /*
  43970. * Debug dumping
  43971. */
  43972. #ifdef DUK_USE_DDDPRINT
  43973. {
  43974. duk_hcompiledfunction *h;
  43975. duk_instr_t *p, *p_start, *p_end;
  43976. h = (duk_hcompiledfunction *) duk_get_hobject(ctx, -1);
  43977. p_start = (duk_instr_t *) DUK_HCOMPILEDFUNCTION_GET_CODE_BASE(thr->heap, h);
  43978. p_end = (duk_instr_t *) DUK_HCOMPILEDFUNCTION_GET_CODE_END(thr->heap, h);
  43979. p = p_start;
  43980. while (p < p_end) {
  43981. DUK_DDD(DUK_DDDPRINT("BC %04ld: %!I ; 0x%08lx op=%ld (%!C) a=%ld b=%ld c=%ld",
  43982. (long) (p - p_start),
  43983. (duk_instr_t) (*p),
  43984. (unsigned long) (*p),
  43985. (long) DUK_DEC_OP(*p),
  43986. (long) DUK_DEC_OP(*p),
  43987. (long) DUK_DEC_A(*p),
  43988. (long) DUK_DEC_B(*p),
  43989. (long) DUK_DEC_C(*p)));
  43990. p++;
  43991. }
  43992. }
  43993. #endif
  43994. }
  43995. /*
  43996. * Code emission helpers
  43997. *
  43998. * Some emission helpers understand the range of target and source reg/const
  43999. * values and automatically emit shuffling code if necessary. This is the
  44000. * case when the slot in question (A, B, C) is used in the standard way and
  44001. * for opcodes the emission helpers explicitly understand (like DUK_OP_CALL).
  44002. *
  44003. * The standard way is that:
  44004. * - slot A is a target register
  44005. * - slot B is a source register/constant
  44006. * - slot C is a source register/constant
  44007. *
  44008. * If a slot is used in a non-standard way the caller must indicate this
  44009. * somehow. If a slot is used as a target instead of a source (or vice
  44010. * versa), this can be indicated with a flag to trigger proper shuffling
  44011. * (e.g. DUK__EMIT_FLAG_B_IS_TARGET). If the value in the slot is not
  44012. * register/const related at all, the caller must ensure that the raw value
  44013. * fits into the corresponding slot so as to not trigger shuffling. The
  44014. * caller must set a "no shuffle" flag to ensure compilation fails if
  44015. * shuffling were to be triggered because of an internal error.
  44016. *
  44017. * For slots B and C the raw slot size is 9 bits but one bit is reserved for
  44018. * the reg/const indicator. To use the full 9-bit range for a raw value,
  44019. * shuffling must be disabled with the DUK__EMIT_FLAG_NO_SHUFFLE_{B,C} flag.
  44020. * Shuffling is only done for A, B, and C slots, not the larger BC or ABC slots.
  44021. *
  44022. * There is call handling specific understanding in the A-B-C emitter to
  44023. * convert call setup and call instructions into indirect ones if necessary.
  44024. */
  44025. /* Code emission flags, passed in the 'opcode' field. Opcode + flags
  44026. * fit into 16 bits for now, so use duk_small_uint.t.
  44027. */
  44028. #define DUK__EMIT_FLAG_NO_SHUFFLE_A (1 << 8)
  44029. #define DUK__EMIT_FLAG_NO_SHUFFLE_B (1 << 9)
  44030. #define DUK__EMIT_FLAG_NO_SHUFFLE_C (1 << 10)
  44031. #define DUK__EMIT_FLAG_A_IS_SOURCE (1 << 11) /* slot A is a source (default: target) */
  44032. #define DUK__EMIT_FLAG_B_IS_TARGET (1 << 12) /* slot B is a target (default: source) */
  44033. #define DUK__EMIT_FLAG_C_IS_TARGET (1 << 13) /* slot C is a target (default: source) */
  44034. #define DUK__EMIT_FLAG_B_IS_TARGETSOURCE (1 << 14) /* slot B is both a target and a source (used by extraops like DUK_EXTRAOP_INSTOF */
  44035. #define DUK__EMIT_FLAG_RESERVE_JUMPSLOT (1 << 15) /* reserve a jumpslot after instr before target spilling, used for NEXTENUM */
  44036. /* XXX: clarify on when and where DUK__CONST_MARKER is allowed */
  44037. /* XXX: opcode specific assertions on when consts are allowed */
  44038. /* XXX: macro smaller than call? */
  44039. DUK_LOCAL duk_int_t duk__get_current_pc(duk_compiler_ctx *comp_ctx) {
  44040. return (duk_int_t) (DUK_HBUFFER_GET_SIZE(comp_ctx->curr_func.h_code) / sizeof(duk_compiler_instr));
  44041. }
  44042. DUK_LOCAL duk_compiler_instr *duk__get_instr_ptr(duk_compiler_ctx *comp_ctx, duk_int_t pc) {
  44043. duk_compiler_func *f = &comp_ctx->curr_func;
  44044. duk_uint8_t *p;
  44045. duk_compiler_instr *code_begin, *code_end;
  44046. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(comp_ctx->thr->heap, f->h_code);
  44047. code_begin = (duk_compiler_instr *) p;
  44048. code_end = (duk_compiler_instr *) (p + DUK_HBUFFER_GET_SIZE(f->h_code));
  44049. DUK_UNREF(code_end);
  44050. DUK_ASSERT(pc >= 0);
  44051. DUK_ASSERT((duk_size_t) pc < (duk_size_t) (code_end - code_begin));
  44052. return code_begin + pc;
  44053. }
  44054. /* emit instruction; could return PC but that's not needed in the majority
  44055. * of cases.
  44056. */
  44057. DUK_LOCAL void duk__emit(duk_compiler_ctx *comp_ctx, duk_instr_t ins) {
  44058. duk_hbuffer_dynamic *h;
  44059. #if defined(DUK_USE_PC2LINE)
  44060. duk_int_t line;
  44061. #endif
  44062. duk_compiler_instr instr;
  44063. DUK_DDD(DUK_DDDPRINT("duk__emit: 0x%08lx curr_token.start_line=%ld prev_token.start_line=%ld pc=%ld --> %!I",
  44064. (unsigned long) ins,
  44065. (long) comp_ctx->curr_token.start_line,
  44066. (long) comp_ctx->prev_token.start_line,
  44067. (long) duk__get_current_pc(comp_ctx),
  44068. (duk_instr_t) ins));
  44069. h = comp_ctx->curr_func.h_code;
  44070. #if defined(DUK_USE_PC2LINE)
  44071. /* The line number tracking is a bit inconsistent right now, which
  44072. * affects debugger accuracy. Mostly call sites emit opcodes when
  44073. * they have parsed a token (say a terminating semicolon) and called
  44074. * duk__advance(). In this case the line number of the previous
  44075. * token is the most accurate one (except in prologue where
  44076. * prev_token.start_line is 0). This is probably not 100% correct
  44077. * right now.
  44078. */
  44079. /* approximation, close enough */
  44080. line = comp_ctx->prev_token.start_line;
  44081. if (line == 0) {
  44082. line = comp_ctx->curr_token.start_line;
  44083. }
  44084. #endif
  44085. instr.ins = ins;
  44086. #if defined(DUK_USE_PC2LINE)
  44087. instr.line = line;
  44088. #endif
  44089. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  44090. if (line < comp_ctx->curr_func.min_line) {
  44091. comp_ctx->curr_func.min_line = line;
  44092. }
  44093. if (line > comp_ctx->curr_func.max_line) {
  44094. comp_ctx->curr_func.max_line = line;
  44095. }
  44096. #endif
  44097. /* Limit checks for bytecode byte size and line number. */
  44098. #if defined(DUK_USE_PC2LINE) && defined(DUK_USE_ESBC_LIMITS)
  44099. #if defined(DUK_USE_BUFLEN16)
  44100. /* Buffer length is bounded to 0xffff automatically, avoid compile warning. */
  44101. if (DUK_UNLIKELY(line > DUK_USE_ESBC_MAX_LINENUMBER)) {
  44102. DUK_ERROR(comp_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_BYTECODE_LIMIT);
  44103. }
  44104. #else
  44105. if (DUK_UNLIKELY(line > DUK_USE_ESBC_MAX_LINENUMBER ||
  44106. DUK_HBUFFER_GET_SIZE((duk_hbuffer *) h) > DUK_USE_ESBC_MAX_BYTES)) {
  44107. DUK_ERROR(comp_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_BYTECODE_LIMIT);
  44108. }
  44109. #endif
  44110. #endif
  44111. duk_hbuffer_append_bytes(comp_ctx->thr, h, (duk_uint8_t *) &instr, sizeof(instr));
  44112. }
  44113. /* Update function min/max line from current token. Needed to improve
  44114. * function line range information for debugging, so that e.g. opening
  44115. * curly brace is covered by line range even when no opcodes are emitted
  44116. * for the line containing the brace.
  44117. */
  44118. DUK_LOCAL void duk__update_lineinfo_currtoken(duk_compiler_ctx *comp_ctx) {
  44119. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  44120. duk_int_t line;
  44121. line = comp_ctx->curr_token.start_line;
  44122. if (line == 0) {
  44123. return;
  44124. }
  44125. if (line < comp_ctx->curr_func.min_line) {
  44126. comp_ctx->curr_func.min_line = line;
  44127. }
  44128. if (line > comp_ctx->curr_func.max_line) {
  44129. comp_ctx->curr_func.max_line = line;
  44130. }
  44131. #else
  44132. DUK_UNREF(comp_ctx);
  44133. #endif
  44134. }
  44135. #if 0 /* unused */
  44136. DUK_LOCAL void duk__emit_op_only(duk_compiler_ctx *comp_ctx, duk_small_uint_t op) {
  44137. duk__emit(comp_ctx, DUK_ENC_OP_ABC(op, 0));
  44138. }
  44139. #endif
  44140. /* Important main primitive. */
  44141. DUK_LOCAL void duk__emit_a_b_c(duk_compiler_ctx *comp_ctx, duk_small_uint_t op_flags, duk_regconst_t a, duk_regconst_t b, duk_regconst_t c) {
  44142. duk_instr_t ins = 0;
  44143. duk_int_t a_out = -1;
  44144. duk_int_t b_out = -1;
  44145. duk_int_t c_out = -1;
  44146. duk_int_t tmp;
  44147. DUK_DDD(DUK_DDDPRINT("emit: op_flags=%04lx, a=%ld, b=%ld, c=%ld",
  44148. (unsigned long) op_flags, (long) a, (long) b, (long) c));
  44149. /* We could rely on max temp/const checks: if they don't exceed BC
  44150. * limit, nothing here can either (just asserts would be enough).
  44151. * Currently we check for the limits, which provides additional
  44152. * protection against creating invalid bytecode due to compiler
  44153. * bugs.
  44154. */
  44155. DUK_ASSERT_DISABLE((op_flags & 0xff) >= DUK_BC_OP_MIN); /* unsigned */
  44156. DUK_ASSERT((op_flags & 0xff) <= DUK_BC_OP_MAX);
  44157. /* Input shuffling happens before the actual operation, while output
  44158. * shuffling happens afterwards. Output shuffling decisions are still
  44159. * made at the same time to reduce branch clutter; output shuffle decisions
  44160. * are recorded into X_out variables.
  44161. */
  44162. /* Slot A */
  44163. #if defined(DUK_USE_SHUFFLE_TORTURE)
  44164. if (a <= DUK_BC_A_MAX && (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_A)) {
  44165. #else
  44166. if (a <= DUK_BC_A_MAX) {
  44167. #endif
  44168. ;
  44169. } else if (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_A) {
  44170. DUK_D(DUK_DPRINT("out of regs: 'a' (reg) needs shuffling but shuffle prohibited, a: %ld", (long) a));
  44171. goto error_outofregs;
  44172. } else if (a <= DUK_BC_BC_MAX) {
  44173. comp_ctx->curr_func.needs_shuffle = 1;
  44174. tmp = comp_ctx->curr_func.shuffle1;
  44175. if (op_flags & DUK__EMIT_FLAG_A_IS_SOURCE) {
  44176. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_LDREG, tmp, a));
  44177. } else {
  44178. duk_small_int_t op = op_flags & 0xff;
  44179. if (op == DUK_OP_CSVAR || op == DUK_OP_CSREG || op == DUK_OP_CSPROP) {
  44180. /* Special handling for call setup instructions. The target
  44181. * is expressed indirectly, but there is no output shuffling.
  44182. */
  44183. DUK_ASSERT((op_flags & DUK__EMIT_FLAG_A_IS_SOURCE) == 0);
  44184. duk__emit_load_int32_noshuffle(comp_ctx, tmp, a);
  44185. DUK_ASSERT(DUK_OP_CSVARI == DUK_OP_CSVAR + 1);
  44186. DUK_ASSERT(DUK_OP_CSREGI == DUK_OP_CSREG + 1);
  44187. DUK_ASSERT(DUK_OP_CSPROPI == DUK_OP_CSPROP + 1);
  44188. op_flags++; /* indirect opcode follows direct */
  44189. } else {
  44190. /* Output shuffle needed after main operation */
  44191. a_out = a;
  44192. }
  44193. }
  44194. a = tmp;
  44195. } else {
  44196. DUK_D(DUK_DPRINT("out of regs: 'a' (reg) needs shuffling but does not fit into BC, a: %ld", (long) a));
  44197. goto error_outofregs;
  44198. }
  44199. /* Slot B */
  44200. if (b & DUK__CONST_MARKER) {
  44201. DUK_ASSERT((op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_B) == 0);
  44202. DUK_ASSERT((op_flags & DUK__EMIT_FLAG_B_IS_TARGET) == 0);
  44203. DUK_ASSERT((op_flags & 0xff) != DUK_OP_CALL);
  44204. DUK_ASSERT((op_flags & 0xff) != DUK_OP_NEW);
  44205. b = b & ~DUK__CONST_MARKER;
  44206. #if defined(DUK_USE_SHUFFLE_TORTURE)
  44207. if (0) {
  44208. #else
  44209. if (b <= 0xff) {
  44210. #endif
  44211. ins |= DUK_ENC_OP_A_B_C(0, 0, 0x100, 0); /* const flag for B */
  44212. } else if (b <= DUK_BC_BC_MAX) {
  44213. comp_ctx->curr_func.needs_shuffle = 1;
  44214. tmp = comp_ctx->curr_func.shuffle2;
  44215. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_LDCONST, tmp, b));
  44216. b = tmp;
  44217. } else {
  44218. DUK_D(DUK_DPRINT("out of regs: 'b' (const) needs shuffling but does not fit into BC, b: %ld", (long) b));
  44219. goto error_outofregs;
  44220. }
  44221. } else {
  44222. #if defined(DUK_USE_SHUFFLE_TORTURE)
  44223. if (b <= 0xff && (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_B)) {
  44224. #else
  44225. if (b <= 0xff) {
  44226. #endif
  44227. ;
  44228. } else if (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_B) {
  44229. if (b > DUK_BC_B_MAX) {
  44230. /* Note: 0xff != DUK_BC_B_MAX */
  44231. DUK_D(DUK_DPRINT("out of regs: 'b' (reg) needs shuffling but shuffle prohibited, b: %ld", (long) b));
  44232. goto error_outofregs;
  44233. }
  44234. } else if (b <= DUK_BC_BC_MAX) {
  44235. comp_ctx->curr_func.needs_shuffle = 1;
  44236. tmp = comp_ctx->curr_func.shuffle2;
  44237. if (op_flags & DUK__EMIT_FLAG_B_IS_TARGET) {
  44238. /* Output shuffle needed after main operation */
  44239. b_out = b;
  44240. }
  44241. if (!(op_flags & DUK__EMIT_FLAG_B_IS_TARGET) || (op_flags & DUK__EMIT_FLAG_B_IS_TARGETSOURCE)) {
  44242. duk_small_int_t op = op_flags & 0xff;
  44243. if (op == DUK_OP_CALL || op == DUK_OP_NEW ||
  44244. op == DUK_OP_MPUTOBJ || op == DUK_OP_MPUTARR) {
  44245. /* Special handling for CALL/NEW/MPUTOBJ/MPUTARR shuffling.
  44246. * For each, slot B identifies the first register of a range
  44247. * of registers, so normal shuffling won't work. Instead,
  44248. * an indirect version of the opcode is used.
  44249. */
  44250. DUK_ASSERT((op_flags & DUK__EMIT_FLAG_B_IS_TARGET) == 0);
  44251. duk__emit_load_int32_noshuffle(comp_ctx, tmp, b);
  44252. DUK_ASSERT(DUK_OP_CALLI == DUK_OP_CALL + 1);
  44253. DUK_ASSERT(DUK_OP_NEWI == DUK_OP_NEW + 1);
  44254. DUK_ASSERT(DUK_OP_MPUTOBJI == DUK_OP_MPUTOBJ + 1);
  44255. DUK_ASSERT(DUK_OP_MPUTARRI == DUK_OP_MPUTARR + 1);
  44256. op_flags++; /* indirect opcode follows direct */
  44257. } else {
  44258. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_LDREG, tmp, b));
  44259. }
  44260. }
  44261. b = tmp;
  44262. } else {
  44263. DUK_D(DUK_DPRINT("out of regs: 'b' (reg) needs shuffling but does not fit into BC, b: %ld", (long) b));
  44264. goto error_outofregs;
  44265. }
  44266. }
  44267. /* Slot C */
  44268. if (c & DUK__CONST_MARKER) {
  44269. DUK_ASSERT((op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_C) == 0);
  44270. DUK_ASSERT((op_flags & DUK__EMIT_FLAG_C_IS_TARGET) == 0);
  44271. c = c & ~DUK__CONST_MARKER;
  44272. #if defined(DUK_USE_SHUFFLE_TORTURE)
  44273. if (0) {
  44274. #else
  44275. if (c <= 0xff) {
  44276. #endif
  44277. ins |= DUK_ENC_OP_A_B_C(0, 0, 0, 0x100); /* const flag for C */
  44278. } else if (c <= DUK_BC_BC_MAX) {
  44279. comp_ctx->curr_func.needs_shuffle = 1;
  44280. tmp = comp_ctx->curr_func.shuffle3;
  44281. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_LDCONST, tmp, c));
  44282. c = tmp;
  44283. } else {
  44284. DUK_D(DUK_DPRINT("out of regs: 'c' (const) needs shuffling but does not fit into BC, c: %ld", (long) c));
  44285. goto error_outofregs;
  44286. }
  44287. } else {
  44288. #if defined(DUK_USE_SHUFFLE_TORTURE)
  44289. if (c <= 0xff && (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_C)) {
  44290. #else
  44291. if (c <= 0xff) {
  44292. #endif
  44293. ;
  44294. } else if (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_C) {
  44295. if (c > DUK_BC_C_MAX) {
  44296. /* Note: 0xff != DUK_BC_C_MAX */
  44297. DUK_D(DUK_DPRINT("out of regs: 'c' (reg) needs shuffling but shuffle prohibited, c: %ld", (long) c));
  44298. goto error_outofregs;
  44299. }
  44300. } else if (c <= DUK_BC_BC_MAX) {
  44301. comp_ctx->curr_func.needs_shuffle = 1;
  44302. tmp = comp_ctx->curr_func.shuffle3;
  44303. if (op_flags & DUK__EMIT_FLAG_C_IS_TARGET) {
  44304. /* Output shuffle needed after main operation */
  44305. c_out = c;
  44306. } else {
  44307. duk_small_int_t op = op_flags & 0xff;
  44308. if (op == DUK_OP_EXTRA &&
  44309. (a == DUK_EXTRAOP_INITGET || a == DUK_EXTRAOP_INITSET)) {
  44310. /* Special shuffling for INITGET/INITSET, where slot C
  44311. * identifies a register pair and cannot be shuffled
  44312. * normally. Use an indirect variant instead.
  44313. */
  44314. DUK_ASSERT((op_flags & DUK__EMIT_FLAG_C_IS_TARGET) == 0);
  44315. duk__emit_load_int32_noshuffle(comp_ctx, tmp, c);
  44316. DUK_ASSERT(DUK_EXTRAOP_INITGETI == DUK_EXTRAOP_INITGET + 1);
  44317. DUK_ASSERT(DUK_EXTRAOP_INITSETI == DUK_EXTRAOP_INITSET + 1);
  44318. a++; /* indirect opcode follows direct */
  44319. } else {
  44320. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_LDREG, tmp, c));
  44321. }
  44322. }
  44323. c = tmp;
  44324. } else {
  44325. DUK_D(DUK_DPRINT("out of regs: 'c' (reg) needs shuffling but does not fit into BC, c: %ld", (long) c));
  44326. goto error_outofregs;
  44327. }
  44328. }
  44329. /* Main operation */
  44330. DUK_ASSERT_DISABLE(a >= DUK_BC_A_MIN); /* unsigned */
  44331. DUK_ASSERT(a <= DUK_BC_A_MAX);
  44332. DUK_ASSERT_DISABLE(b >= DUK_BC_B_MIN); /* unsigned */
  44333. DUK_ASSERT(b <= DUK_BC_B_MAX);
  44334. DUK_ASSERT_DISABLE(c >= DUK_BC_C_MIN); /* unsigned */
  44335. DUK_ASSERT(c <= DUK_BC_C_MAX);
  44336. ins |= DUK_ENC_OP_A_B_C(op_flags & 0xff, a, b, c);
  44337. duk__emit(comp_ctx, ins);
  44338. /* NEXTENUM needs a jump slot right after the main instruction.
  44339. * When the JUMP is taken, output spilling is not needed so this
  44340. * workaround is possible. The jump slot PC is exceptionally
  44341. * plumbed through comp_ctx to minimize call sites.
  44342. */
  44343. if (op_flags & DUK__EMIT_FLAG_RESERVE_JUMPSLOT) {
  44344. comp_ctx->emit_jumpslot_pc = duk__get_current_pc(comp_ctx);
  44345. duk__emit_abc(comp_ctx, DUK_OP_JUMP, 0);
  44346. }
  44347. /* Output shuffling: only one output register is realistically possible.
  44348. *
  44349. * (Zero would normally be an OK marker value: if the target register
  44350. * was zero, it would never be shuffled. But with DUK_USE_SHUFFLE_TORTURE
  44351. * this is no longer true, so use -1 as a marker instead.)
  44352. */
  44353. if (a_out >= 0) {
  44354. DUK_ASSERT(b_out < 0);
  44355. DUK_ASSERT(c_out < 0);
  44356. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_STREG, a, a_out));
  44357. } else if (b_out >= 0) {
  44358. DUK_ASSERT(a_out < 0);
  44359. DUK_ASSERT(c_out < 0);
  44360. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_STREG, b, b_out));
  44361. } else if (c_out >= 0) {
  44362. DUK_ASSERT(b_out < 0);
  44363. DUK_ASSERT(c_out < 0);
  44364. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_STREG, c, c_out));
  44365. }
  44366. return;
  44367. error_outofregs:
  44368. DUK_ERROR(comp_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_REG_LIMIT);
  44369. }
  44370. DUK_LOCAL void duk__emit_a_b(duk_compiler_ctx *comp_ctx, duk_small_uint_t op_flags, duk_regconst_t a, duk_regconst_t b) {
  44371. duk__emit_a_b_c(comp_ctx, op_flags | DUK__EMIT_FLAG_NO_SHUFFLE_C, a, b, 0);
  44372. }
  44373. #if 0 /* unused */
  44374. DUK_LOCAL void duk__emit_a(duk_compiler_ctx *comp_ctx, int op_flags, int a) {
  44375. duk__emit_a_b_c(comp_ctx, op_flags | DUK__EMIT_FLAG_NO_SHUFFLE_B | DUK__EMIT_FLAG_NO_SHUFFLE_C, a, 0, 0);
  44376. }
  44377. #endif
  44378. DUK_LOCAL void duk__emit_a_bc(duk_compiler_ctx *comp_ctx, duk_small_uint_t op_flags, duk_regconst_t a, duk_regconst_t bc) {
  44379. duk_instr_t ins;
  44380. duk_int_t tmp;
  44381. /* allow caller to give a const number with the DUK__CONST_MARKER */
  44382. bc = bc & (~DUK__CONST_MARKER);
  44383. DUK_ASSERT_DISABLE((op_flags & 0xff) >= DUK_BC_OP_MIN); /* unsigned */
  44384. DUK_ASSERT((op_flags & 0xff) <= DUK_BC_OP_MAX);
  44385. DUK_ASSERT_DISABLE(bc >= DUK_BC_BC_MIN); /* unsigned */
  44386. DUK_ASSERT(bc <= DUK_BC_BC_MAX);
  44387. DUK_ASSERT((bc & DUK__CONST_MARKER) == 0);
  44388. if (bc <= DUK_BC_BC_MAX) {
  44389. ;
  44390. } else {
  44391. /* No BC shuffling now. */
  44392. goto error_outofregs;
  44393. }
  44394. #if defined(DUK_USE_SHUFFLE_TORTURE)
  44395. if (a <= DUK_BC_A_MAX && (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_A)) {
  44396. #else
  44397. if (a <= DUK_BC_A_MAX) {
  44398. #endif
  44399. ins = DUK_ENC_OP_A_BC(op_flags & 0xff, a, bc);
  44400. duk__emit(comp_ctx, ins);
  44401. } else if (op_flags & DUK__EMIT_FLAG_NO_SHUFFLE_A) {
  44402. goto error_outofregs;
  44403. } else if (a <= DUK_BC_BC_MAX) {
  44404. comp_ctx->curr_func.needs_shuffle = 1;
  44405. tmp = comp_ctx->curr_func.shuffle1;
  44406. ins = DUK_ENC_OP_A_BC(op_flags & 0xff, tmp, bc);
  44407. if (op_flags & DUK__EMIT_FLAG_A_IS_SOURCE) {
  44408. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_LDREG, tmp, a));
  44409. duk__emit(comp_ctx, ins);
  44410. } else {
  44411. duk__emit(comp_ctx, ins);
  44412. duk__emit(comp_ctx, DUK_ENC_OP_A_BC(DUK_OP_STREG, tmp, a));
  44413. }
  44414. } else {
  44415. goto error_outofregs;
  44416. }
  44417. return;
  44418. error_outofregs:
  44419. DUK_ERROR(comp_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_REG_LIMIT);
  44420. }
  44421. DUK_LOCAL void duk__emit_abc(duk_compiler_ctx *comp_ctx, duk_small_uint_t op, duk_regconst_t abc) {
  44422. duk_instr_t ins;
  44423. DUK_ASSERT_DISABLE(op >= DUK_BC_OP_MIN); /* unsigned */
  44424. DUK_ASSERT(op <= DUK_BC_OP_MAX);
  44425. DUK_ASSERT_DISABLE(abc >= DUK_BC_ABC_MIN); /* unsigned */
  44426. DUK_ASSERT(abc <= DUK_BC_ABC_MAX);
  44427. DUK_ASSERT((abc & DUK__CONST_MARKER) == 0);
  44428. if (abc <= DUK_BC_ABC_MAX) {
  44429. ;
  44430. } else {
  44431. goto error_outofregs;
  44432. }
  44433. ins = DUK_ENC_OP_ABC(op, abc);
  44434. DUK_DDD(DUK_DDDPRINT("duk__emit_abc: 0x%08lx line=%ld pc=%ld op=%ld (%!C) abc=%ld (%!I)",
  44435. (unsigned long) ins, (long) comp_ctx->curr_token.start_line,
  44436. (long) duk__get_current_pc(comp_ctx), (long) op, (long) op,
  44437. (long) abc, (duk_instr_t) ins));
  44438. duk__emit(comp_ctx, ins);
  44439. return;
  44440. error_outofregs:
  44441. DUK_ERROR(comp_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_REG_LIMIT);
  44442. }
  44443. DUK_LOCAL void duk__emit_extraop_b_c(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop_flags, duk_regconst_t b, duk_regconst_t c) {
  44444. DUK_ASSERT_DISABLE((extraop_flags & 0xff) >= DUK_BC_EXTRAOP_MIN); /* unsigned */
  44445. DUK_ASSERT((extraop_flags & 0xff) <= DUK_BC_EXTRAOP_MAX);
  44446. /* Setting "no shuffle A" is covered by the assert, but it's needed
  44447. * with DUK_USE_SHUFFLE_TORTURE.
  44448. */
  44449. duk__emit_a_b_c(comp_ctx,
  44450. DUK_OP_EXTRA | DUK__EMIT_FLAG_NO_SHUFFLE_A | (extraop_flags & ~0xff), /* transfer flags */
  44451. extraop_flags & 0xff,
  44452. b,
  44453. c);
  44454. }
  44455. DUK_LOCAL void duk__emit_extraop_b(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop_flags, duk_regconst_t b) {
  44456. DUK_ASSERT_DISABLE((extraop_flags & 0xff) >= DUK_BC_EXTRAOP_MIN); /* unsigned */
  44457. DUK_ASSERT((extraop_flags & 0xff) <= DUK_BC_EXTRAOP_MAX);
  44458. /* Setting "no shuffle A" is covered by the assert, but it's needed
  44459. * with DUK_USE_SHUFFLE_TORTURE.
  44460. */
  44461. duk__emit_a_b_c(comp_ctx,
  44462. DUK_OP_EXTRA | DUK__EMIT_FLAG_NO_SHUFFLE_A | (extraop_flags & ~0xff), /* transfer flags */
  44463. extraop_flags & 0xff,
  44464. b,
  44465. 0);
  44466. }
  44467. DUK_LOCAL void duk__emit_extraop_bc(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop, duk_regconst_t bc) {
  44468. DUK_ASSERT_DISABLE(extraop >= DUK_BC_EXTRAOP_MIN); /* unsigned */
  44469. DUK_ASSERT(extraop <= DUK_BC_EXTRAOP_MAX);
  44470. /* Setting "no shuffle A" is covered by the assert, but it's needed
  44471. * with DUK_USE_SHUFFLE_TORTURE.
  44472. */
  44473. duk__emit_a_bc(comp_ctx,
  44474. DUK_OP_EXTRA | DUK__EMIT_FLAG_NO_SHUFFLE_A,
  44475. extraop,
  44476. bc);
  44477. }
  44478. DUK_LOCAL void duk__emit_extraop_only(duk_compiler_ctx *comp_ctx, duk_small_uint_t extraop_flags) {
  44479. DUK_ASSERT_DISABLE((extraop_flags & 0xff) >= DUK_BC_EXTRAOP_MIN); /* unsigned */
  44480. DUK_ASSERT((extraop_flags & 0xff) <= DUK_BC_EXTRAOP_MAX);
  44481. /* Setting "no shuffle A" is covered by the assert, but it's needed
  44482. * with DUK_USE_SHUFFLE_TORTURE.
  44483. */
  44484. duk__emit_a_b_c(comp_ctx,
  44485. DUK_OP_EXTRA | DUK__EMIT_FLAG_NO_SHUFFLE_A | DUK__EMIT_FLAG_NO_SHUFFLE_B |
  44486. DUK__EMIT_FLAG_NO_SHUFFLE_C | (extraop_flags & ~0xff), /* transfer flags */
  44487. extraop_flags & 0xff,
  44488. 0,
  44489. 0);
  44490. }
  44491. DUK_LOCAL void duk__emit_load_int32_raw(duk_compiler_ctx *comp_ctx, duk_reg_t reg, duk_int32_t val, duk_small_uint_t op_flags) {
  44492. /* XXX: Shuffling support could be implemented here so that LDINT+LDINTX
  44493. * would only shuffle once (instead of twice). The current code works
  44494. * though, and has a smaller compiler footprint.
  44495. */
  44496. if ((val >= (duk_int32_t) DUK_BC_BC_MIN - (duk_int32_t) DUK_BC_LDINT_BIAS) &&
  44497. (val <= (duk_int32_t) DUK_BC_BC_MAX - (duk_int32_t) DUK_BC_LDINT_BIAS)) {
  44498. DUK_DDD(DUK_DDDPRINT("emit LDINT to reg %ld for %ld", (long) reg, (long) val));
  44499. duk__emit_a_bc(comp_ctx, DUK_OP_LDINT | op_flags, reg, (duk_regconst_t) (val + (duk_int32_t) DUK_BC_LDINT_BIAS));
  44500. } else {
  44501. duk_int32_t hi = val >> DUK_BC_LDINTX_SHIFT;
  44502. duk_int32_t lo = val & ((((duk_int32_t) 1) << DUK_BC_LDINTX_SHIFT) - 1);
  44503. DUK_ASSERT(lo >= 0);
  44504. DUK_DDD(DUK_DDDPRINT("emit LDINT+LDINTX to reg %ld for %ld -> hi %ld, lo %ld",
  44505. (long) reg, (long) val, (long) hi, (long) lo));
  44506. duk__emit_a_bc(comp_ctx, DUK_OP_LDINT | op_flags, reg, (duk_regconst_t) (hi + (duk_int32_t) DUK_BC_LDINT_BIAS));
  44507. duk__emit_a_bc(comp_ctx, DUK_OP_LDINTX | op_flags, reg, (duk_regconst_t) lo);
  44508. }
  44509. }
  44510. DUK_LOCAL void duk__emit_load_int32(duk_compiler_ctx *comp_ctx, duk_reg_t reg, duk_int32_t val) {
  44511. duk__emit_load_int32_raw(comp_ctx, reg, val, 0 /*op_flags*/);
  44512. }
  44513. #if defined(DUK_USE_SHUFFLE_TORTURE)
  44514. /* Used by duk__emit*() calls so that we don't shuffle the loadints that
  44515. * are needed to handle indirect opcodes.
  44516. */
  44517. DUK_LOCAL void duk__emit_load_int32_noshuffle(duk_compiler_ctx *comp_ctx, duk_reg_t reg, duk_int32_t val) {
  44518. duk__emit_load_int32_raw(comp_ctx, reg, val, DUK__EMIT_FLAG_NO_SHUFFLE_A /*op_flags*/);
  44519. }
  44520. #else
  44521. DUK_LOCAL void duk__emit_load_int32_noshuffle(duk_compiler_ctx *comp_ctx, duk_reg_t reg, duk_int32_t val) {
  44522. /* When torture not enabled, can just use the same helper because
  44523. * 'reg' won't get spilled.
  44524. */
  44525. DUK_ASSERT(reg <= DUK_BC_A_MAX);
  44526. duk__emit_load_int32(comp_ctx, reg, val);
  44527. }
  44528. #endif
  44529. DUK_LOCAL void duk__emit_jump(duk_compiler_ctx *comp_ctx, duk_int_t target_pc) {
  44530. duk_hbuffer_dynamic *h;
  44531. duk_int_t curr_pc;
  44532. duk_int_t offset;
  44533. h = comp_ctx->curr_func.h_code;
  44534. curr_pc = (duk_int_t) (DUK_HBUFFER_GET_SIZE(h) / sizeof(duk_compiler_instr));
  44535. offset = (duk_int_t) target_pc - (duk_int_t) curr_pc - 1;
  44536. DUK_ASSERT(offset + DUK_BC_JUMP_BIAS >= DUK_BC_ABC_MIN);
  44537. DUK_ASSERT(offset + DUK_BC_JUMP_BIAS <= DUK_BC_ABC_MAX);
  44538. duk__emit_abc(comp_ctx, DUK_OP_JUMP, (duk_regconst_t) (offset + DUK_BC_JUMP_BIAS));
  44539. }
  44540. DUK_LOCAL duk_int_t duk__emit_jump_empty(duk_compiler_ctx *comp_ctx) {
  44541. duk_int_t ret;
  44542. ret = duk__get_current_pc(comp_ctx); /* useful for patching jumps later */
  44543. duk__emit_abc(comp_ctx, DUK_OP_JUMP, 0);
  44544. return ret;
  44545. }
  44546. /* Insert an empty jump in the middle of code emitted earlier. This is
  44547. * currently needed for compiling for-in.
  44548. */
  44549. DUK_LOCAL void duk__insert_jump_entry(duk_compiler_ctx *comp_ctx, duk_int_t jump_pc) {
  44550. duk_hbuffer_dynamic *h;
  44551. #if defined(DUK_USE_PC2LINE)
  44552. duk_int_t line;
  44553. #endif
  44554. duk_compiler_instr instr;
  44555. duk_size_t offset;
  44556. h = comp_ctx->curr_func.h_code;
  44557. #if defined(DUK_USE_PC2LINE)
  44558. line = comp_ctx->curr_token.start_line; /* approximation, close enough */
  44559. #endif
  44560. instr.ins = DUK_ENC_OP_ABC(DUK_OP_JUMP, 0);
  44561. #if defined(DUK_USE_PC2LINE)
  44562. instr.line = line;
  44563. #endif
  44564. offset = jump_pc * sizeof(duk_compiler_instr);
  44565. duk_hbuffer_insert_bytes(comp_ctx->thr, h, offset, (duk_uint8_t *) &instr, sizeof(instr));
  44566. }
  44567. /* Does not assume that jump_pc contains a DUK_OP_JUMP previously; this is intentional
  44568. * to allow e.g. an INVALID opcode be overwritten with a JUMP (label management uses this).
  44569. */
  44570. DUK_LOCAL void duk__patch_jump(duk_compiler_ctx *comp_ctx, duk_int_t jump_pc, duk_int_t target_pc) {
  44571. duk_compiler_instr *instr;
  44572. duk_int_t offset;
  44573. /* allow negative PCs, behave as a no-op */
  44574. if (jump_pc < 0) {
  44575. DUK_DDD(DUK_DDDPRINT("duk__patch_jump(): nop call, jump_pc=%ld (<0), target_pc=%ld",
  44576. (long) jump_pc, (long) target_pc));
  44577. return;
  44578. }
  44579. DUK_ASSERT(jump_pc >= 0);
  44580. /* XXX: range assert */
  44581. instr = duk__get_instr_ptr(comp_ctx, jump_pc);
  44582. DUK_ASSERT(instr != NULL);
  44583. /* XXX: range assert */
  44584. offset = target_pc - jump_pc - 1;
  44585. instr->ins = DUK_ENC_OP_ABC(DUK_OP_JUMP, offset + DUK_BC_JUMP_BIAS);
  44586. DUK_DDD(DUK_DDDPRINT("duk__patch_jump(): jump_pc=%ld, target_pc=%ld, offset=%ld",
  44587. (long) jump_pc, (long) target_pc, (long) offset));
  44588. }
  44589. DUK_LOCAL void duk__patch_jump_here(duk_compiler_ctx *comp_ctx, duk_int_t jump_pc) {
  44590. duk__patch_jump(comp_ctx, jump_pc, duk__get_current_pc(comp_ctx));
  44591. }
  44592. DUK_LOCAL void duk__patch_trycatch(duk_compiler_ctx *comp_ctx, duk_int_t trycatch_pc, duk_regconst_t reg_catch, duk_regconst_t const_varname, duk_small_uint_t flags) {
  44593. duk_compiler_instr *instr;
  44594. instr = duk__get_instr_ptr(comp_ctx, trycatch_pc);
  44595. DUK_ASSERT(instr != NULL);
  44596. DUK_ASSERT_DISABLE(flags >= DUK_BC_A_MIN);
  44597. DUK_ASSERT(flags <= DUK_BC_A_MAX);
  44598. DUK_ASSERT((reg_catch & DUK__CONST_MARKER) == 0);
  44599. const_varname = const_varname & (~DUK__CONST_MARKER);
  44600. if (reg_catch > DUK_BC_B_MAX || const_varname > DUK_BC_C_MAX) {
  44601. /* Catch attempts to use out-of-range reg/const. Without this
  44602. * check Duktape 0.12.0 could generate invalid code which caused
  44603. * an assert failure on execution. This error is triggered e.g.
  44604. * for functions with a lot of constants and a try-catch statement.
  44605. * Shuffling or opcode semantics change is needed to fix the issue.
  44606. * See: test-bug-trycatch-many-constants.js.
  44607. */
  44608. DUK_D(DUK_DPRINT("failed to patch trycatch: flags=%ld, reg_catch=%ld, const_varname=%ld (0x%08lx)",
  44609. (long) flags, (long) reg_catch, (long) const_varname, (long) const_varname));
  44610. DUK_ERROR(comp_ctx->thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_REG_LIMIT);
  44611. }
  44612. instr->ins = DUK_ENC_OP_A_B_C(DUK_OP_TRYCATCH, flags, reg_catch, const_varname);
  44613. }
  44614. DUK_LOCAL void duk__emit_if_false_skip(duk_compiler_ctx *comp_ctx, duk_regconst_t regconst) {
  44615. duk__emit_a_b_c(comp_ctx,
  44616. DUK_OP_IF | DUK__EMIT_FLAG_NO_SHUFFLE_A | DUK__EMIT_FLAG_NO_SHUFFLE_C,
  44617. 0 /*false*/,
  44618. regconst,
  44619. 0 /*unused*/);
  44620. }
  44621. DUK_LOCAL void duk__emit_if_true_skip(duk_compiler_ctx *comp_ctx, duk_regconst_t regconst) {
  44622. duk__emit_a_b_c(comp_ctx,
  44623. DUK_OP_IF | DUK__EMIT_FLAG_NO_SHUFFLE_A | DUK__EMIT_FLAG_NO_SHUFFLE_C,
  44624. 1 /*true*/,
  44625. regconst,
  44626. 0 /*unused*/);
  44627. }
  44628. DUK_LOCAL void duk__emit_invalid(duk_compiler_ctx *comp_ctx) {
  44629. duk__emit_extraop_bc(comp_ctx, DUK_EXTRAOP_INVALID, 0);
  44630. }
  44631. /*
  44632. * Peephole optimizer for finished bytecode.
  44633. *
  44634. * Does not remove opcodes; currently only straightens out unconditional
  44635. * jump chains which are generated by several control structures.
  44636. */
  44637. DUK_LOCAL void duk__peephole_optimize_bytecode(duk_compiler_ctx *comp_ctx) {
  44638. duk_hbuffer_dynamic *h;
  44639. duk_compiler_instr *bc;
  44640. duk_small_uint_t iter;
  44641. duk_int_t i, n;
  44642. duk_int_t count_opt;
  44643. h = comp_ctx->curr_func.h_code;
  44644. DUK_ASSERT(h != NULL);
  44645. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(h));
  44646. bc = (duk_compiler_instr *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(comp_ctx->thr->heap, h);
  44647. #if defined(DUK_USE_BUFLEN16)
  44648. /* No need to assert, buffer size maximum is 0xffff. */
  44649. #else
  44650. DUK_ASSERT(DUK_HBUFFER_GET_SIZE(h) / sizeof(duk_compiler_instr) <= DUK_INT_MAX); /* bytecode limits */
  44651. #endif
  44652. n = (duk_int_t) (DUK_HBUFFER_GET_SIZE(h) / sizeof(duk_compiler_instr));
  44653. for (iter = 0; iter < DUK_COMPILER_PEEPHOLE_MAXITER; iter++) {
  44654. count_opt = 0;
  44655. for (i = 0; i < n; i++) {
  44656. duk_instr_t ins;
  44657. duk_int_t target_pc1;
  44658. duk_int_t target_pc2;
  44659. ins = bc[i].ins;
  44660. if (DUK_DEC_OP(ins) != DUK_OP_JUMP) {
  44661. continue;
  44662. }
  44663. target_pc1 = i + 1 + DUK_DEC_ABC(ins) - DUK_BC_JUMP_BIAS;
  44664. DUK_DDD(DUK_DDDPRINT("consider jump at pc %ld; target_pc=%ld", (long) i, (long) target_pc1));
  44665. DUK_ASSERT(target_pc1 >= 0);
  44666. DUK_ASSERT(target_pc1 < n);
  44667. /* Note: if target_pc1 == i, we'll optimize a jump to itself.
  44668. * This does not need to be checked for explicitly; the case
  44669. * is rare and max iter breaks us out.
  44670. */
  44671. ins = bc[target_pc1].ins;
  44672. if (DUK_DEC_OP(ins) != DUK_OP_JUMP) {
  44673. continue;
  44674. }
  44675. target_pc2 = target_pc1 + 1 + DUK_DEC_ABC(ins) - DUK_BC_JUMP_BIAS;
  44676. DUK_DDD(DUK_DDDPRINT("optimizing jump at pc %ld; old target is %ld -> new target is %ld",
  44677. (long) i, (long) target_pc1, (long) target_pc2));
  44678. bc[i].ins = DUK_ENC_OP_ABC(DUK_OP_JUMP, target_pc2 - (i + 1) + DUK_BC_JUMP_BIAS);
  44679. count_opt++;
  44680. }
  44681. DUK_DD(DUK_DDPRINT("optimized %ld jumps on peephole round %ld", (long) count_opt, (long) (iter + 1)));
  44682. if (count_opt == 0) {
  44683. break;
  44684. }
  44685. }
  44686. }
  44687. /*
  44688. * Intermediate value helpers
  44689. */
  44690. #define DUK__ISREG(comp_ctx,x) (((x) & DUK__CONST_MARKER) == 0)
  44691. #define DUK__ISCONST(comp_ctx,x) (((x) & DUK__CONST_MARKER) != 0)
  44692. #define DUK__ISTEMP(comp_ctx,x) (DUK__ISREG((comp_ctx), (x)) && (duk_regconst_t) (x) >= (duk_regconst_t) ((comp_ctx)->curr_func.temp_first))
  44693. #define DUK__GETTEMP(comp_ctx) ((comp_ctx)->curr_func.temp_next)
  44694. #define DUK__SETTEMP(comp_ctx,x) ((comp_ctx)->curr_func.temp_next = (x)) /* dangerous: must only lower (temp_max not updated) */
  44695. #define DUK__SETTEMP_CHECKMAX(comp_ctx,x) duk__settemp_checkmax((comp_ctx),(x))
  44696. #define DUK__ALLOCTEMP(comp_ctx) duk__alloctemp((comp_ctx))
  44697. #define DUK__ALLOCTEMPS(comp_ctx,count) duk__alloctemps((comp_ctx),(count))
  44698. /* Flags for intermediate value coercions. A flag for using a forced reg
  44699. * is not needed, the forced_reg argument suffices and generates better
  44700. * code (it is checked as it is used).
  44701. */
  44702. #define DUK__IVAL_FLAG_ALLOW_CONST (1 << 0) /* allow a constant to be returned */
  44703. #define DUK__IVAL_FLAG_REQUIRE_TEMP (1 << 1) /* require a (mutable) temporary as a result */
  44704. #define DUK__IVAL_FLAG_REQUIRE_SHORT (1 << 2) /* require a short (8-bit) reg/const which fits into bytecode B/C slot */
  44705. /* XXX: some code might benefit from DUK__SETTEMP_IFTEMP(ctx,x) */
  44706. DUK_LOCAL void duk__copy_ispec(duk_compiler_ctx *comp_ctx, duk_ispec *src, duk_ispec *dst) {
  44707. duk_context *ctx = (duk_context *) comp_ctx->thr;
  44708. dst->t = src->t;
  44709. dst->regconst = src->regconst;
  44710. duk_copy(ctx, src->valstack_idx, dst->valstack_idx);
  44711. }
  44712. DUK_LOCAL void duk__copy_ivalue(duk_compiler_ctx *comp_ctx, duk_ivalue *src, duk_ivalue *dst) {
  44713. duk_context *ctx = (duk_context *) comp_ctx->thr;
  44714. dst->t = src->t;
  44715. dst->op = src->op;
  44716. dst->x1.t = src->x1.t;
  44717. dst->x1.regconst = src->x1.regconst;
  44718. dst->x2.t = src->x2.t;
  44719. dst->x2.regconst = src->x2.regconst;
  44720. duk_copy(ctx, src->x1.valstack_idx, dst->x1.valstack_idx);
  44721. duk_copy(ctx, src->x2.valstack_idx, dst->x2.valstack_idx);
  44722. }
  44723. /* XXX: to util */
  44724. DUK_LOCAL duk_bool_t duk__is_whole_get_int32(duk_double_t x, duk_int32_t *ival) {
  44725. duk_small_int_t c;
  44726. duk_int32_t t;
  44727. c = DUK_FPCLASSIFY(x);
  44728. if (c == DUK_FP_NORMAL || (c == DUK_FP_ZERO && !DUK_SIGNBIT(x))) {
  44729. /* Don't allow negative zero as it will cause trouble with
  44730. * LDINT+LDINTX. But positive zero is OK.
  44731. */
  44732. t = (duk_int32_t) x;
  44733. if ((duk_double_t) t == x) {
  44734. *ival = t;
  44735. return 1;
  44736. }
  44737. }
  44738. return 0;
  44739. }
  44740. DUK_LOCAL duk_reg_t duk__alloctemps(duk_compiler_ctx *comp_ctx, duk_small_int_t num) {
  44741. duk_reg_t res;
  44742. res = comp_ctx->curr_func.temp_next;
  44743. comp_ctx->curr_func.temp_next += num;
  44744. if (comp_ctx->curr_func.temp_next > DUK__MAX_TEMPS) { /* == DUK__MAX_TEMPS is OK */
  44745. DUK_ERROR(comp_ctx->thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_TEMP_LIMIT);
  44746. }
  44747. /* maintain highest 'used' temporary, needed to figure out nregs of function */
  44748. if (comp_ctx->curr_func.temp_next > comp_ctx->curr_func.temp_max) {
  44749. comp_ctx->curr_func.temp_max = comp_ctx->curr_func.temp_next;
  44750. }
  44751. return res;
  44752. }
  44753. DUK_LOCAL duk_reg_t duk__alloctemp(duk_compiler_ctx *comp_ctx) {
  44754. return duk__alloctemps(comp_ctx, 1);
  44755. }
  44756. DUK_LOCAL void duk__settemp_checkmax(duk_compiler_ctx *comp_ctx, duk_reg_t temp_next) {
  44757. comp_ctx->curr_func.temp_next = temp_next;
  44758. if (temp_next > comp_ctx->curr_func.temp_max) {
  44759. comp_ctx->curr_func.temp_max = temp_next;
  44760. }
  44761. }
  44762. /* get const for value at valstack top */
  44763. DUK_LOCAL duk_regconst_t duk__getconst(duk_compiler_ctx *comp_ctx) {
  44764. duk_hthread *thr = comp_ctx->thr;
  44765. duk_context *ctx = (duk_context *) thr;
  44766. duk_compiler_func *f = &comp_ctx->curr_func;
  44767. duk_tval *tv1;
  44768. duk_int_t i, n, n_check;
  44769. n = (duk_int_t) duk_get_length(ctx, f->consts_idx);
  44770. tv1 = duk_get_tval(ctx, -1);
  44771. DUK_ASSERT(tv1 != NULL);
  44772. #if defined(DUK_USE_FASTINT)
  44773. /* Explicit check for fastint downgrade. */
  44774. DUK_TVAL_CHKFAST_INPLACE(tv1);
  44775. #endif
  44776. /* Sanity workaround for handling functions with a large number of
  44777. * constants at least somewhat reasonably. Otherwise checking whether
  44778. * we already have the constant would grow very slow (as it is O(N^2)).
  44779. */
  44780. n_check = (n > DUK__GETCONST_MAX_CONSTS_CHECK ? DUK__GETCONST_MAX_CONSTS_CHECK : n);
  44781. for (i = 0; i < n_check; i++) {
  44782. duk_tval *tv2 = DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, f->h_consts, i);
  44783. /* Strict equality is NOT enough, because we cannot use the same
  44784. * constant for e.g. +0 and -0.
  44785. */
  44786. if (duk_js_samevalue(tv1, tv2)) {
  44787. DUK_DDD(DUK_DDDPRINT("reused existing constant for %!T -> const index %ld",
  44788. (duk_tval *) tv1, (long) i));
  44789. duk_pop(ctx);
  44790. return (duk_regconst_t) (i | DUK__CONST_MARKER);
  44791. }
  44792. }
  44793. if (n > DUK__MAX_CONSTS) {
  44794. DUK_ERROR(comp_ctx->thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_CONST_LIMIT);
  44795. }
  44796. DUK_DDD(DUK_DDDPRINT("allocating new constant for %!T -> const index %ld",
  44797. (duk_tval *) tv1, (long) n));
  44798. (void) duk_put_prop_index(ctx, f->consts_idx, n); /* invalidates tv1, tv2 */
  44799. return (duk_regconst_t) (n | DUK__CONST_MARKER);
  44800. }
  44801. /* Get the value represented by an duk_ispec to a register or constant.
  44802. * The caller can control the result by indicating whether or not:
  44803. *
  44804. * (1) a constant is allowed (sometimes the caller needs the result to
  44805. * be in a register)
  44806. *
  44807. * (2) a temporary register is required (usually when caller requires
  44808. * the register to be safely mutable; normally either a bound
  44809. * register or a temporary register are both OK)
  44810. *
  44811. * (3) a forced register target needs to be used
  44812. *
  44813. * Bytecode may be emitted to generate the necessary value. The return
  44814. * value is either a register or a constant.
  44815. */
  44816. DUK_LOCAL
  44817. duk_regconst_t duk__ispec_toregconst_raw(duk_compiler_ctx *comp_ctx,
  44818. duk_ispec *x,
  44819. duk_reg_t forced_reg,
  44820. duk_small_uint_t flags) {
  44821. duk_hthread *thr = comp_ctx->thr;
  44822. duk_context *ctx = (duk_context *) thr;
  44823. DUK_DDD(DUK_DDDPRINT("duk__ispec_toregconst_raw(): x={%ld:%ld:%!T}, "
  44824. "forced_reg=%ld, flags 0x%08lx: allow_const=%ld require_temp=%ld require_short=%ld",
  44825. (long) x->t,
  44826. (long) x->regconst,
  44827. (duk_tval *) duk_get_tval(ctx, x->valstack_idx),
  44828. (long) forced_reg,
  44829. (unsigned long) flags,
  44830. (long) ((flags & DUK__IVAL_FLAG_ALLOW_CONST) ? 1 : 0),
  44831. (long) ((flags & DUK__IVAL_FLAG_REQUIRE_TEMP) ? 1 : 0),
  44832. (long) ((flags & DUK__IVAL_FLAG_REQUIRE_SHORT) ? 1 : 0)));
  44833. switch (x->t) {
  44834. case DUK_ISPEC_VALUE: {
  44835. duk_tval *tv;
  44836. tv = duk_get_tval(ctx, x->valstack_idx);
  44837. DUK_ASSERT(tv != NULL);
  44838. switch (DUK_TVAL_GET_TAG(tv)) {
  44839. case DUK_TAG_UNDEFINED: {
  44840. /* Note: although there is no 'undefined' literal, undefined
  44841. * values can occur during compilation as a result of e.g.
  44842. * the 'void' operator.
  44843. */
  44844. duk_reg_t dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  44845. duk__emit_extraop_bc(comp_ctx, DUK_EXTRAOP_LDUNDEF, (duk_regconst_t) dest);
  44846. return (duk_regconst_t) dest;
  44847. }
  44848. case DUK_TAG_NULL: {
  44849. duk_reg_t dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  44850. duk__emit_extraop_bc(comp_ctx, DUK_EXTRAOP_LDNULL, (duk_regconst_t) dest);
  44851. return (duk_regconst_t) dest;
  44852. }
  44853. case DUK_TAG_BOOLEAN: {
  44854. duk_reg_t dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  44855. duk__emit_extraop_bc(comp_ctx,
  44856. (DUK_TVAL_GET_BOOLEAN(tv) ? DUK_EXTRAOP_LDTRUE : DUK_EXTRAOP_LDFALSE),
  44857. (duk_regconst_t) dest);
  44858. return (duk_regconst_t) dest;
  44859. }
  44860. case DUK_TAG_POINTER: {
  44861. DUK_UNREACHABLE();
  44862. break;
  44863. }
  44864. case DUK_TAG_STRING: {
  44865. duk_hstring *h;
  44866. duk_reg_t dest;
  44867. duk_regconst_t constidx;
  44868. h = DUK_TVAL_GET_STRING(tv);
  44869. DUK_UNREF(h);
  44870. DUK_ASSERT(h != NULL);
  44871. #if 0 /* XXX: to be implemented? */
  44872. /* Use special opcodes to load short strings */
  44873. if (DUK_HSTRING_GET_BYTELEN(h) <= 2) {
  44874. /* Encode into a single opcode (18 bits can encode 1-2 bytes + length indicator) */
  44875. } else if (DUK_HSTRING_GET_BYTELEN(h) <= 6) {
  44876. /* Encode into a double constant (53 bits can encode 6*8 = 48 bits + 3-bit length */
  44877. }
  44878. #endif
  44879. duk_dup(ctx, x->valstack_idx);
  44880. constidx = duk__getconst(comp_ctx);
  44881. if (flags & DUK__IVAL_FLAG_ALLOW_CONST) {
  44882. return constidx;
  44883. }
  44884. dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  44885. duk__emit_a_bc(comp_ctx, DUK_OP_LDCONST, (duk_regconst_t) dest, constidx);
  44886. return (duk_regconst_t) dest;
  44887. }
  44888. case DUK_TAG_OBJECT: {
  44889. DUK_UNREACHABLE();
  44890. break;
  44891. }
  44892. case DUK_TAG_BUFFER: {
  44893. DUK_UNREACHABLE();
  44894. break;
  44895. }
  44896. case DUK_TAG_LIGHTFUNC: {
  44897. DUK_UNREACHABLE();
  44898. break;
  44899. }
  44900. #if defined(DUK_USE_FASTINT)
  44901. case DUK_TAG_FASTINT:
  44902. #endif
  44903. default: {
  44904. /* number */
  44905. duk_reg_t dest;
  44906. duk_regconst_t constidx;
  44907. duk_double_t dval;
  44908. duk_int32_t ival;
  44909. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  44910. dval = DUK_TVAL_GET_NUMBER(tv);
  44911. if (!(flags & DUK__IVAL_FLAG_ALLOW_CONST)) {
  44912. /* A number can be loaded either through a constant, using
  44913. * LDINT, or using LDINT+LDINTX. LDINT is always a size win,
  44914. * LDINT+LDINTX is not if the constant is used multiple times.
  44915. * Currently always prefer LDINT+LDINTX over a double constant.
  44916. */
  44917. if (duk__is_whole_get_int32(dval, &ival)) {
  44918. dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  44919. duk__emit_load_int32(comp_ctx, dest, ival);
  44920. return (duk_regconst_t) dest;
  44921. }
  44922. }
  44923. duk_dup(ctx, x->valstack_idx);
  44924. constidx = duk__getconst(comp_ctx);
  44925. if (flags & DUK__IVAL_FLAG_ALLOW_CONST) {
  44926. return constidx;
  44927. } else {
  44928. dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  44929. duk__emit_a_bc(comp_ctx, DUK_OP_LDCONST, (duk_regconst_t) dest, constidx);
  44930. return (duk_regconst_t) dest;
  44931. }
  44932. }
  44933. } /* end switch */
  44934. }
  44935. case DUK_ISPEC_REGCONST: {
  44936. if ((x->regconst & DUK__CONST_MARKER) && !(flags & DUK__IVAL_FLAG_ALLOW_CONST)) {
  44937. duk_reg_t dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  44938. duk__emit_a_bc(comp_ctx, DUK_OP_LDCONST, (duk_regconst_t) dest, x->regconst);
  44939. return (duk_regconst_t) dest;
  44940. } else {
  44941. if (forced_reg >= 0) {
  44942. if (x->regconst != (duk_regconst_t) forced_reg) {
  44943. duk__emit_a_bc(comp_ctx, DUK_OP_LDREG, forced_reg, x->regconst);
  44944. }
  44945. return (duk_regconst_t) forced_reg;
  44946. } else {
  44947. if ((flags & DUK__IVAL_FLAG_REQUIRE_TEMP) && !DUK__ISTEMP(comp_ctx, x->regconst)) {
  44948. duk_reg_t dest = DUK__ALLOCTEMP(comp_ctx);
  44949. duk__emit_a_bc(comp_ctx, DUK_OP_LDREG, (duk_regconst_t) dest, x->regconst);
  44950. return (duk_regconst_t) dest;
  44951. } else {
  44952. return x->regconst;
  44953. }
  44954. }
  44955. }
  44956. }
  44957. default: {
  44958. break;
  44959. }
  44960. }
  44961. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR);
  44962. return 0;
  44963. }
  44964. DUK_LOCAL void duk__ispec_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ispec *x, duk_reg_t forced_reg) {
  44965. DUK_ASSERT(forced_reg >= 0);
  44966. (void) duk__ispec_toregconst_raw(comp_ctx, x, forced_reg, 0 /*flags*/);
  44967. }
  44968. /* Coerce an duk_ivalue to a 'plain' value by generating the necessary
  44969. * arithmetic operations, property access, or variable access bytecode.
  44970. * The duk_ivalue argument ('x') is converted into a plain value as a
  44971. * side effect.
  44972. */
  44973. DUK_LOCAL void duk__ivalue_toplain_raw(duk_compiler_ctx *comp_ctx, duk_ivalue *x, duk_reg_t forced_reg) {
  44974. duk_hthread *thr = comp_ctx->thr;
  44975. duk_context *ctx = (duk_context *) thr;
  44976. DUK_DDD(DUK_DDDPRINT("duk__ivalue_toplain_raw(): x={t=%ld,op=%ld,x1={%ld:%ld:%!T},x2={%ld:%ld:%!T}}, "
  44977. "forced_reg=%ld",
  44978. (long) x->t, (long) x->op,
  44979. (long) x->x1.t, (long) x->x1.regconst,
  44980. (duk_tval *) duk_get_tval(ctx, x->x1.valstack_idx),
  44981. (long) x->x2.t, (long) x->x2.regconst,
  44982. (duk_tval *) duk_get_tval(ctx, x->x2.valstack_idx),
  44983. (long) forced_reg));
  44984. switch (x->t) {
  44985. case DUK_IVAL_PLAIN: {
  44986. return;
  44987. }
  44988. /* XXX: support unary arithmetic ivalues (useful?) */
  44989. case DUK_IVAL_ARITH:
  44990. case DUK_IVAL_ARITH_EXTRAOP: {
  44991. duk_regconst_t arg1;
  44992. duk_regconst_t arg2;
  44993. duk_reg_t dest;
  44994. duk_tval *tv1;
  44995. duk_tval *tv2;
  44996. DUK_DDD(DUK_DDDPRINT("arith to plain conversion"));
  44997. /* inline arithmetic check for constant values */
  44998. /* XXX: use the exactly same arithmetic function here as in executor */
  44999. if (x->x1.t == DUK_ISPEC_VALUE && x->x2.t == DUK_ISPEC_VALUE && x->t == DUK_IVAL_ARITH) {
  45000. tv1 = duk_get_tval(ctx, x->x1.valstack_idx);
  45001. tv2 = duk_get_tval(ctx, x->x2.valstack_idx);
  45002. DUK_ASSERT(tv1 != NULL);
  45003. DUK_ASSERT(tv2 != NULL);
  45004. DUK_DDD(DUK_DDDPRINT("arith: tv1=%!T, tv2=%!T",
  45005. (duk_tval *) tv1,
  45006. (duk_tval *) tv2));
  45007. if (DUK_TVAL_IS_NUMBER(tv1) && DUK_TVAL_IS_NUMBER(tv2)) {
  45008. duk_double_t d1 = DUK_TVAL_GET_NUMBER(tv1);
  45009. duk_double_t d2 = DUK_TVAL_GET_NUMBER(tv2);
  45010. duk_double_t d3;
  45011. duk_bool_t accept = 1;
  45012. DUK_DDD(DUK_DDDPRINT("arith inline check: d1=%lf, d2=%lf, op=%ld",
  45013. (double) d1, (double) d2, (long) x->op));
  45014. switch (x->op) {
  45015. case DUK_OP_ADD: d3 = d1 + d2; break;
  45016. case DUK_OP_SUB: d3 = d1 - d2; break;
  45017. case DUK_OP_MUL: d3 = d1 * d2; break;
  45018. case DUK_OP_DIV: d3 = d1 / d2; break;
  45019. default: accept = 0; break;
  45020. }
  45021. if (accept) {
  45022. duk_double_union du;
  45023. du.d = d3;
  45024. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&du);
  45025. d3 = du.d;
  45026. x->t = DUK_IVAL_PLAIN;
  45027. DUK_ASSERT(x->x1.t == DUK_ISPEC_VALUE);
  45028. DUK_TVAL_SET_NUMBER(tv1, d3); /* old value is number: no refcount */
  45029. return;
  45030. }
  45031. } else if (x->op == DUK_OP_ADD && DUK_TVAL_IS_STRING(tv1) && DUK_TVAL_IS_STRING(tv2)) {
  45032. /* inline string concatenation */
  45033. duk_dup(ctx, x->x1.valstack_idx);
  45034. duk_dup(ctx, x->x2.valstack_idx);
  45035. duk_concat(ctx, 2);
  45036. duk_replace(ctx, x->x1.valstack_idx);
  45037. x->t = DUK_IVAL_PLAIN;
  45038. DUK_ASSERT(x->x1.t == DUK_ISPEC_VALUE);
  45039. return;
  45040. }
  45041. }
  45042. arg1 = duk__ispec_toregconst_raw(comp_ctx, &x->x1, -1, DUK__IVAL_FLAG_ALLOW_CONST | DUK__IVAL_FLAG_REQUIRE_SHORT /*flags*/);
  45043. arg2 = duk__ispec_toregconst_raw(comp_ctx, &x->x2, -1, DUK__IVAL_FLAG_ALLOW_CONST | DUK__IVAL_FLAG_REQUIRE_SHORT /*flags*/);
  45044. /* If forced reg, use it as destination. Otherwise try to
  45045. * use either coerced ispec if it is a temporary.
  45046. *
  45047. * When using extraops, avoid reusing arg2 as dest because that
  45048. * would lead to an LDREG shuffle below. We still can't guarantee
  45049. * dest != arg2 because we may have a forced_reg.
  45050. */
  45051. if (forced_reg >= 0) {
  45052. dest = forced_reg;
  45053. } else if (DUK__ISTEMP(comp_ctx, arg1)) {
  45054. dest = (duk_reg_t) arg1;
  45055. } else if (DUK__ISTEMP(comp_ctx, arg2) && x->t != DUK_IVAL_ARITH_EXTRAOP) {
  45056. dest = (duk_reg_t) arg2;
  45057. } else {
  45058. dest = DUK__ALLOCTEMP(comp_ctx);
  45059. }
  45060. /* Extraop arithmetic opcodes must have destination same as
  45061. * first source. If second source matches destination we need
  45062. * a temporary register to avoid clobbering the second source.
  45063. *
  45064. * XXX: change calling code to avoid this situation in most cases.
  45065. */
  45066. if (x->t == DUK_IVAL_ARITH_EXTRAOP) {
  45067. if (!(DUK__ISREG(comp_ctx, arg1) && (duk_reg_t) arg1 == dest)) {
  45068. if (DUK__ISREG(comp_ctx, arg2) && (duk_reg_t) arg2 == dest) {
  45069. /* arg2 would be clobbered so reassign it to a temp. */
  45070. duk_reg_t tempreg;
  45071. tempreg = DUK__ALLOCTEMP(comp_ctx);
  45072. duk__emit_a_bc(comp_ctx, DUK_OP_LDREG, tempreg, arg2);
  45073. arg2 = tempreg;
  45074. }
  45075. if (DUK__ISREG(comp_ctx, arg1)) {
  45076. duk__emit_a_bc(comp_ctx, DUK_OP_LDREG, dest, arg1);
  45077. } else {
  45078. DUK_ASSERT(DUK__ISCONST(comp_ctx, arg1));
  45079. duk__emit_a_bc(comp_ctx, DUK_OP_LDCONST, dest, arg1);
  45080. }
  45081. }
  45082. /* Note: special DUK__EMIT_FLAG_B_IS_TARGETSOURCE
  45083. * used to indicate that B is both a source and a
  45084. * target register. When shuffled, it needs to be
  45085. * both input and output shuffled.
  45086. */
  45087. DUK_ASSERT(DUK__ISREG(comp_ctx, dest));
  45088. duk__emit_extraop_b_c(comp_ctx,
  45089. x->op | DUK__EMIT_FLAG_B_IS_TARGET |
  45090. DUK__EMIT_FLAG_B_IS_TARGETSOURCE,
  45091. (duk_regconst_t) dest,
  45092. (duk_regconst_t) arg2);
  45093. } else {
  45094. DUK_ASSERT(DUK__ISREG(comp_ctx, dest));
  45095. duk__emit_a_b_c(comp_ctx, x->op, (duk_regconst_t) dest, arg1, arg2);
  45096. }
  45097. x->t = DUK_IVAL_PLAIN;
  45098. x->x1.t = DUK_ISPEC_REGCONST;
  45099. x->x1.regconst = (duk_regconst_t) dest;
  45100. return;
  45101. }
  45102. case DUK_IVAL_PROP: {
  45103. /* XXX: very similar to DUK_IVAL_ARITH - merge? */
  45104. duk_regconst_t arg1;
  45105. duk_regconst_t arg2;
  45106. duk_reg_t dest;
  45107. /* Need a short reg/const, does not have to be a mutable temp. */
  45108. arg1 = duk__ispec_toregconst_raw(comp_ctx, &x->x1, -1, DUK__IVAL_FLAG_ALLOW_CONST | DUK__IVAL_FLAG_REQUIRE_SHORT /*flags*/);
  45109. arg2 = duk__ispec_toregconst_raw(comp_ctx, &x->x2, -1, DUK__IVAL_FLAG_ALLOW_CONST | DUK__IVAL_FLAG_REQUIRE_SHORT /*flags*/);
  45110. /* Pick a destination register. If either base value or key
  45111. * happens to be a temp value, reuse it as the destination.
  45112. *
  45113. * XXX: The temp must be a "mutable" one, i.e. such that no
  45114. * other expression is using it anymore. Here this should be
  45115. * the case because the value of a property access expression
  45116. * is neither the base nor the key, but the lookup result.
  45117. */
  45118. if (forced_reg >= 0) {
  45119. dest = forced_reg;
  45120. } else if (DUK__ISTEMP(comp_ctx, arg1)) {
  45121. dest = (duk_reg_t) arg1;
  45122. } else if (DUK__ISTEMP(comp_ctx, arg2)) {
  45123. dest = (duk_reg_t) arg2;
  45124. } else {
  45125. dest = DUK__ALLOCTEMP(comp_ctx);
  45126. }
  45127. duk__emit_a_b_c(comp_ctx, DUK_OP_GETPROP, (duk_regconst_t) dest, arg1, arg2);
  45128. x->t = DUK_IVAL_PLAIN;
  45129. x->x1.t = DUK_ISPEC_REGCONST;
  45130. x->x1.regconst = (duk_regconst_t) dest;
  45131. return;
  45132. }
  45133. case DUK_IVAL_VAR: {
  45134. /* x1 must be a string */
  45135. duk_reg_t dest;
  45136. duk_reg_t reg_varbind;
  45137. duk_regconst_t rc_varname;
  45138. DUK_ASSERT(x->x1.t == DUK_ISPEC_VALUE);
  45139. duk_dup(ctx, x->x1.valstack_idx);
  45140. if (duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname)) {
  45141. x->t = DUK_IVAL_PLAIN;
  45142. x->x1.t = DUK_ISPEC_REGCONST;
  45143. x->x1.regconst = (duk_regconst_t) reg_varbind;
  45144. } else {
  45145. dest = (forced_reg >= 0 ? forced_reg : DUK__ALLOCTEMP(comp_ctx));
  45146. duk__emit_a_bc(comp_ctx, DUK_OP_GETVAR, (duk_regconst_t) dest, rc_varname);
  45147. x->t = DUK_IVAL_PLAIN;
  45148. x->x1.t = DUK_ISPEC_REGCONST;
  45149. x->x1.regconst = (duk_regconst_t) dest;
  45150. }
  45151. return;
  45152. }
  45153. case DUK_IVAL_NONE:
  45154. default: {
  45155. break;
  45156. }
  45157. }
  45158. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR);
  45159. return;
  45160. }
  45161. /* evaluate to plain value, no forced register (temp/bound reg both ok) */
  45162. DUK_LOCAL void duk__ivalue_toplain(duk_compiler_ctx *comp_ctx, duk_ivalue *x) {
  45163. duk__ivalue_toplain_raw(comp_ctx, x, -1 /*forced_reg*/);
  45164. }
  45165. /* evaluate to final form (e.g. coerce GETPROP to code), throw away temp */
  45166. DUK_LOCAL void duk__ivalue_toplain_ignore(duk_compiler_ctx *comp_ctx, duk_ivalue *x) {
  45167. duk_reg_t temp;
  45168. /* If duk__ivalue_toplain_raw() allocates a temp, forget it and
  45169. * restore next temp state.
  45170. */
  45171. temp = DUK__GETTEMP(comp_ctx);
  45172. duk__ivalue_toplain_raw(comp_ctx, x, -1 /*forced_reg*/);
  45173. DUK__SETTEMP(comp_ctx, temp);
  45174. }
  45175. /* Coerce an duk_ivalue to a register or constant; result register may
  45176. * be a temp or a bound register.
  45177. *
  45178. * The duk_ivalue argument ('x') is converted into a regconst as a
  45179. * side effect.
  45180. */
  45181. DUK_LOCAL
  45182. duk_regconst_t duk__ivalue_toregconst_raw(duk_compiler_ctx *comp_ctx,
  45183. duk_ivalue *x,
  45184. duk_reg_t forced_reg,
  45185. duk_small_uint_t flags) {
  45186. duk_hthread *thr = comp_ctx->thr;
  45187. duk_context *ctx = (duk_context *) thr;
  45188. duk_regconst_t reg;
  45189. DUK_UNREF(thr);
  45190. DUK_UNREF(ctx);
  45191. DUK_DDD(DUK_DDDPRINT("duk__ivalue_toregconst_raw(): x={t=%ld,op=%ld,x1={%ld:%ld:%!T},x2={%ld:%ld:%!T}}, "
  45192. "forced_reg=%ld, flags 0x%08lx: allow_const=%ld require_temp=%ld require_short=%ld",
  45193. (long) x->t, (long) x->op,
  45194. (long) x->x1.t, (long) x->x1.regconst,
  45195. (duk_tval *) duk_get_tval(ctx, x->x1.valstack_idx),
  45196. (long) x->x2.t, (long) x->x2.regconst,
  45197. (duk_tval *) duk_get_tval(ctx, x->x2.valstack_idx),
  45198. (long) forced_reg,
  45199. (unsigned long) flags,
  45200. (long) ((flags & DUK__IVAL_FLAG_ALLOW_CONST) ? 1 : 0),
  45201. (long) ((flags & DUK__IVAL_FLAG_REQUIRE_TEMP) ? 1 : 0),
  45202. (long) ((flags & DUK__IVAL_FLAG_REQUIRE_SHORT) ? 1 : 0)));
  45203. /* first coerce to a plain value */
  45204. duk__ivalue_toplain_raw(comp_ctx, x, forced_reg);
  45205. DUK_ASSERT(x->t == DUK_IVAL_PLAIN);
  45206. /* then to a register */
  45207. reg = duk__ispec_toregconst_raw(comp_ctx, &x->x1, forced_reg, flags);
  45208. x->x1.t = DUK_ISPEC_REGCONST;
  45209. x->x1.regconst = reg;
  45210. return reg;
  45211. }
  45212. DUK_LOCAL duk_reg_t duk__ivalue_toreg(duk_compiler_ctx *comp_ctx, duk_ivalue *x) {
  45213. return duk__ivalue_toregconst_raw(comp_ctx, x, -1, 0 /*flags*/);
  45214. }
  45215. #if 0 /* unused */
  45216. DUK_LOCAL duk_reg_t duk__ivalue_totempreg(duk_compiler_ctx *comp_ctx, duk_ivalue *x) {
  45217. return duk__ivalue_toregconst_raw(comp_ctx, x, -1, DUK__IVAL_FLAG_REQUIRE_TEMP /*flags*/);
  45218. }
  45219. #endif
  45220. DUK_LOCAL void duk__ivalue_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ivalue *x, duk_int_t forced_reg) {
  45221. DUK_ASSERT(forced_reg >= 0);
  45222. (void) duk__ivalue_toregconst_raw(comp_ctx, x, forced_reg, 0 /*flags*/);
  45223. }
  45224. DUK_LOCAL duk_regconst_t duk__ivalue_toregconst(duk_compiler_ctx *comp_ctx, duk_ivalue *x) {
  45225. return duk__ivalue_toregconst_raw(comp_ctx, x, -1, DUK__IVAL_FLAG_ALLOW_CONST /*flags*/);
  45226. }
  45227. /* The issues below can be solved with better flags */
  45228. /* XXX: many operations actually want toforcedtemp() -- brand new temp? */
  45229. /* XXX: need a toplain_ignore() which will only coerce a value to a temp
  45230. * register if it might have a side effect. Side-effect free values do not
  45231. * need to be coerced.
  45232. */
  45233. /*
  45234. * Identifier handling
  45235. */
  45236. DUK_LOCAL duk_reg_t duk__lookup_active_register_binding(duk_compiler_ctx *comp_ctx) {
  45237. duk_hthread *thr = comp_ctx->thr;
  45238. duk_context *ctx = (duk_context *) thr;
  45239. duk_hstring *h_varname;
  45240. duk_reg_t ret;
  45241. DUK_DDD(DUK_DDDPRINT("resolving identifier reference to '%!T'",
  45242. (duk_tval *) duk_get_tval(ctx, -1)));
  45243. /*
  45244. * Special name handling
  45245. */
  45246. h_varname = duk_get_hstring(ctx, -1);
  45247. DUK_ASSERT(h_varname != NULL);
  45248. if (h_varname == DUK_HTHREAD_STRING_LC_ARGUMENTS(thr)) {
  45249. DUK_DDD(DUK_DDDPRINT("flagging function as accessing 'arguments'"));
  45250. comp_ctx->curr_func.id_access_arguments = 1;
  45251. }
  45252. /*
  45253. * Inside one or more 'with' statements fall back to slow path always.
  45254. * (See e.g. test-stmt-with.js.)
  45255. */
  45256. if (comp_ctx->curr_func.with_depth > 0) {
  45257. DUK_DDD(DUK_DDDPRINT("identifier lookup inside a 'with' -> fall back to slow path"));
  45258. goto slow_path;
  45259. }
  45260. /*
  45261. * Any catch bindings ("catch (e)") also affect identifier binding.
  45262. *
  45263. * Currently, the varmap is modified for the duration of the catch
  45264. * clause to ensure any identifier accesses with the catch variable
  45265. * name will use slow path.
  45266. */
  45267. duk_get_prop(ctx, comp_ctx->curr_func.varmap_idx);
  45268. if (duk_is_number(ctx, -1)) {
  45269. ret = duk_to_int(ctx, -1);
  45270. duk_pop(ctx);
  45271. } else {
  45272. duk_pop(ctx);
  45273. goto slow_path;
  45274. }
  45275. DUK_DDD(DUK_DDDPRINT("identifier lookup -> reg %ld", (long) ret));
  45276. return ret;
  45277. slow_path:
  45278. DUK_DDD(DUK_DDDPRINT("identifier lookup -> slow path"));
  45279. comp_ctx->curr_func.id_access_slow = 1;
  45280. return (duk_reg_t) -1;
  45281. }
  45282. /* Lookup an identifier name in the current varmap, indicating whether the
  45283. * identifier is register-bound and if not, allocating a constant for the
  45284. * identifier name. Returns 1 if register-bound, 0 otherwise. Caller can
  45285. * also check (out_reg_varbind >= 0) to check whether or not identifier is
  45286. * register bound. The caller must NOT use out_rc_varname at all unless
  45287. * return code is 0 or out_reg_varbind is < 0; this is becuase out_rc_varname
  45288. * is unsigned and doesn't have a "unused" / none value.
  45289. */
  45290. DUK_LOCAL duk_bool_t duk__lookup_lhs(duk_compiler_ctx *comp_ctx, duk_reg_t *out_reg_varbind, duk_regconst_t *out_rc_varname) {
  45291. duk_hthread *thr = comp_ctx->thr;
  45292. duk_context *ctx = (duk_context *) thr;
  45293. duk_reg_t reg_varbind;
  45294. duk_regconst_t rc_varname;
  45295. /* [ ... varname ] */
  45296. duk_dup_top(ctx);
  45297. reg_varbind = duk__lookup_active_register_binding(comp_ctx);
  45298. if (reg_varbind >= 0) {
  45299. *out_reg_varbind = reg_varbind;
  45300. *out_rc_varname = 0; /* duk_regconst_t is unsigned, so use 0 as dummy value (ignored by caller) */
  45301. duk_pop(ctx);
  45302. return 1;
  45303. } else {
  45304. rc_varname = duk__getconst(comp_ctx);
  45305. *out_reg_varbind = -1;
  45306. *out_rc_varname = rc_varname;
  45307. return 0;
  45308. }
  45309. }
  45310. /*
  45311. * Label handling
  45312. *
  45313. * Labels are initially added with flags prohibiting both break and continue.
  45314. * When the statement type is finally uncovered (after potentially multiple
  45315. * labels), all the labels are updated to allow/prohibit break and continue.
  45316. */
  45317. DUK_LOCAL void duk__add_label(duk_compiler_ctx *comp_ctx, duk_hstring *h_label, duk_int_t pc_label, duk_int_t label_id) {
  45318. duk_hthread *thr = comp_ctx->thr;
  45319. duk_context *ctx = (duk_context *) thr;
  45320. duk_size_t n;
  45321. duk_size_t new_size;
  45322. duk_uint8_t *p;
  45323. duk_labelinfo *li_start, *li;
  45324. /* Duplicate (shadowing) labels are not allowed, except for the empty
  45325. * labels (which are used as default labels for switch and iteration
  45326. * statements).
  45327. *
  45328. * We could also allow shadowing of non-empty pending labels without any
  45329. * other issues than breaking the required label shadowing requirements
  45330. * of the E5 specification, see Section 12.12.
  45331. */
  45332. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, comp_ctx->curr_func.h_labelinfos);
  45333. li_start = (duk_labelinfo *) p;
  45334. li = (duk_labelinfo *) (p + DUK_HBUFFER_GET_SIZE(comp_ctx->curr_func.h_labelinfos));
  45335. n = (duk_size_t) (li - li_start);
  45336. while (li > li_start) {
  45337. li--;
  45338. if (li->h_label == h_label && h_label != DUK_HTHREAD_STRING_EMPTY_STRING(thr)) {
  45339. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_DUPLICATE_LABEL);
  45340. }
  45341. }
  45342. duk_push_hstring(ctx, h_label);
  45343. DUK_ASSERT(n <= DUK_UARRIDX_MAX); /* label limits */
  45344. (void) duk_put_prop_index(ctx, comp_ctx->curr_func.labelnames_idx, (duk_uarridx_t) n);
  45345. new_size = (n + 1) * sizeof(duk_labelinfo);
  45346. duk_hbuffer_resize(thr, comp_ctx->curr_func.h_labelinfos, new_size, new_size);
  45347. /* XXX: spare handling, slow now */
  45348. /* relookup after possible realloc */
  45349. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, comp_ctx->curr_func.h_labelinfos);
  45350. li_start = (duk_labelinfo *) p;
  45351. DUK_UNREF(li_start); /* silence scan-build warning */
  45352. li = (duk_labelinfo *) (p + DUK_HBUFFER_GET_SIZE(comp_ctx->curr_func.h_labelinfos));
  45353. li--;
  45354. /* Labels can be used for iteration statements but also for other statements,
  45355. * in particular a label can be used for a block statement. All cases of a
  45356. * named label accept a 'break' so that flag is set here. Iteration statements
  45357. * also allow 'continue', so that flag is updated when we figure out the
  45358. * statement type.
  45359. */
  45360. li->flags = DUK_LABEL_FLAG_ALLOW_BREAK;
  45361. li->label_id = label_id;
  45362. li->h_label = h_label;
  45363. li->catch_depth = comp_ctx->curr_func.catch_depth; /* catch depth from current func */
  45364. li->pc_label = pc_label;
  45365. DUK_DDD(DUK_DDDPRINT("registered label: flags=0x%08lx, id=%ld, name=%!O, catch_depth=%ld, pc_label=%ld",
  45366. (unsigned long) li->flags, (long) li->label_id, (duk_heaphdr *) li->h_label,
  45367. (long) li->catch_depth, (long) li->pc_label));
  45368. }
  45369. /* Update all labels with matching label_id. */
  45370. DUK_LOCAL void duk__update_label_flags(duk_compiler_ctx *comp_ctx, duk_int_t label_id, duk_small_uint_t flags) {
  45371. duk_uint8_t *p;
  45372. duk_labelinfo *li_start, *li;
  45373. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(comp_ctx->thr->heap, comp_ctx->curr_func.h_labelinfos);
  45374. li_start = (duk_labelinfo *) p;
  45375. li = (duk_labelinfo *) (p + DUK_HBUFFER_GET_SIZE(comp_ctx->curr_func.h_labelinfos));
  45376. /* Match labels starting from latest; once label_id no longer matches, we can
  45377. * safely exit without checking the rest of the labels (only the topmost labels
  45378. * are ever updated).
  45379. */
  45380. while (li > li_start) {
  45381. li--;
  45382. if (li->label_id != label_id) {
  45383. break;
  45384. }
  45385. DUK_DDD(DUK_DDDPRINT("updating (overwriting) label flags for li=%p, label_id=%ld, flags=%ld",
  45386. (void *) li, (long) label_id, (long) flags));
  45387. li->flags = flags;
  45388. }
  45389. }
  45390. /* Lookup active label information. Break/continue distinction is necessary to handle switch
  45391. * statement related labels correctly: a switch will only catch a 'break', not a 'continue'.
  45392. *
  45393. * An explicit label cannot appear multiple times in the active set, but empty labels (unlabelled
  45394. * iteration and switch statements) can. A break will match the closest unlabelled or labelled
  45395. * statement. A continue will match the closest unlabelled or labelled iteration statement. It is
  45396. * a syntax error if a continue matches a labelled switch statement; because an explicit label cannot
  45397. * be duplicated, the continue cannot match any valid label outside the switch.
  45398. *
  45399. * A side effect of these rules is that a LABEL statement related to a switch should never actually
  45400. * catch a continue abrupt completion at run-time. Hence an INVALID opcode can be placed in the
  45401. * continue slot of the switch's LABEL statement.
  45402. */
  45403. /* XXX: awkward, especially the bunch of separate output values -> output struct? */
  45404. DUK_LOCAL void duk__lookup_active_label(duk_compiler_ctx *comp_ctx, duk_hstring *h_label, duk_bool_t is_break, duk_int_t *out_label_id, duk_int_t *out_label_catch_depth, duk_int_t *out_label_pc, duk_bool_t *out_is_closest) {
  45405. duk_hthread *thr = comp_ctx->thr;
  45406. duk_context *ctx = (duk_context *) thr;
  45407. duk_uint8_t *p;
  45408. duk_labelinfo *li_start, *li_end, *li;
  45409. duk_bool_t match = 0;
  45410. DUK_DDD(DUK_DDDPRINT("looking up active label: label='%!O', is_break=%ld",
  45411. (duk_heaphdr *) h_label, (long) is_break));
  45412. DUK_UNREF(ctx);
  45413. p = (duk_uint8_t *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, comp_ctx->curr_func.h_labelinfos);
  45414. li_start = (duk_labelinfo *) p;
  45415. li_end = (duk_labelinfo *) (p + DUK_HBUFFER_GET_SIZE(comp_ctx->curr_func.h_labelinfos));
  45416. li = li_end;
  45417. /* Match labels starting from latest label because there can be duplicate empty
  45418. * labels in the label set.
  45419. */
  45420. while (li > li_start) {
  45421. li--;
  45422. if (li->h_label != h_label) {
  45423. DUK_DDD(DUK_DDDPRINT("labelinfo[%ld] ->'%!O' != %!O",
  45424. (long) (li - li_start),
  45425. (duk_heaphdr *) li->h_label,
  45426. (duk_heaphdr *) h_label));
  45427. continue;
  45428. }
  45429. DUK_DDD(DUK_DDDPRINT("labelinfo[%ld] -> '%!O' label name matches (still need to check type)",
  45430. (long) (li - li_start), (duk_heaphdr *) h_label));
  45431. /* currently all labels accept a break, so no explicit check for it now */
  45432. DUK_ASSERT(li->flags & DUK_LABEL_FLAG_ALLOW_BREAK);
  45433. if (is_break) {
  45434. /* break matches always */
  45435. match = 1;
  45436. break;
  45437. } else if (li->flags & DUK_LABEL_FLAG_ALLOW_CONTINUE) {
  45438. /* iteration statements allow continue */
  45439. match = 1;
  45440. break;
  45441. } else {
  45442. /* continue matched this label -- we can only continue if this is the empty
  45443. * label, for which duplication is allowed, and thus there is hope of
  45444. * finding a match deeper in the label stack.
  45445. */
  45446. if (h_label != DUK_HTHREAD_STRING_EMPTY_STRING(thr)) {
  45447. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_LABEL);
  45448. } else {
  45449. DUK_DDD(DUK_DDDPRINT("continue matched an empty label which does not "
  45450. "allow a continue -> continue lookup deeper in label stack"));
  45451. }
  45452. }
  45453. }
  45454. /* XXX: match flag is awkward, rework */
  45455. if (!match) {
  45456. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_LABEL);
  45457. }
  45458. DUK_DDD(DUK_DDDPRINT("label match: %!O -> label_id %ld, catch_depth=%ld, pc_label=%ld",
  45459. (duk_heaphdr *) h_label, (long) li->label_id,
  45460. (long) li->catch_depth, (long) li->pc_label));
  45461. *out_label_id = li->label_id;
  45462. *out_label_catch_depth = li->catch_depth;
  45463. *out_label_pc = li->pc_label;
  45464. *out_is_closest = (li == li_end - 1);
  45465. }
  45466. DUK_LOCAL void duk__reset_labels_to_length(duk_compiler_ctx *comp_ctx, duk_int_t len) {
  45467. duk_hthread *thr = comp_ctx->thr;
  45468. duk_context *ctx = (duk_context *) thr;
  45469. duk_size_t new_size;
  45470. /* XXX: duk_set_length */
  45471. new_size = sizeof(duk_labelinfo) * (duk_size_t) len;
  45472. duk_push_int(ctx, len);
  45473. duk_put_prop_stridx(ctx, comp_ctx->curr_func.labelnames_idx, DUK_STRIDX_LENGTH);
  45474. duk_hbuffer_resize(thr, comp_ctx->curr_func.h_labelinfos, new_size, new_size); /* XXX: spare handling */
  45475. }
  45476. /*
  45477. * Expression parsing: duk__expr_nud(), duk__expr_led(), duk__expr_lbp(), and helpers.
  45478. *
  45479. * - duk__expr_nud(): ("null denotation"): process prev_token as a "start" of an expression (e.g. literal)
  45480. * - duk__expr_led(): ("left denotation"): process prev_token in the "middle" of an expression (e.g. operator)
  45481. * - duk__expr_lbp(): ("left-binding power"): return left-binding power of curr_token
  45482. */
  45483. /* object literal key tracking flags */
  45484. #define DUK__OBJ_LIT_KEY_PLAIN (1 << 0) /* key encountered as a plain property */
  45485. #define DUK__OBJ_LIT_KEY_GET (1 << 1) /* key encountered as a getter */
  45486. #define DUK__OBJ_LIT_KEY_SET (1 << 2) /* key encountered as a setter */
  45487. DUK_LOCAL void duk__nud_array_literal(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  45488. duk_hthread *thr = comp_ctx->thr;
  45489. duk_reg_t reg_obj; /* result reg */
  45490. duk_reg_t reg_temp; /* temp reg */
  45491. duk_reg_t temp_start; /* temp reg value for start of loop */
  45492. duk_small_uint_t max_init_values; /* max # of values initialized in one MPUTARR set */
  45493. duk_small_uint_t num_values; /* number of values in current MPUTARR set */
  45494. duk_uarridx_t curr_idx; /* current (next) array index */
  45495. duk_uarridx_t start_idx; /* start array index of current MPUTARR set */
  45496. duk_uarridx_t init_idx; /* last array index explicitly initialized, +1 */
  45497. duk_bool_t require_comma; /* next loop requires a comma */
  45498. /* DUK_TOK_LBRACKET already eaten, current token is right after that */
  45499. DUK_ASSERT(comp_ctx->prev_token.t == DUK_TOK_LBRACKET);
  45500. max_init_values = DUK__MAX_ARRAY_INIT_VALUES; /* XXX: depend on available temps? */
  45501. reg_obj = DUK__ALLOCTEMP(comp_ctx);
  45502. duk__emit_extraop_b_c(comp_ctx,
  45503. DUK_EXTRAOP_NEWARR | DUK__EMIT_FLAG_B_IS_TARGET,
  45504. reg_obj,
  45505. 0); /* XXX: patch initial size afterwards? */
  45506. temp_start = DUK__GETTEMP(comp_ctx);
  45507. /*
  45508. * Emit initializers in sets of maximum max_init_values.
  45509. * Corner cases such as single value initializers do not have
  45510. * special handling now.
  45511. *
  45512. * Elided elements must not be emitted as 'undefined' values,
  45513. * because such values would be enumerable (which is incorrect).
  45514. * Also note that trailing elisions must be reflected in the
  45515. * length of the final array but cause no elements to be actually
  45516. * inserted.
  45517. */
  45518. curr_idx = 0;
  45519. init_idx = 0; /* tracks maximum initialized index + 1 */
  45520. start_idx = 0;
  45521. require_comma = 0;
  45522. for (;;) {
  45523. num_values = 0;
  45524. DUK__SETTEMP(comp_ctx, temp_start);
  45525. if (comp_ctx->curr_token.t == DUK_TOK_RBRACKET) {
  45526. break;
  45527. }
  45528. for (;;) {
  45529. if (comp_ctx->curr_token.t == DUK_TOK_RBRACKET) {
  45530. /* the outer loop will recheck and exit */
  45531. break;
  45532. }
  45533. /* comma check */
  45534. if (require_comma) {
  45535. if (comp_ctx->curr_token.t == DUK_TOK_COMMA) {
  45536. /* comma after a value, expected */
  45537. duk__advance(comp_ctx);
  45538. require_comma = 0;
  45539. continue;
  45540. } else {
  45541. goto syntax_error;
  45542. }
  45543. } else {
  45544. if (comp_ctx->curr_token.t == DUK_TOK_COMMA) {
  45545. /* elision - flush */
  45546. curr_idx++;
  45547. duk__advance(comp_ctx);
  45548. /* if num_values > 0, MPUTARR emitted by outer loop after break */
  45549. break;
  45550. }
  45551. }
  45552. /* else an array initializer element */
  45553. /* initial index */
  45554. if (num_values == 0) {
  45555. start_idx = curr_idx;
  45556. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  45557. duk__emit_load_int32(comp_ctx, reg_temp, (duk_int32_t) start_idx);
  45558. }
  45559. reg_temp = DUK__ALLOCTEMP(comp_ctx); /* alloc temp just in case, to update max temp */
  45560. DUK__SETTEMP(comp_ctx, reg_temp);
  45561. duk__expr_toforcedreg(comp_ctx, res, DUK__BP_COMMA /*rbp_flags*/, reg_temp /*forced_reg*/);
  45562. DUK__SETTEMP(comp_ctx, reg_temp + 1);
  45563. num_values++;
  45564. curr_idx++;
  45565. require_comma = 1;
  45566. if (num_values >= max_init_values) {
  45567. /* MPUTARR emitted by outer loop */
  45568. break;
  45569. }
  45570. }
  45571. if (num_values > 0) {
  45572. /* - A is a source register (it's not a write target, but used
  45573. * to identify the target object) but can be shuffled.
  45574. * - B cannot be shuffled normally because it identifies a range
  45575. * of registers, the emitter has special handling for this
  45576. * (the "no shuffle" flag must not be set).
  45577. * - C is a non-register number and cannot be shuffled, but
  45578. * never needs to be.
  45579. */
  45580. duk__emit_a_b_c(comp_ctx,
  45581. DUK_OP_MPUTARR |
  45582. DUK__EMIT_FLAG_NO_SHUFFLE_C |
  45583. DUK__EMIT_FLAG_A_IS_SOURCE,
  45584. (duk_regconst_t) reg_obj,
  45585. (duk_regconst_t) temp_start,
  45586. (duk_regconst_t) num_values);
  45587. init_idx = start_idx + num_values;
  45588. /* num_values and temp_start reset at top of outer loop */
  45589. }
  45590. }
  45591. DUK_ASSERT(comp_ctx->curr_token.t == DUK_TOK_RBRACKET);
  45592. duk__advance(comp_ctx);
  45593. DUK_DDD(DUK_DDDPRINT("array literal done, curridx=%ld, initidx=%ld",
  45594. (long) curr_idx, (long) init_idx));
  45595. /* trailing elisions? */
  45596. if (curr_idx > init_idx) {
  45597. /* yes, must set array length explicitly */
  45598. DUK_DDD(DUK_DDDPRINT("array literal has trailing elisions which affect its length"));
  45599. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  45600. duk__emit_load_int32(comp_ctx, reg_temp, (duk_int_t) curr_idx);
  45601. duk__emit_extraop_b_c(comp_ctx,
  45602. DUK_EXTRAOP_SETALEN,
  45603. (duk_regconst_t) reg_obj,
  45604. (duk_regconst_t) reg_temp);
  45605. }
  45606. DUK__SETTEMP(comp_ctx, temp_start);
  45607. res->t = DUK_IVAL_PLAIN;
  45608. res->x1.t = DUK_ISPEC_REGCONST;
  45609. res->x1.regconst = (duk_regconst_t) reg_obj;
  45610. return;
  45611. syntax_error:
  45612. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_ARRAY_LITERAL);
  45613. }
  45614. /* duplicate/invalid key checks; returns 1 if syntax error */
  45615. DUK_LOCAL duk_bool_t duk__nud_object_literal_key_check(duk_compiler_ctx *comp_ctx, duk_small_uint_t new_key_flags) {
  45616. duk_hthread *thr = comp_ctx->thr;
  45617. duk_context *ctx = (duk_context *) thr;
  45618. duk_small_uint_t key_flags;
  45619. /* [ ... key_obj key ] */
  45620. DUK_ASSERT(duk_is_string(ctx, -1));
  45621. /*
  45622. * 'key_obj' tracks keys encountered so far by associating an
  45623. * integer with flags with already encountered keys. The checks
  45624. * below implement E5 Section 11.1.5, step 4 for production:
  45625. *
  45626. * PropertyNameAndValueList: PropertyNameAndValueList , PropertyAssignment
  45627. */
  45628. duk_dup(ctx, -1); /* [ ... key_obj key key ] */
  45629. duk_get_prop(ctx, -3); /* [ ... key_obj key val ] */
  45630. key_flags = duk_to_int(ctx, -1);
  45631. duk_pop(ctx); /* [ ... key_obj key ] */
  45632. if (new_key_flags & DUK__OBJ_LIT_KEY_PLAIN) {
  45633. if ((key_flags & DUK__OBJ_LIT_KEY_PLAIN) && comp_ctx->curr_func.is_strict) {
  45634. /* step 4.a */
  45635. DUK_DDD(DUK_DDDPRINT("duplicate key: plain key appears twice in strict mode"));
  45636. return 1;
  45637. }
  45638. if (key_flags & (DUK__OBJ_LIT_KEY_GET | DUK__OBJ_LIT_KEY_SET)) {
  45639. /* step 4.c */
  45640. DUK_DDD(DUK_DDDPRINT("duplicate key: plain key encountered after setter/getter"));
  45641. return 1;
  45642. }
  45643. } else {
  45644. if (key_flags & DUK__OBJ_LIT_KEY_PLAIN) {
  45645. /* step 4.b */
  45646. DUK_DDD(DUK_DDDPRINT("duplicate key: getter/setter encountered after plain key"));
  45647. return 1;
  45648. }
  45649. if (key_flags & new_key_flags) {
  45650. /* step 4.d */
  45651. DUK_DDD(DUK_DDDPRINT("duplicate key: getter/setter encountered twice"));
  45652. return 1;
  45653. }
  45654. }
  45655. new_key_flags |= key_flags;
  45656. DUK_DDD(DUK_DDDPRINT("setting/updating key %!T flags: 0x%08lx -> 0x%08lx",
  45657. (duk_tval *) duk_get_tval(ctx, -1),
  45658. (unsigned long) key_flags,
  45659. (unsigned long) new_key_flags));
  45660. duk_dup(ctx, -1);
  45661. duk_push_int(ctx, new_key_flags); /* [ ... key_obj key key flags ] */
  45662. duk_put_prop(ctx, -4); /* [ ... key_obj key ] */
  45663. return 0;
  45664. }
  45665. DUK_LOCAL void duk__nud_object_literal(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  45666. duk_hthread *thr = comp_ctx->thr;
  45667. duk_context *ctx = (duk_context *) thr;
  45668. duk_reg_t reg_obj; /* result reg */
  45669. duk_reg_t reg_key; /* temp reg for key literal */
  45670. duk_reg_t reg_temp; /* temp reg */
  45671. duk_reg_t temp_start; /* temp reg value for start of loop */
  45672. duk_small_uint_t max_init_pairs; /* max # of key-value pairs initialized in one MPUTOBJ set */
  45673. duk_small_uint_t num_pairs; /* number of pairs in current MPUTOBJ set */
  45674. duk_bool_t first; /* first value: comma must not precede the value */
  45675. duk_bool_t is_set, is_get; /* temps */
  45676. DUK_ASSERT(comp_ctx->prev_token.t == DUK_TOK_LCURLY);
  45677. max_init_pairs = DUK__MAX_OBJECT_INIT_PAIRS; /* XXX: depend on available temps? */
  45678. reg_obj = DUK__ALLOCTEMP(comp_ctx);
  45679. duk__emit_extraop_b_c(comp_ctx,
  45680. DUK_EXTRAOP_NEWOBJ | DUK__EMIT_FLAG_B_IS_TARGET,
  45681. reg_obj,
  45682. 0); /* XXX: patch initial size afterwards? */
  45683. temp_start = DUK__GETTEMP(comp_ctx);
  45684. /* temp object for tracking / detecting duplicate keys */
  45685. duk_push_object(ctx);
  45686. /*
  45687. * Emit initializers in sets of maximum max_init_pairs keys.
  45688. * Setter/getter is handled separately and terminates the
  45689. * current set of initializer values. Corner cases such as
  45690. * single value initializers do not have special handling now.
  45691. */
  45692. first = 1;
  45693. for (;;) {
  45694. num_pairs = 0;
  45695. DUK__SETTEMP(comp_ctx, temp_start);
  45696. if (comp_ctx->curr_token.t == DUK_TOK_RCURLY) {
  45697. break;
  45698. }
  45699. for (;;) {
  45700. /*
  45701. * Three possible element formats:
  45702. * 1) PropertyName : AssignmentExpression
  45703. * 2) get PropertyName () { FunctionBody }
  45704. * 3) set PropertyName ( PropertySetParameterList ) { FunctionBody }
  45705. *
  45706. * PropertyName can be IdentifierName (includes reserved words), a string
  45707. * literal, or a number literal. Note that IdentifierName allows 'get' and
  45708. * 'set' too, so we need to look ahead to the next token to distinguish:
  45709. *
  45710. * { get : 1 }
  45711. *
  45712. * and
  45713. *
  45714. * { get foo() { return 1 } }
  45715. * { get get() { return 1 } } // 'get' as getter propertyname
  45716. *
  45717. * Finally, a trailing comma is allowed.
  45718. *
  45719. * Key name is coerced to string at compile time (and ends up as a
  45720. * a string constant) even for numeric keys (e.g. "{1:'foo'}").
  45721. * These could be emitted using e.g. LDINT, but that seems hardly
  45722. * worth the effort and would increase code size.
  45723. */
  45724. DUK_DDD(DUK_DDDPRINT("object literal inner loop, curr_token->t = %ld",
  45725. (long) comp_ctx->curr_token.t));
  45726. if (comp_ctx->curr_token.t == DUK_TOK_RCURLY) {
  45727. /* the outer loop will recheck and exit */
  45728. break;
  45729. }
  45730. if (num_pairs >= max_init_pairs) {
  45731. /* MPUTOBJ emitted by outer loop */
  45732. break;
  45733. }
  45734. if (first) {
  45735. first = 0;
  45736. } else {
  45737. if (comp_ctx->curr_token.t != DUK_TOK_COMMA) {
  45738. goto syntax_error;
  45739. }
  45740. duk__advance(comp_ctx);
  45741. if (comp_ctx->curr_token.t == DUK_TOK_RCURLY) {
  45742. /* trailing comma followed by rcurly */
  45743. break;
  45744. }
  45745. }
  45746. /* advance to get one step of lookup */
  45747. duk__advance(comp_ctx);
  45748. /* NOTE: "get" and "set" are not officially ReservedWords and the lexer
  45749. * currently treats them always like ordinary identifiers (DUK_TOK_GET
  45750. * and DUK_TOK_SET are unused). They need to be detected based on the
  45751. * identifier string content.
  45752. */
  45753. is_get = (comp_ctx->prev_token.t == DUK_TOK_IDENTIFIER &&
  45754. comp_ctx->prev_token.str1 == DUK_HTHREAD_STRING_GET(thr));
  45755. is_set = (comp_ctx->prev_token.t == DUK_TOK_IDENTIFIER &&
  45756. comp_ctx->prev_token.str1 == DUK_HTHREAD_STRING_SET(thr));
  45757. if ((is_get || is_set) && comp_ctx->curr_token.t != DUK_TOK_COLON) {
  45758. /* getter/setter */
  45759. duk_int_t fnum;
  45760. if (comp_ctx->curr_token.t_nores == DUK_TOK_IDENTIFIER ||
  45761. comp_ctx->curr_token.t_nores == DUK_TOK_STRING) {
  45762. /* same handling for identifiers and strings */
  45763. DUK_ASSERT(comp_ctx->curr_token.str1 != NULL);
  45764. duk_push_hstring(ctx, comp_ctx->curr_token.str1);
  45765. } else if (comp_ctx->curr_token.t == DUK_TOK_NUMBER) {
  45766. duk_push_number(ctx, comp_ctx->curr_token.num);
  45767. duk_to_string(ctx, -1);
  45768. } else {
  45769. goto syntax_error;
  45770. }
  45771. DUK_ASSERT(duk_is_string(ctx, -1));
  45772. if (duk__nud_object_literal_key_check(comp_ctx,
  45773. (is_get ? DUK__OBJ_LIT_KEY_GET : DUK__OBJ_LIT_KEY_SET))) {
  45774. goto syntax_error;
  45775. }
  45776. reg_key = duk__getconst(comp_ctx);
  45777. if (num_pairs > 0) {
  45778. /* - A is a source register (it's not a write target, but used
  45779. * to identify the target object) but can be shuffled.
  45780. * - B cannot be shuffled normally because it identifies a range
  45781. * of registers, the emitter has special handling for this
  45782. * (the "no shuffle" flag must not be set).
  45783. * - C is a non-register number and cannot be shuffled, but
  45784. * never needs to be.
  45785. */
  45786. duk__emit_a_b_c(comp_ctx,
  45787. DUK_OP_MPUTOBJ |
  45788. DUK__EMIT_FLAG_NO_SHUFFLE_C |
  45789. DUK__EMIT_FLAG_A_IS_SOURCE,
  45790. reg_obj,
  45791. temp_start,
  45792. num_pairs);
  45793. num_pairs = 0;
  45794. DUK__SETTEMP(comp_ctx, temp_start);
  45795. }
  45796. /* curr_token = get/set name */
  45797. fnum = duk__parse_func_like_fnum(comp_ctx, 0 /*is_decl*/, 1 /*is_setget*/);
  45798. DUK_ASSERT(DUK__GETTEMP(comp_ctx) == temp_start);
  45799. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  45800. duk__emit_a_bc(comp_ctx,
  45801. DUK_OP_LDCONST,
  45802. (duk_regconst_t) reg_temp,
  45803. (duk_regconst_t) reg_key);
  45804. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  45805. duk__emit_a_bc(comp_ctx,
  45806. DUK_OP_CLOSURE,
  45807. (duk_regconst_t) reg_temp,
  45808. (duk_regconst_t) fnum);
  45809. /* Slot C is used in a non-standard fashion (range of regs),
  45810. * emitter code has special handling for it (must not set the
  45811. * "no shuffle" flag).
  45812. */
  45813. duk__emit_extraop_b_c(comp_ctx,
  45814. (is_get ? DUK_EXTRAOP_INITGET : DUK_EXTRAOP_INITSET),
  45815. reg_obj,
  45816. temp_start); /* temp_start+0 = key, temp_start+1 = closure */
  45817. DUK__SETTEMP(comp_ctx, temp_start);
  45818. } else {
  45819. /* normal key/value */
  45820. if (comp_ctx->prev_token.t_nores == DUK_TOK_IDENTIFIER ||
  45821. comp_ctx->prev_token.t_nores == DUK_TOK_STRING) {
  45822. /* same handling for identifiers and strings */
  45823. DUK_ASSERT(comp_ctx->prev_token.str1 != NULL);
  45824. duk_push_hstring(ctx, comp_ctx->prev_token.str1);
  45825. } else if (comp_ctx->prev_token.t == DUK_TOK_NUMBER) {
  45826. duk_push_number(ctx, comp_ctx->prev_token.num);
  45827. duk_to_string(ctx, -1);
  45828. } else {
  45829. goto syntax_error;
  45830. }
  45831. DUK_ASSERT(duk_is_string(ctx, -1));
  45832. if (duk__nud_object_literal_key_check(comp_ctx, DUK__OBJ_LIT_KEY_PLAIN)) {
  45833. goto syntax_error;
  45834. }
  45835. reg_key = duk__getconst(comp_ctx);
  45836. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  45837. duk__emit_a_bc(comp_ctx,
  45838. DUK_OP_LDCONST,
  45839. (duk_regconst_t) reg_temp,
  45840. (duk_regconst_t) reg_key);
  45841. duk__advance_expect(comp_ctx, DUK_TOK_COLON);
  45842. reg_temp = DUK__ALLOCTEMP(comp_ctx); /* alloc temp just in case, to update max temp */
  45843. DUK__SETTEMP(comp_ctx, reg_temp);
  45844. duk__expr_toforcedreg(comp_ctx, res, DUK__BP_COMMA /*rbp_flags*/, reg_temp /*forced_reg*/);
  45845. DUK__SETTEMP(comp_ctx, reg_temp + 1);
  45846. num_pairs++;
  45847. }
  45848. }
  45849. if (num_pairs > 0) {
  45850. /* See MPUTOBJ comments above. */
  45851. duk__emit_a_b_c(comp_ctx,
  45852. DUK_OP_MPUTOBJ |
  45853. DUK__EMIT_FLAG_NO_SHUFFLE_C |
  45854. DUK__EMIT_FLAG_A_IS_SOURCE,
  45855. reg_obj,
  45856. temp_start,
  45857. num_pairs);
  45858. /* num_pairs and temp_start reset at top of outer loop */
  45859. }
  45860. }
  45861. DUK_ASSERT(comp_ctx->curr_token.t == DUK_TOK_RCURLY);
  45862. duk__advance(comp_ctx);
  45863. DUK__SETTEMP(comp_ctx, temp_start);
  45864. res->t = DUK_IVAL_PLAIN;
  45865. res->x1.t = DUK_ISPEC_REGCONST;
  45866. res->x1.regconst = (duk_regconst_t) reg_obj;
  45867. DUK_DDD(DUK_DDDPRINT("final tracking object: %!T",
  45868. (duk_tval *) duk_get_tval(ctx, -1)));
  45869. duk_pop(ctx);
  45870. return;
  45871. syntax_error:
  45872. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_OBJECT_LITERAL);
  45873. }
  45874. /* Parse argument list. Arguments are written to temps starting from
  45875. * "next temp". Returns number of arguments parsed. Expects left paren
  45876. * to be already eaten, and eats the right paren before returning.
  45877. */
  45878. DUK_LOCAL duk_int_t duk__parse_arguments(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  45879. duk_int_t nargs = 0;
  45880. duk_reg_t reg_temp;
  45881. /* Note: expect that caller has already eaten the left paren */
  45882. DUK_DDD(DUK_DDDPRINT("start parsing arguments, prev_token.t=%ld, curr_token.t=%ld",
  45883. (long) comp_ctx->prev_token.t, (long) comp_ctx->curr_token.t));
  45884. for (;;) {
  45885. if (comp_ctx->curr_token.t == DUK_TOK_RPAREN) {
  45886. break;
  45887. }
  45888. if (nargs > 0) {
  45889. duk__advance_expect(comp_ctx, DUK_TOK_COMMA);
  45890. }
  45891. /* We want the argument expression value to go to "next temp"
  45892. * without additional moves. That should almost always be the
  45893. * case, but we double check after expression parsing.
  45894. *
  45895. * This is not the cleanest possible approach.
  45896. */
  45897. reg_temp = DUK__ALLOCTEMP(comp_ctx); /* bump up "allocated" reg count, just in case */
  45898. DUK__SETTEMP(comp_ctx, reg_temp);
  45899. /* binding power must be high enough to NOT allow comma expressions directly */
  45900. duk__expr_toforcedreg(comp_ctx, res, DUK__BP_COMMA /*rbp_flags*/, reg_temp); /* always allow 'in', coerce to 'tr' just in case */
  45901. DUK__SETTEMP(comp_ctx, reg_temp + 1);
  45902. nargs++;
  45903. DUK_DDD(DUK_DDDPRINT("argument #%ld written into reg %ld", (long) nargs, (long) reg_temp));
  45904. }
  45905. /* eat the right paren */
  45906. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  45907. DUK_DDD(DUK_DDDPRINT("end parsing arguments"));
  45908. return nargs;
  45909. }
  45910. DUK_LOCAL duk_bool_t duk__expr_is_empty(duk_compiler_ctx *comp_ctx) {
  45911. /* empty expressions can be detected conveniently with nud/led counts */
  45912. return (comp_ctx->curr_func.nud_count == 0) &&
  45913. (comp_ctx->curr_func.led_count == 0);
  45914. }
  45915. DUK_LOCAL void duk__expr_nud(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  45916. duk_hthread *thr = comp_ctx->thr;
  45917. duk_context *ctx = (duk_context *) thr;
  45918. duk_token *tk;
  45919. duk_reg_t temp_at_entry;
  45920. duk_small_int_t tok;
  45921. duk_uint32_t args; /* temp variable to pass constants and flags to shared code */
  45922. /*
  45923. * ctx->prev_token token to process with duk__expr_nud()
  45924. * ctx->curr_token updated by caller
  45925. *
  45926. * Note: the token in the switch below has already been eaten.
  45927. */
  45928. temp_at_entry = DUK__GETTEMP(comp_ctx);
  45929. comp_ctx->curr_func.nud_count++;
  45930. tk = &comp_ctx->prev_token;
  45931. tok = tk->t;
  45932. res->t = DUK_IVAL_NONE;
  45933. DUK_DDD(DUK_DDDPRINT("duk__expr_nud(), prev_token.t=%ld, allow_in=%ld, paren_level=%ld",
  45934. (long) tk->t, (long) comp_ctx->curr_func.allow_in, (long) comp_ctx->curr_func.paren_level));
  45935. switch (tok) {
  45936. /* PRIMARY EXPRESSIONS */
  45937. case DUK_TOK_THIS: {
  45938. duk_reg_t reg_temp;
  45939. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  45940. duk__emit_extraop_bc(comp_ctx,
  45941. DUK_EXTRAOP_LDTHIS,
  45942. (duk_regconst_t) reg_temp);
  45943. res->t = DUK_IVAL_PLAIN;
  45944. res->x1.t = DUK_ISPEC_REGCONST;
  45945. res->x1.regconst = (duk_regconst_t) reg_temp;
  45946. return;
  45947. }
  45948. case DUK_TOK_IDENTIFIER: {
  45949. res->t = DUK_IVAL_VAR;
  45950. res->x1.t = DUK_ISPEC_VALUE;
  45951. duk_push_hstring(ctx, tk->str1);
  45952. duk_replace(ctx, res->x1.valstack_idx);
  45953. return;
  45954. }
  45955. case DUK_TOK_NULL: {
  45956. duk_push_null(ctx);
  45957. goto plain_value;
  45958. }
  45959. case DUK_TOK_TRUE: {
  45960. duk_push_true(ctx);
  45961. goto plain_value;
  45962. }
  45963. case DUK_TOK_FALSE: {
  45964. duk_push_false(ctx);
  45965. goto plain_value;
  45966. }
  45967. case DUK_TOK_NUMBER: {
  45968. duk_push_number(ctx, tk->num);
  45969. goto plain_value;
  45970. }
  45971. case DUK_TOK_STRING: {
  45972. DUK_ASSERT(tk->str1 != NULL);
  45973. duk_push_hstring(ctx, tk->str1);
  45974. goto plain_value;
  45975. }
  45976. case DUK_TOK_REGEXP: {
  45977. #ifdef DUK_USE_REGEXP_SUPPORT
  45978. duk_reg_t reg_temp;
  45979. duk_regconst_t rc_re_bytecode; /* const */
  45980. duk_regconst_t rc_re_source; /* const */
  45981. DUK_ASSERT(tk->str1 != NULL);
  45982. DUK_ASSERT(tk->str2 != NULL);
  45983. DUK_DDD(DUK_DDDPRINT("emitting regexp op, str1=%!O, str2=%!O",
  45984. (duk_heaphdr *) tk->str1,
  45985. (duk_heaphdr *) tk->str2));
  45986. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  45987. duk_push_hstring(ctx, tk->str1);
  45988. duk_push_hstring(ctx, tk->str2);
  45989. /* [ ... pattern flags ] */
  45990. duk_regexp_compile(thr);
  45991. /* [ ... escaped_source bytecode ] */
  45992. rc_re_bytecode = duk__getconst(comp_ctx);
  45993. rc_re_source = duk__getconst(comp_ctx);
  45994. duk__emit_a_b_c(comp_ctx,
  45995. DUK_OP_REGEXP,
  45996. (duk_regconst_t) reg_temp /*a*/,
  45997. rc_re_bytecode /*b*/,
  45998. rc_re_source /*c*/);
  45999. res->t = DUK_IVAL_PLAIN;
  46000. res->x1.t = DUK_ISPEC_REGCONST;
  46001. res->x1.regconst = (duk_regconst_t) reg_temp;
  46002. return;
  46003. #else /* DUK_USE_REGEXP_SUPPORT */
  46004. goto syntax_error;
  46005. #endif /* DUK_USE_REGEXP_SUPPORT */
  46006. }
  46007. case DUK_TOK_LBRACKET: {
  46008. DUK_DDD(DUK_DDDPRINT("parsing array literal"));
  46009. duk__nud_array_literal(comp_ctx, res);
  46010. return;
  46011. }
  46012. case DUK_TOK_LCURLY: {
  46013. DUK_DDD(DUK_DDDPRINT("parsing object literal"));
  46014. duk__nud_object_literal(comp_ctx, res);
  46015. return;
  46016. }
  46017. case DUK_TOK_LPAREN: {
  46018. duk_bool_t prev_allow_in;
  46019. comp_ctx->curr_func.paren_level++;
  46020. prev_allow_in = comp_ctx->curr_func.allow_in;
  46021. comp_ctx->curr_func.allow_in = 1; /* reset 'allow_in' for parenthesized expression */
  46022. duk__expr(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/); /* Expression, terminates at a ')' */
  46023. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  46024. comp_ctx->curr_func.allow_in = prev_allow_in;
  46025. comp_ctx->curr_func.paren_level--;
  46026. return;
  46027. }
  46028. /* MEMBER/NEW/CALL EXPRESSIONS */
  46029. case DUK_TOK_NEW: {
  46030. /*
  46031. * Parsing an expression starting with 'new' is tricky because
  46032. * there are multiple possible productions deriving from
  46033. * LeftHandSideExpression which begin with 'new'.
  46034. *
  46035. * We currently resort to one-token lookahead to distinguish the
  46036. * cases. Hopefully this is correct. The binding power must be
  46037. * such that parsing ends at an LPAREN (CallExpression) but not at
  46038. * a PERIOD or LBRACKET (MemberExpression).
  46039. *
  46040. * See doc/compiler.txt for discussion on the parsing approach,
  46041. * and testcases/test-dev-new.js for a bunch of documented tests.
  46042. */
  46043. duk_reg_t reg_target;
  46044. duk_int_t nargs;
  46045. DUK_DDD(DUK_DDDPRINT("begin parsing new expression"));
  46046. reg_target = DUK__ALLOCTEMP(comp_ctx);
  46047. duk__expr_toforcedreg(comp_ctx, res, DUK__BP_CALL /*rbp_flags*/, reg_target /*forced_reg*/);
  46048. DUK__SETTEMP(comp_ctx, reg_target + 1);
  46049. if (comp_ctx->curr_token.t == DUK_TOK_LPAREN) {
  46050. /* 'new' MemberExpression Arguments */
  46051. DUK_DDD(DUK_DDDPRINT("new expression has argument list"));
  46052. duk__advance(comp_ctx);
  46053. nargs = duk__parse_arguments(comp_ctx, res); /* parse args starting from "next temp", reg_target + 1 */
  46054. /* right paren eaten */
  46055. } else {
  46056. /* 'new' MemberExpression */
  46057. DUK_DDD(DUK_DDDPRINT("new expression has no argument list"));
  46058. nargs = 0;
  46059. }
  46060. /* Opcode slot C is used in a non-standard way, so shuffling
  46061. * is not allowed.
  46062. */
  46063. duk__emit_a_b_c(comp_ctx,
  46064. DUK_OP_NEW | DUK__EMIT_FLAG_NO_SHUFFLE_A | DUK__EMIT_FLAG_NO_SHUFFLE_C,
  46065. 0 /*unused*/,
  46066. reg_target /*target*/,
  46067. nargs /*num_args*/);
  46068. DUK_DDD(DUK_DDDPRINT("end parsing new expression"));
  46069. res->t = DUK_IVAL_PLAIN;
  46070. res->x1.t = DUK_ISPEC_REGCONST;
  46071. res->x1.regconst = (duk_regconst_t) reg_target;
  46072. return;
  46073. }
  46074. /* FUNCTION EXPRESSIONS */
  46075. case DUK_TOK_FUNCTION: {
  46076. /* Function expression. Note that any statement beginning with 'function'
  46077. * is handled by the statement parser as a function declaration, or a
  46078. * non-standard function expression/statement (or a SyntaxError). We only
  46079. * handle actual function expressions (occurring inside an expression) here.
  46080. *
  46081. * O(depth^2) parse count for inner functions is handled by recording a
  46082. * lexer offset on the first compilation pass, so that the function can
  46083. * be efficiently skipped on the second pass. This is encapsulated into
  46084. * duk__parse_func_like_fnum().
  46085. */
  46086. duk_reg_t reg_temp;
  46087. duk_int_t fnum;
  46088. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46089. /* curr_token follows 'function' */
  46090. fnum = duk__parse_func_like_fnum(comp_ctx, 0 /*is_decl*/, 0 /*is_setget*/);
  46091. DUK_DDD(DUK_DDDPRINT("parsed inner function -> fnum %ld", (long) fnum));
  46092. duk__emit_a_bc(comp_ctx,
  46093. DUK_OP_CLOSURE,
  46094. (duk_regconst_t) reg_temp /*a*/,
  46095. (duk_regconst_t) fnum /*bc*/);
  46096. res->t = DUK_IVAL_PLAIN;
  46097. res->x1.t = DUK_ISPEC_REGCONST;
  46098. res->x1.regconst = (duk_regconst_t) reg_temp;
  46099. return;
  46100. }
  46101. /* UNARY EXPRESSIONS */
  46102. case DUK_TOK_DELETE: {
  46103. /* Delete semantics are a bit tricky. The description in E5 specification
  46104. * is kind of confusing, because it distinguishes between resolvability of
  46105. * a reference (which is only known at runtime) seemingly at compile time
  46106. * (= SyntaxError throwing).
  46107. */
  46108. duk__expr(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46109. if (res->t == DUK_IVAL_VAR) {
  46110. /* not allowed in strict mode, regardless of whether resolves;
  46111. * in non-strict mode DELVAR handles both non-resolving and
  46112. * resolving cases (the specification description is a bit confusing).
  46113. */
  46114. duk_reg_t reg_temp;
  46115. duk_reg_t reg_varbind;
  46116. duk_regconst_t rc_varname;
  46117. if (comp_ctx->curr_func.is_strict) {
  46118. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_CANNOT_DELETE_IDENTIFIER);
  46119. }
  46120. DUK__SETTEMP(comp_ctx, temp_at_entry);
  46121. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46122. duk_dup(ctx, res->x1.valstack_idx);
  46123. if (duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname)) {
  46124. /* register bound variables are non-configurable -> always false */
  46125. duk__emit_extraop_bc(comp_ctx,
  46126. DUK_EXTRAOP_LDFALSE,
  46127. (duk_regconst_t) reg_temp);
  46128. } else {
  46129. duk_dup(ctx, res->x1.valstack_idx);
  46130. rc_varname = duk__getconst(comp_ctx);
  46131. duk__emit_a_b(comp_ctx,
  46132. DUK_OP_DELVAR,
  46133. (duk_regconst_t) reg_temp,
  46134. (duk_regconst_t) rc_varname);
  46135. }
  46136. res->t = DUK_IVAL_PLAIN;
  46137. res->x1.t = DUK_ISPEC_REGCONST;
  46138. res->x1.regconst = (duk_regconst_t) reg_temp;
  46139. } else if (res->t == DUK_IVAL_PROP) {
  46140. duk_reg_t reg_temp;
  46141. duk_reg_t reg_obj;
  46142. duk_regconst_t rc_key;
  46143. DUK__SETTEMP(comp_ctx, temp_at_entry);
  46144. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46145. reg_obj = duk__ispec_toregconst_raw(comp_ctx, &res->x1, -1 /*forced_reg*/, 0 /*flags*/); /* don't allow const */
  46146. rc_key = duk__ispec_toregconst_raw(comp_ctx, &res->x2, -1 /*forced_reg*/, DUK__IVAL_FLAG_ALLOW_CONST /*flags*/);
  46147. duk__emit_a_b_c(comp_ctx,
  46148. DUK_OP_DELPROP,
  46149. (duk_regconst_t) reg_temp,
  46150. (duk_regconst_t) reg_obj,
  46151. rc_key);
  46152. res->t = DUK_IVAL_PLAIN;
  46153. res->x1.t = DUK_ISPEC_REGCONST;
  46154. res->x1.regconst = (duk_regconst_t) reg_temp;
  46155. } else {
  46156. /* non-Reference deletion is always 'true', even in strict mode */
  46157. duk_push_true(ctx);
  46158. goto plain_value;
  46159. }
  46160. return;
  46161. }
  46162. case DUK_TOK_VOID: {
  46163. duk__expr_toplain_ignore(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46164. duk_push_undefined(ctx);
  46165. goto plain_value;
  46166. }
  46167. case DUK_TOK_TYPEOF: {
  46168. /* 'typeof' must handle unresolvable references without throwing
  46169. * a ReferenceError (E5 Section 11.4.3). Register mapped values
  46170. * will never be unresolvable so special handling is only required
  46171. * when an identifier is a "slow path" one.
  46172. */
  46173. duk__expr(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46174. if (res->t == DUK_IVAL_VAR) {
  46175. duk_reg_t reg_varbind;
  46176. duk_regconst_t rc_varname;
  46177. duk_reg_t reg_temp;
  46178. duk_dup(ctx, res->x1.valstack_idx);
  46179. if (!duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname)) {
  46180. DUK_DDD(DUK_DDDPRINT("typeof for an identifier name which could not be resolved "
  46181. "at compile time, need to use special run-time handling"));
  46182. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46183. duk__emit_extraop_b_c(comp_ctx,
  46184. DUK_EXTRAOP_TYPEOFID | DUK__EMIT_FLAG_B_IS_TARGET,
  46185. reg_temp,
  46186. rc_varname);
  46187. res->t = DUK_IVAL_PLAIN;
  46188. res->x1.t = DUK_ISPEC_REGCONST;
  46189. res->x1.regconst = (duk_regconst_t) reg_temp;
  46190. return;
  46191. }
  46192. }
  46193. args = (DUK_EXTRAOP_TYPEOF << 8) + 0;
  46194. goto unary_extraop;
  46195. }
  46196. case DUK_TOK_INCREMENT: {
  46197. args = (DUK_OP_PREINCR << 8) + 0;
  46198. goto preincdec;
  46199. }
  46200. case DUK_TOK_DECREMENT: {
  46201. args = (DUK_OP_PREDECR << 8) + 0;
  46202. goto preincdec;
  46203. }
  46204. case DUK_TOK_ADD: {
  46205. /* unary plus */
  46206. duk__expr(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46207. if (res->t == DUK_IVAL_PLAIN && res->x1.t == DUK_ISPEC_VALUE &&
  46208. duk_is_number(ctx, res->x1.valstack_idx)) {
  46209. /* unary plus of a number is identity */
  46210. ;
  46211. return;
  46212. }
  46213. args = (DUK_EXTRAOP_UNP << 8) + 0;
  46214. goto unary_extraop;
  46215. }
  46216. case DUK_TOK_SUB: {
  46217. /* unary minus */
  46218. duk__expr(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46219. if (res->t == DUK_IVAL_PLAIN && res->x1.t == DUK_ISPEC_VALUE &&
  46220. duk_is_number(ctx, res->x1.valstack_idx)) {
  46221. /* this optimization is important to handle negative literals (which are not directly
  46222. * provided by the lexical grammar
  46223. */
  46224. duk_tval *tv_num = duk_get_tval(ctx, res->x1.valstack_idx);
  46225. duk_double_union du;
  46226. DUK_ASSERT(tv_num != NULL);
  46227. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_num));
  46228. du.d = DUK_TVAL_GET_NUMBER(tv_num);
  46229. du.d = -du.d;
  46230. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&du);
  46231. DUK_TVAL_SET_NUMBER(tv_num, du.d);
  46232. return;
  46233. }
  46234. args = (DUK_EXTRAOP_UNM << 8) + 0;
  46235. goto unary_extraop;
  46236. }
  46237. case DUK_TOK_BNOT: {
  46238. duk__expr(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46239. args = (DUK_EXTRAOP_BNOT << 8) + 0;
  46240. goto unary_extraop;
  46241. }
  46242. case DUK_TOK_LNOT: {
  46243. duk__expr(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46244. if (res->t == DUK_IVAL_PLAIN && res->x1.t == DUK_ISPEC_VALUE) {
  46245. /* Very minimal inlining to handle common idioms '!0' and '!1',
  46246. * and also boolean arguments like '!false' and '!true'.
  46247. */
  46248. duk_tval *tv_val = duk_get_tval(ctx, res->x1.valstack_idx);
  46249. DUK_ASSERT(tv_val != NULL);
  46250. if (DUK_TVAL_IS_NUMBER(tv_val)) {
  46251. duk_double_t d;
  46252. d = DUK_TVAL_GET_NUMBER(tv_val);
  46253. if (d == 0.0) {
  46254. /* Matches both +0 and -0 on purpose. */
  46255. DUK_DDD(DUK_DDDPRINT("inlined lnot: !0 -> true"));
  46256. DUK_TVAL_SET_BOOLEAN_TRUE(tv_val);
  46257. return;
  46258. } else if (d == 1.0) {
  46259. DUK_DDD(DUK_DDDPRINT("inlined lnot: !1 -> false"));
  46260. DUK_TVAL_SET_BOOLEAN_FALSE(tv_val);
  46261. return;
  46262. }
  46263. } else if (DUK_TVAL_IS_BOOLEAN(tv_val)) {
  46264. duk_small_int_t v;
  46265. v = DUK_TVAL_GET_BOOLEAN(tv_val);
  46266. DUK_DDD(DUK_DDDPRINT("inlined lnot boolean: %ld", (long) v));
  46267. DUK_ASSERT(v == 0 || v == 1);
  46268. DUK_TVAL_SET_BOOLEAN(tv_val, v ^ 0x01);
  46269. return;
  46270. }
  46271. }
  46272. args = (DUK_EXTRAOP_LNOT << 8) + 0;
  46273. goto unary_extraop;
  46274. }
  46275. } /* end switch */
  46276. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_PARSE_ERROR);
  46277. return;
  46278. unary_extraop:
  46279. {
  46280. /* Note: must coerce to a (writable) temp register, so that e.g. "!x" where x
  46281. * is a reg-mapped variable works correctly (does not mutate the variable register).
  46282. */
  46283. duk_reg_t reg_temp;
  46284. reg_temp = duk__ivalue_toregconst_raw(comp_ctx, res, -1 /*forced_reg*/, DUK__IVAL_FLAG_REQUIRE_TEMP /*flags*/);
  46285. duk__emit_extraop_bc(comp_ctx,
  46286. (args >> 8),
  46287. (duk_regconst_t) reg_temp);
  46288. res->t = DUK_IVAL_PLAIN;
  46289. res->x1.t = DUK_ISPEC_REGCONST;
  46290. res->x1.regconst = (duk_regconst_t) reg_temp;
  46291. return;
  46292. }
  46293. preincdec:
  46294. {
  46295. /* preincrement and predecrement */
  46296. duk_reg_t reg_res;
  46297. duk_small_uint_t args_op = args >> 8;
  46298. /* Specific assumptions for opcode numbering. */
  46299. DUK_ASSERT(DUK_OP_PREINCR + 4 == DUK_OP_PREINCV);
  46300. DUK_ASSERT(DUK_OP_PREDECR + 4 == DUK_OP_PREDECV);
  46301. DUK_ASSERT(DUK_OP_PREINCR + 8 == DUK_OP_PREINCP);
  46302. DUK_ASSERT(DUK_OP_PREDECR + 8 == DUK_OP_PREDECP);
  46303. reg_res = DUK__ALLOCTEMP(comp_ctx);
  46304. duk__expr(comp_ctx, res, DUK__BP_MULTIPLICATIVE /*rbp_flags*/); /* UnaryExpression */
  46305. if (res->t == DUK_IVAL_VAR) {
  46306. duk_hstring *h_varname;
  46307. duk_reg_t reg_varbind;
  46308. duk_regconst_t rc_varname;
  46309. h_varname = duk_get_hstring(ctx, res->x1.valstack_idx);
  46310. DUK_ASSERT(h_varname != NULL);
  46311. if (duk__hstring_is_eval_or_arguments_in_strict_mode(comp_ctx, h_varname)) {
  46312. goto syntax_error;
  46313. }
  46314. duk_dup(ctx, res->x1.valstack_idx);
  46315. if (duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname)) {
  46316. duk__emit_a_bc(comp_ctx,
  46317. args_op, /* e.g. DUK_OP_PREINCR */
  46318. (duk_regconst_t) reg_res,
  46319. (duk_regconst_t) reg_varbind);
  46320. } else {
  46321. duk__emit_a_bc(comp_ctx,
  46322. args_op + 4, /* e.g. DUK_OP_PREINCV */
  46323. (duk_regconst_t) reg_res,
  46324. rc_varname);
  46325. }
  46326. DUK_DDD(DUK_DDDPRINT("preincdec to '%!O' -> reg_varbind=%ld, rc_varname=%ld",
  46327. (duk_heaphdr *) h_varname, (long) reg_varbind, (long) rc_varname));
  46328. } else if (res->t == DUK_IVAL_PROP) {
  46329. duk_reg_t reg_obj; /* allocate to reg only (not const) */
  46330. duk_regconst_t rc_key;
  46331. reg_obj = duk__ispec_toregconst_raw(comp_ctx, &res->x1, -1 /*forced_reg*/, 0 /*flags*/); /* don't allow const */
  46332. rc_key = duk__ispec_toregconst_raw(comp_ctx, &res->x2, -1 /*forced_reg*/, DUK__IVAL_FLAG_ALLOW_CONST /*flags*/);
  46333. duk__emit_a_b_c(comp_ctx,
  46334. args_op + 8, /* e.g. DUK_OP_PREINCP */
  46335. (duk_regconst_t) reg_res,
  46336. (duk_regconst_t) reg_obj,
  46337. rc_key);
  46338. } else {
  46339. /* Technically return value is not needed because INVLHS will
  46340. * unconditially throw a ReferenceError. Coercion is necessary
  46341. * for proper semantics (consider ToNumber() called for an object).
  46342. * Use DUK_EXTRAOP_UNP with a dummy register to get ToNumber().
  46343. */
  46344. duk__ivalue_toforcedreg(comp_ctx, res, reg_res);
  46345. duk__emit_extraop_bc(comp_ctx,
  46346. DUK_EXTRAOP_UNP,
  46347. reg_res); /* for side effects, result ignored */
  46348. duk__emit_extraop_only(comp_ctx,
  46349. DUK_EXTRAOP_INVLHS);
  46350. }
  46351. res->t = DUK_IVAL_PLAIN;
  46352. res->x1.t = DUK_ISPEC_REGCONST;
  46353. res->x1.regconst = (duk_regconst_t) reg_res;
  46354. DUK__SETTEMP(comp_ctx, reg_res + 1);
  46355. return;
  46356. }
  46357. plain_value:
  46358. {
  46359. /* Stack top contains plain value */
  46360. res->t = DUK_IVAL_PLAIN;
  46361. res->x1.t = DUK_ISPEC_VALUE;
  46362. duk_replace(ctx, res->x1.valstack_idx);
  46363. return;
  46364. }
  46365. syntax_error:
  46366. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_EXPRESSION);
  46367. }
  46368. /* XXX: add flag to indicate whether caller cares about return value; this
  46369. * affects e.g. handling of assignment expressions. This change needs API
  46370. * changes elsewhere too.
  46371. */
  46372. DUK_LOCAL void duk__expr_led(duk_compiler_ctx *comp_ctx, duk_ivalue *left, duk_ivalue *res) {
  46373. duk_hthread *thr = comp_ctx->thr;
  46374. duk_context *ctx = (duk_context *) thr;
  46375. duk_token *tk;
  46376. duk_small_int_t tok;
  46377. duk_uint32_t args; /* temp variable to pass constants and flags to shared code */
  46378. /*
  46379. * ctx->prev_token token to process with duk__expr_led()
  46380. * ctx->curr_token updated by caller
  46381. */
  46382. comp_ctx->curr_func.led_count++;
  46383. /* The token in the switch has already been eaten here */
  46384. tk = &comp_ctx->prev_token;
  46385. tok = tk->t;
  46386. DUK_DDD(DUK_DDDPRINT("duk__expr_led(), prev_token.t=%ld, allow_in=%ld, paren_level=%ld",
  46387. (long) tk->t, (long) comp_ctx->curr_func.allow_in, (long) comp_ctx->curr_func.paren_level));
  46388. /* XXX: default priority for infix operators is duk__expr_lbp(tok) -> get it here? */
  46389. switch (tok) {
  46390. /* PRIMARY EXPRESSIONS */
  46391. case DUK_TOK_PERIOD: {
  46392. /* Property access expressions are critical for correct LHS ordering,
  46393. * see comments in duk__expr()!
  46394. */
  46395. /* XXX: this now coerces an identifier into a GETVAR to a temp, which
  46396. * causes an extra LDREG in call setup. It's sufficient to coerce to a
  46397. * unary ivalue?
  46398. */
  46399. duk__ivalue_toplain(comp_ctx, left);
  46400. /* NB: must accept reserved words as property name */
  46401. if (comp_ctx->curr_token.t_nores != DUK_TOK_IDENTIFIER) {
  46402. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_EXPECTED_IDENTIFIER);
  46403. }
  46404. res->t = DUK_IVAL_PROP;
  46405. duk__copy_ispec(comp_ctx, &left->x1, &res->x1); /* left.x1 -> res.x1 */
  46406. DUK_ASSERT(comp_ctx->curr_token.str1 != NULL);
  46407. duk_push_hstring(ctx, comp_ctx->curr_token.str1);
  46408. duk_replace(ctx, res->x2.valstack_idx);
  46409. res->x2.t = DUK_ISPEC_VALUE;
  46410. /* special RegExp literal handling after IdentifierName */
  46411. comp_ctx->curr_func.reject_regexp_in_adv = 1;
  46412. duk__advance(comp_ctx);
  46413. return;
  46414. }
  46415. case DUK_TOK_LBRACKET: {
  46416. /* Property access expressions are critical for correct LHS ordering,
  46417. * see comments in duk__expr()!
  46418. */
  46419. /* XXX: optimize temp reg use */
  46420. /* XXX: similar coercion issue as in DUK_TOK_PERIOD */
  46421. /* XXX: coerce to regs? it might be better for enumeration use, where the
  46422. * same PROP ivalue is used multiple times. Or perhaps coerce PROP further
  46423. * there?
  46424. */
  46425. duk__ivalue_toplain(comp_ctx, left);
  46426. duk__expr_toplain(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/); /* Expression, ']' terminates */
  46427. duk__advance_expect(comp_ctx, DUK_TOK_RBRACKET);
  46428. res->t = DUK_IVAL_PROP;
  46429. duk__copy_ispec(comp_ctx, &res->x1, &res->x2); /* res.x1 -> res.x2 */
  46430. duk__copy_ispec(comp_ctx, &left->x1, &res->x1); /* left.x1 -> res.x1 */
  46431. return;
  46432. }
  46433. case DUK_TOK_LPAREN: {
  46434. /* function call */
  46435. duk_reg_t reg_cs = DUK__ALLOCTEMPS(comp_ctx, 2);
  46436. duk_int_t nargs;
  46437. duk_small_uint_t call_flags = 0;
  46438. /*
  46439. * XXX: attempt to get the call result to "next temp" whenever
  46440. * possible to avoid unnecessary register shuffles.
  46441. *
  46442. * XXX: CSPROP (and CSREG) can overwrite the call target register, and save one temp,
  46443. * if the call target is a temporary register and at the top of the temp reg "stack".
  46444. */
  46445. /*
  46446. * Setup call: target and 'this' binding. Three cases:
  46447. *
  46448. * 1. Identifier base (e.g. "foo()")
  46449. * 2. Property base (e.g. "foo.bar()")
  46450. * 3. Register base (e.g. "foo()()"; i.e. when a return value is a function)
  46451. */
  46452. if (left->t == DUK_IVAL_VAR) {
  46453. duk_hstring *h_varname;
  46454. duk_reg_t reg_varbind;
  46455. duk_regconst_t rc_varname;
  46456. DUK_DDD(DUK_DDDPRINT("function call with identifier base"));
  46457. h_varname = duk_get_hstring(ctx, left->x1.valstack_idx);
  46458. DUK_ASSERT(h_varname != NULL);
  46459. if (h_varname == DUK_HTHREAD_STRING_EVAL(thr)) {
  46460. /* Potential direct eval call detected, flag the CALL
  46461. * so that a run-time "direct eval" check is made and
  46462. * special behavior may be triggered. Note that this
  46463. * does not prevent 'eval' from being register bound.
  46464. */
  46465. DUK_DDD(DUK_DDDPRINT("function call with identifier 'eval' "
  46466. "-> enabling EVALCALL flag, marking function "
  46467. "as may_direct_eval"));
  46468. call_flags |= DUK_BC_CALL_FLAG_EVALCALL;
  46469. comp_ctx->curr_func.may_direct_eval = 1;
  46470. }
  46471. duk_dup(ctx, left->x1.valstack_idx);
  46472. if (duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname)) {
  46473. duk__emit_a_b(comp_ctx,
  46474. DUK_OP_CSREG,
  46475. (duk_regconst_t) (reg_cs + 0),
  46476. (duk_regconst_t) reg_varbind);
  46477. } else {
  46478. duk__emit_a_b(comp_ctx,
  46479. DUK_OP_CSVAR,
  46480. (duk_regconst_t) (reg_cs + 0),
  46481. rc_varname);
  46482. }
  46483. } else if (left->t == DUK_IVAL_PROP) {
  46484. DUK_DDD(DUK_DDDPRINT("function call with property base"));
  46485. duk__ispec_toforcedreg(comp_ctx, &left->x1, reg_cs + 0); /* base */
  46486. duk__ispec_toforcedreg(comp_ctx, &left->x2, reg_cs + 1); /* key */
  46487. duk__emit_a_b_c(comp_ctx,
  46488. DUK_OP_CSPROP,
  46489. (duk_regconst_t) (reg_cs + 0),
  46490. (duk_regconst_t) (reg_cs + 0),
  46491. (duk_regconst_t) (reg_cs + 1)); /* in-place setup */
  46492. } else {
  46493. DUK_DDD(DUK_DDDPRINT("function call with register base"));
  46494. duk__ivalue_toforcedreg(comp_ctx, left, reg_cs + 0);
  46495. duk__emit_a_b(comp_ctx,
  46496. DUK_OP_CSREG,
  46497. (duk_regconst_t) (reg_cs + 0),
  46498. (duk_regconst_t) (reg_cs + 0)); /* in-place setup */
  46499. }
  46500. DUK__SETTEMP(comp_ctx, reg_cs + 2);
  46501. nargs = duk__parse_arguments(comp_ctx, res); /* parse args starting from "next temp" */
  46502. /* Tailcalls are handled by back-patching the TAILCALL flag to the
  46503. * already emitted instruction later (in return statement parser).
  46504. * Since A and C have a special meaning here, they cannot be "shuffled".
  46505. */
  46506. duk__emit_a_b_c(comp_ctx,
  46507. DUK_OP_CALL | DUK__EMIT_FLAG_NO_SHUFFLE_A | DUK__EMIT_FLAG_NO_SHUFFLE_C,
  46508. (duk_regconst_t) call_flags /*flags*/,
  46509. (duk_regconst_t) reg_cs /*basereg*/,
  46510. (duk_regconst_t) nargs /*numargs*/);
  46511. DUK__SETTEMP(comp_ctx, reg_cs + 1); /* result in csreg */
  46512. res->t = DUK_IVAL_PLAIN;
  46513. res->x1.t = DUK_ISPEC_REGCONST;
  46514. res->x1.regconst = (duk_regconst_t) reg_cs;
  46515. return;
  46516. }
  46517. /* POSTFIX EXPRESSION */
  46518. case DUK_TOK_INCREMENT: {
  46519. args = (DUK_OP_POSTINCR << 8) + 0;
  46520. goto postincdec;
  46521. }
  46522. case DUK_TOK_DECREMENT: {
  46523. args = (DUK_OP_POSTDECR << 8) + 0;
  46524. goto postincdec;
  46525. }
  46526. /* MULTIPLICATIVE EXPRESSION */
  46527. case DUK_TOK_MUL: {
  46528. args = (DUK_OP_MUL << 8) + DUK__BP_MULTIPLICATIVE; /* UnaryExpression */
  46529. goto binary;
  46530. }
  46531. case DUK_TOK_DIV: {
  46532. args = (DUK_OP_DIV << 8) + DUK__BP_MULTIPLICATIVE; /* UnaryExpression */
  46533. goto binary;
  46534. }
  46535. case DUK_TOK_MOD: {
  46536. args = (DUK_OP_MOD << 8) + DUK__BP_MULTIPLICATIVE; /* UnaryExpression */
  46537. goto binary;
  46538. }
  46539. /* ADDITIVE EXPRESSION */
  46540. case DUK_TOK_ADD: {
  46541. args = (DUK_OP_ADD << 8) + DUK__BP_ADDITIVE; /* MultiplicativeExpression */
  46542. goto binary;
  46543. }
  46544. case DUK_TOK_SUB: {
  46545. args = (DUK_OP_SUB << 8) + DUK__BP_ADDITIVE; /* MultiplicativeExpression */
  46546. goto binary;
  46547. }
  46548. /* SHIFT EXPRESSION */
  46549. case DUK_TOK_ALSHIFT: {
  46550. /* << */
  46551. args = (DUK_OP_BASL << 8) + DUK__BP_SHIFT;
  46552. goto binary;
  46553. }
  46554. case DUK_TOK_ARSHIFT: {
  46555. /* >> */
  46556. args = (DUK_OP_BASR << 8) + DUK__BP_SHIFT;
  46557. goto binary;
  46558. }
  46559. case DUK_TOK_RSHIFT: {
  46560. /* >>> */
  46561. args = (DUK_OP_BLSR << 8) + DUK__BP_SHIFT;
  46562. goto binary;
  46563. }
  46564. /* RELATIONAL EXPRESSION */
  46565. case DUK_TOK_LT: {
  46566. /* < */
  46567. args = (DUK_OP_LT << 8) + DUK__BP_RELATIONAL;
  46568. goto binary;
  46569. }
  46570. case DUK_TOK_GT: {
  46571. args = (DUK_OP_GT << 8) + DUK__BP_RELATIONAL;
  46572. goto binary;
  46573. }
  46574. case DUK_TOK_LE: {
  46575. args = (DUK_OP_LE << 8) + DUK__BP_RELATIONAL;
  46576. goto binary;
  46577. }
  46578. case DUK_TOK_GE: {
  46579. args = (DUK_OP_GE << 8) + DUK__BP_RELATIONAL;
  46580. goto binary;
  46581. }
  46582. case DUK_TOK_INSTANCEOF: {
  46583. args = (1 << 16 /*is_extra*/) + (DUK_EXTRAOP_INSTOF << 8) + DUK__BP_RELATIONAL;
  46584. goto binary;
  46585. }
  46586. case DUK_TOK_IN: {
  46587. args = (1 << 16 /*is_extra*/) + (DUK_EXTRAOP_IN << 8) + DUK__BP_RELATIONAL;
  46588. goto binary;
  46589. }
  46590. /* EQUALITY EXPRESSION */
  46591. case DUK_TOK_EQ: {
  46592. args = (DUK_OP_EQ << 8) + DUK__BP_EQUALITY;
  46593. goto binary;
  46594. }
  46595. case DUK_TOK_NEQ: {
  46596. args = (DUK_OP_NEQ << 8) + DUK__BP_EQUALITY;
  46597. goto binary;
  46598. }
  46599. case DUK_TOK_SEQ: {
  46600. args = (DUK_OP_SEQ << 8) + DUK__BP_EQUALITY;
  46601. goto binary;
  46602. }
  46603. case DUK_TOK_SNEQ: {
  46604. args = (DUK_OP_SNEQ << 8) + DUK__BP_EQUALITY;
  46605. goto binary;
  46606. }
  46607. /* BITWISE EXPRESSIONS */
  46608. case DUK_TOK_BAND: {
  46609. args = (DUK_OP_BAND << 8) + DUK__BP_BAND;
  46610. goto binary;
  46611. }
  46612. case DUK_TOK_BXOR: {
  46613. args = (DUK_OP_BXOR << 8) + DUK__BP_BXOR;
  46614. goto binary;
  46615. }
  46616. case DUK_TOK_BOR: {
  46617. args = (DUK_OP_BOR << 8) + DUK__BP_BOR;
  46618. goto binary;
  46619. }
  46620. /* LOGICAL EXPRESSIONS */
  46621. case DUK_TOK_LAND: {
  46622. /* syntactically left-associative but parsed as right-associative */
  46623. args = (1 << 8) + DUK__BP_LAND - 1;
  46624. goto binary_logical;
  46625. }
  46626. case DUK_TOK_LOR: {
  46627. /* syntactically left-associative but parsed as right-associative */
  46628. args = (0 << 8) + DUK__BP_LOR - 1;
  46629. goto binary_logical;
  46630. }
  46631. /* CONDITIONAL EXPRESSION */
  46632. case DUK_TOK_QUESTION: {
  46633. /* XXX: common reg allocation need is to reuse a sub-expression's temp reg,
  46634. * but only if it really is a temp. Nothing fancy here now.
  46635. */
  46636. duk_reg_t reg_temp;
  46637. duk_int_t pc_jump1;
  46638. duk_int_t pc_jump2;
  46639. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46640. duk__ivalue_toforcedreg(comp_ctx, left, reg_temp);
  46641. duk__emit_if_true_skip(comp_ctx, reg_temp);
  46642. pc_jump1 = duk__emit_jump_empty(comp_ctx); /* jump to false */
  46643. duk__expr_toforcedreg(comp_ctx, res, DUK__BP_COMMA /*rbp_flags*/, reg_temp /*forced_reg*/); /* AssignmentExpression */
  46644. duk__advance_expect(comp_ctx, DUK_TOK_COLON);
  46645. pc_jump2 = duk__emit_jump_empty(comp_ctx); /* jump to end */
  46646. duk__patch_jump_here(comp_ctx, pc_jump1);
  46647. duk__expr_toforcedreg(comp_ctx, res, DUK__BP_COMMA /*rbp_flags*/, reg_temp /*forced_reg*/); /* AssignmentExpression */
  46648. duk__patch_jump_here(comp_ctx, pc_jump2);
  46649. DUK__SETTEMP(comp_ctx, reg_temp + 1);
  46650. res->t = DUK_IVAL_PLAIN;
  46651. res->x1.t = DUK_ISPEC_REGCONST;
  46652. res->x1.regconst = (duk_regconst_t) reg_temp;
  46653. return;
  46654. }
  46655. /* ASSIGNMENT EXPRESSION */
  46656. case DUK_TOK_EQUALSIGN: {
  46657. /*
  46658. * Assignments are right associative, allows e.g.
  46659. * a = 5;
  46660. * a += b = 9; // same as a += (b = 9)
  46661. * -> expression value 14, a = 14, b = 9
  46662. *
  46663. * Right associativiness is reflected in the BP for recursion,
  46664. * "-1" ensures assignment operations are allowed.
  46665. *
  46666. * XXX: just use DUK__BP_COMMA (i.e. no need for 2-step bp levels)?
  46667. */
  46668. args = (DUK_OP_NONE << 8) + DUK__BP_ASSIGNMENT - 1; /* DUK_OP_NONE marks a 'plain' assignment */
  46669. goto assign;
  46670. }
  46671. case DUK_TOK_ADD_EQ: {
  46672. /* right associative */
  46673. args = (DUK_OP_ADD << 8) + DUK__BP_ASSIGNMENT - 1;
  46674. goto assign;
  46675. }
  46676. case DUK_TOK_SUB_EQ: {
  46677. /* right associative */
  46678. args = (DUK_OP_SUB << 8) + DUK__BP_ASSIGNMENT - 1;
  46679. goto assign;
  46680. }
  46681. case DUK_TOK_MUL_EQ: {
  46682. /* right associative */
  46683. args = (DUK_OP_MUL << 8) + DUK__BP_ASSIGNMENT - 1;
  46684. goto assign;
  46685. }
  46686. case DUK_TOK_DIV_EQ: {
  46687. /* right associative */
  46688. args = (DUK_OP_DIV << 8) + DUK__BP_ASSIGNMENT - 1;
  46689. goto assign;
  46690. }
  46691. case DUK_TOK_MOD_EQ: {
  46692. /* right associative */
  46693. args = (DUK_OP_MOD << 8) + DUK__BP_ASSIGNMENT - 1;
  46694. goto assign;
  46695. }
  46696. case DUK_TOK_ALSHIFT_EQ: {
  46697. /* right associative */
  46698. args = (DUK_OP_BASL << 8) + DUK__BP_ASSIGNMENT - 1;
  46699. goto assign;
  46700. }
  46701. case DUK_TOK_ARSHIFT_EQ: {
  46702. /* right associative */
  46703. args = (DUK_OP_BASR << 8) + DUK__BP_ASSIGNMENT - 1;
  46704. goto assign;
  46705. }
  46706. case DUK_TOK_RSHIFT_EQ: {
  46707. /* right associative */
  46708. args = (DUK_OP_BLSR << 8) + DUK__BP_ASSIGNMENT - 1;
  46709. goto assign;
  46710. }
  46711. case DUK_TOK_BAND_EQ: {
  46712. /* right associative */
  46713. args = (DUK_OP_BAND << 8) + DUK__BP_ASSIGNMENT - 1;
  46714. goto assign;
  46715. }
  46716. case DUK_TOK_BOR_EQ: {
  46717. /* right associative */
  46718. args = (DUK_OP_BOR << 8) + DUK__BP_ASSIGNMENT - 1;
  46719. goto assign;
  46720. }
  46721. case DUK_TOK_BXOR_EQ: {
  46722. /* right associative */
  46723. args = (DUK_OP_BXOR << 8) + DUK__BP_ASSIGNMENT - 1;
  46724. goto assign;
  46725. }
  46726. /* COMMA */
  46727. case DUK_TOK_COMMA: {
  46728. /* right associative */
  46729. duk__ivalue_toplain_ignore(comp_ctx, left); /* need side effects, not value */
  46730. duk__expr_toplain(comp_ctx, res, DUK__BP_COMMA - 1 /*rbp_flags*/);
  46731. /* return 'res' (of right part) as our result */
  46732. return;
  46733. }
  46734. default: {
  46735. break;
  46736. }
  46737. }
  46738. DUK_D(DUK_DPRINT("parse error: unexpected token: %ld", (long) tok));
  46739. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_PARSE_ERROR);
  46740. return;
  46741. #if 0
  46742. /* XXX: shared handling for 'duk__expr_lhs'? */
  46743. if (comp_ctx->curr_func.paren_level == 0 && XXX) {
  46744. comp_ctx->curr_func.duk__expr_lhs = 0;
  46745. }
  46746. #endif
  46747. binary:
  46748. /*
  46749. * Shared handling of binary operations
  46750. *
  46751. * args = (is_extraop << 16) + (opcode << 8) + rbp
  46752. */
  46753. {
  46754. duk__ivalue_toplain(comp_ctx, left);
  46755. duk__expr_toplain(comp_ctx, res, args & 0xff /*rbp_flags*/);
  46756. /* combine left->x1 and res->x1 (right->x1, really) -> (left->x1 OP res->x1) */
  46757. DUK_ASSERT(left->t == DUK_IVAL_PLAIN);
  46758. DUK_ASSERT(res->t == DUK_IVAL_PLAIN);
  46759. res->t = (args >> 16) ? DUK_IVAL_ARITH_EXTRAOP : DUK_IVAL_ARITH;
  46760. res->op = (args >> 8) & 0xff;
  46761. res->x2.t = res->x1.t;
  46762. res->x2.regconst = res->x1.regconst;
  46763. duk_copy(ctx, res->x1.valstack_idx, res->x2.valstack_idx);
  46764. res->x1.t = left->x1.t;
  46765. res->x1.regconst = left->x1.regconst;
  46766. duk_copy(ctx, left->x1.valstack_idx, res->x1.valstack_idx);
  46767. DUK_DDD(DUK_DDDPRINT("binary op, res: t=%ld, x1.t=%ld, x1.regconst=0x%08lx, x2.t=%ld, x2.regconst=0x%08lx",
  46768. (long) res->t, (long) res->x1.t, (unsigned long) res->x1.regconst, (long) res->x2.t, (unsigned long) res->x2.regconst));
  46769. return;
  46770. }
  46771. binary_logical:
  46772. /*
  46773. * Shared handling for logical AND and logical OR.
  46774. *
  46775. * args = (truthval << 8) + rbp
  46776. *
  46777. * Truthval determines when to skip right-hand-side.
  46778. * For logical AND truthval=1, for logical OR truthval=0.
  46779. *
  46780. * See doc/compiler.txt for discussion on compiling logical
  46781. * AND and OR expressions. The approach here is very simplistic,
  46782. * generating extra jumps and multiple evaluations of truth values,
  46783. * but generates code on-the-fly with only local back-patching.
  46784. *
  46785. * Both logical AND and OR are syntactically left-associated.
  46786. * However, logical ANDs are compiled as right associative
  46787. * expressions, i.e. "A && B && C" as "A && (B && C)", to allow
  46788. * skip jumps to skip over the entire tail. Similarly for logical OR.
  46789. */
  46790. {
  46791. duk_reg_t reg_temp;
  46792. duk_int_t pc_jump;
  46793. duk_small_uint_t args_truthval = args >> 8;
  46794. duk_small_uint_t args_rbp = args & 0xff;
  46795. /* XXX: unoptimal use of temps, resetting */
  46796. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46797. duk__ivalue_toforcedreg(comp_ctx, left, reg_temp);
  46798. duk__emit_a_b(comp_ctx,
  46799. DUK_OP_IF | DUK__EMIT_FLAG_NO_SHUFFLE_A,
  46800. (duk_regconst_t) args_truthval,
  46801. (duk_regconst_t) reg_temp); /* skip jump conditionally */
  46802. pc_jump = duk__emit_jump_empty(comp_ctx);
  46803. duk__expr_toforcedreg(comp_ctx, res, args_rbp /*rbp_flags*/, reg_temp /*forced_reg*/);
  46804. duk__patch_jump_here(comp_ctx, pc_jump);
  46805. res->t = DUK_IVAL_PLAIN;
  46806. res->x1.t = DUK_ISPEC_REGCONST;
  46807. res->x1.regconst = (duk_regconst_t) reg_temp;
  46808. return;
  46809. }
  46810. assign:
  46811. /*
  46812. * Shared assignment expression handling
  46813. *
  46814. * args = (opcode << 8) + rbp
  46815. *
  46816. * If 'opcode' is DUK_OP_NONE, plain assignment without arithmetic.
  46817. * Syntactically valid left-hand-side forms which are not accepted as
  46818. * left-hand-side values (e.g. as in "f() = 1") must NOT cause a
  46819. * SyntaxError, but rather a run-time ReferenceError.
  46820. */
  46821. {
  46822. duk_small_uint_t args_op = args >> 8;
  46823. duk_small_uint_t args_rbp = args & 0xff;
  46824. /* XXX: here we need to know if 'left' is left-hand-side compatible.
  46825. * That information is no longer available from current expr parsing
  46826. * state; it would need to be carried into the 'left' ivalue or by
  46827. * some other means.
  46828. */
  46829. if (left->t == DUK_IVAL_VAR) {
  46830. duk_hstring *h_varname;
  46831. duk_reg_t reg_varbind;
  46832. duk_regconst_t rc_varname;
  46833. duk_regconst_t rc_res;
  46834. duk_reg_t reg_temp;
  46835. /* already in fluly evaluated form */
  46836. DUK_ASSERT(left->x1.t == DUK_ISPEC_VALUE);
  46837. duk__expr_toreg(comp_ctx, res, args_rbp /*rbp_flags*/);
  46838. DUK_ASSERT(res->t == DUK_IVAL_PLAIN && res->x1.t == DUK_ISPEC_REGCONST);
  46839. h_varname = duk_get_hstring(ctx, left->x1.valstack_idx);
  46840. DUK_ASSERT(h_varname != NULL);
  46841. /* E5 Section 11.13.1 (and others for other assignments), step 4 */
  46842. if (duk__hstring_is_eval_or_arguments_in_strict_mode(comp_ctx, h_varname)) {
  46843. goto syntax_error_lvalue;
  46844. }
  46845. duk_dup(ctx, left->x1.valstack_idx);
  46846. (void) duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname);
  46847. DUK_DDD(DUK_DDDPRINT("assign to '%!O' -> reg_varbind=%ld, rc_varname=%ld",
  46848. (duk_heaphdr *) h_varname, (long) reg_varbind, (long) rc_varname));
  46849. if (args_op == DUK_OP_NONE) {
  46850. rc_res = res->x1.regconst;
  46851. } else {
  46852. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46853. if (reg_varbind >= 0) {
  46854. duk__emit_a_b_c(comp_ctx,
  46855. args_op,
  46856. (duk_regconst_t) reg_temp,
  46857. (duk_regconst_t) reg_varbind,
  46858. res->x1.regconst);
  46859. } else {
  46860. duk__emit_a_bc(comp_ctx,
  46861. DUK_OP_GETVAR,
  46862. (duk_regconst_t) reg_temp,
  46863. rc_varname);
  46864. duk__emit_a_b_c(comp_ctx,
  46865. args_op,
  46866. (duk_regconst_t) reg_temp,
  46867. (duk_regconst_t) reg_temp,
  46868. res->x1.regconst);
  46869. }
  46870. rc_res = (duk_regconst_t) reg_temp;
  46871. }
  46872. if (reg_varbind >= 0) {
  46873. duk__emit_a_bc(comp_ctx,
  46874. DUK_OP_LDREG,
  46875. (duk_regconst_t) reg_varbind,
  46876. rc_res);
  46877. } else {
  46878. /* Only a reg fits into 'A' and reg_res may be a const in
  46879. * straight assignment.
  46880. *
  46881. * XXX: here the current A/B/C split is suboptimal: we could
  46882. * just use 9 bits for reg_res (and support constants) and 17
  46883. * instead of 18 bits for the varname const index.
  46884. */
  46885. if (DUK__ISCONST(comp_ctx, rc_res)) {
  46886. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46887. duk__emit_a_bc(comp_ctx,
  46888. DUK_OP_LDCONST,
  46889. (duk_regconst_t) reg_temp,
  46890. rc_res);
  46891. rc_res = (duk_regconst_t) reg_temp;
  46892. }
  46893. duk__emit_a_bc(comp_ctx,
  46894. DUK_OP_PUTVAR | DUK__EMIT_FLAG_A_IS_SOURCE,
  46895. rc_res,
  46896. rc_varname);
  46897. }
  46898. res->t = DUK_IVAL_PLAIN;
  46899. res->x1.t = DUK_ISPEC_REGCONST;
  46900. res->x1.regconst = rc_res;
  46901. } else if (left->t == DUK_IVAL_PROP) {
  46902. /* E5 Section 11.13.1 (and others) step 4 never matches for prop writes -> no check */
  46903. duk_reg_t reg_obj;
  46904. duk_regconst_t rc_key;
  46905. duk_regconst_t rc_res;
  46906. duk_reg_t reg_temp;
  46907. /* Property access expressions ('a[b]') are critical to correct
  46908. * LHS evaluation ordering, see test-dev-assign-eval-order*.js.
  46909. * We must make sure that the LHS target slot (base object and
  46910. * key) don't change during RHS evaluation. The only concrete
  46911. * problem is a register reference to a variable-bound register
  46912. * (i.e., non-temp). Require temp regs for both key and base.
  46913. *
  46914. * Don't allow a constant for the object (even for a number
  46915. * etc), as it goes into the 'A' field of the opcode.
  46916. */
  46917. reg_obj = duk__ispec_toregconst_raw(comp_ctx,
  46918. &left->x1,
  46919. -1 /*forced_reg*/,
  46920. DUK__IVAL_FLAG_REQUIRE_TEMP /*flags*/);
  46921. rc_key = duk__ispec_toregconst_raw(comp_ctx,
  46922. &left->x2,
  46923. -1 /*forced_reg*/,
  46924. DUK__IVAL_FLAG_REQUIRE_TEMP | DUK__IVAL_FLAG_ALLOW_CONST /*flags*/);
  46925. /* Evaluate RHS only when LHS is safe. */
  46926. duk__expr_toregconst(comp_ctx, res, args_rbp /*rbp_flags*/);
  46927. DUK_ASSERT(res->t == DUK_IVAL_PLAIN && res->x1.t == DUK_ISPEC_REGCONST);
  46928. if (args_op == DUK_OP_NONE) {
  46929. rc_res = res->x1.regconst;
  46930. } else {
  46931. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  46932. duk__emit_a_b_c(comp_ctx,
  46933. DUK_OP_GETPROP,
  46934. (duk_regconst_t) reg_temp,
  46935. (duk_regconst_t) reg_obj,
  46936. rc_key);
  46937. duk__emit_a_b_c(comp_ctx,
  46938. args_op,
  46939. (duk_regconst_t) reg_temp,
  46940. (duk_regconst_t) reg_temp,
  46941. res->x1.regconst);
  46942. rc_res = (duk_regconst_t) reg_temp;
  46943. }
  46944. duk__emit_a_b_c(comp_ctx,
  46945. DUK_OP_PUTPROP | DUK__EMIT_FLAG_A_IS_SOURCE,
  46946. (duk_regconst_t) reg_obj,
  46947. rc_key,
  46948. rc_res);
  46949. res->t = DUK_IVAL_PLAIN;
  46950. res->x1.t = DUK_ISPEC_REGCONST;
  46951. res->x1.regconst = rc_res;
  46952. } else {
  46953. /* No support for lvalues returned from new or function call expressions.
  46954. * However, these must NOT cause compile-time SyntaxErrors, but run-time
  46955. * ReferenceErrors. Both left and right sides of the assignment must be
  46956. * evaluated before throwing a ReferenceError. For instance:
  46957. *
  46958. * f() = g();
  46959. *
  46960. * must result in f() being evaluated, then g() being evaluated, and
  46961. * finally, a ReferenceError being thrown. See E5 Section 11.13.1.
  46962. */
  46963. duk_regconst_t rc_res;
  46964. /* first evaluate LHS fully to ensure all side effects are out */
  46965. duk__ivalue_toplain_ignore(comp_ctx, left);
  46966. /* then evaluate RHS fully (its value becomes the expression value too) */
  46967. rc_res = duk__expr_toregconst(comp_ctx, res, args_rbp /*rbp_flags*/);
  46968. duk__emit_extraop_only(comp_ctx,
  46969. DUK_EXTRAOP_INVLHS);
  46970. /* XXX: this value is irrelevant because of INVLHS? */
  46971. res->t = DUK_IVAL_PLAIN;
  46972. res->x1.t = DUK_ISPEC_REGCONST;
  46973. res->x1.regconst = rc_res;
  46974. }
  46975. return;
  46976. }
  46977. postincdec:
  46978. {
  46979. /*
  46980. * Post-increment/decrement will return the original value as its
  46981. * result value. However, even that value will be coerced using
  46982. * ToNumber() which is quite awkward. Specific bytecode opcodes
  46983. * are used to handle these semantics.
  46984. *
  46985. * Note that post increment/decrement has a "no LineTerminator here"
  46986. * restriction. This is handled by duk__expr_lbp(), which forcibly terminates
  46987. * the previous expression if a LineTerminator occurs before '++'/'--'.
  46988. */
  46989. duk_reg_t reg_res;
  46990. duk_small_uint_t args_op = args >> 8;
  46991. /* Specific assumptions for opcode numbering. */
  46992. DUK_ASSERT(DUK_OP_POSTINCR + 4 == DUK_OP_POSTINCV);
  46993. DUK_ASSERT(DUK_OP_POSTDECR + 4 == DUK_OP_POSTDECV);
  46994. DUK_ASSERT(DUK_OP_POSTINCR + 8 == DUK_OP_POSTINCP);
  46995. DUK_ASSERT(DUK_OP_POSTDECR + 8 == DUK_OP_POSTDECP);
  46996. reg_res = DUK__ALLOCTEMP(comp_ctx);
  46997. if (left->t == DUK_IVAL_VAR) {
  46998. duk_hstring *h_varname;
  46999. duk_reg_t reg_varbind;
  47000. duk_regconst_t rc_varname;
  47001. h_varname = duk_get_hstring(ctx, left->x1.valstack_idx);
  47002. DUK_ASSERT(h_varname != NULL);
  47003. if (duk__hstring_is_eval_or_arguments_in_strict_mode(comp_ctx, h_varname)) {
  47004. goto syntax_error;
  47005. }
  47006. duk_dup(ctx, left->x1.valstack_idx);
  47007. if (duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname)) {
  47008. duk__emit_a_bc(comp_ctx,
  47009. args_op, /* e.g. DUK_OP_POSTINCR */
  47010. (duk_regconst_t) reg_res,
  47011. (duk_regconst_t) reg_varbind);
  47012. } else {
  47013. duk__emit_a_bc(comp_ctx,
  47014. args_op + 4, /* e.g. DUK_OP_POSTINCV */
  47015. (duk_regconst_t) reg_res,
  47016. rc_varname);
  47017. }
  47018. DUK_DDD(DUK_DDDPRINT("postincdec to '%!O' -> reg_varbind=%ld, rc_varname=%ld",
  47019. (duk_heaphdr *) h_varname, (long) reg_varbind, (long) rc_varname));
  47020. } else if (left->t == DUK_IVAL_PROP) {
  47021. duk_reg_t reg_obj; /* allocate to reg only (not const) */
  47022. duk_regconst_t rc_key;
  47023. reg_obj = duk__ispec_toregconst_raw(comp_ctx, &left->x1, -1 /*forced_reg*/, 0 /*flags*/); /* don't allow const */
  47024. rc_key = duk__ispec_toregconst_raw(comp_ctx, &left->x2, -1 /*forced_reg*/, DUK__IVAL_FLAG_ALLOW_CONST /*flags*/);
  47025. duk__emit_a_b_c(comp_ctx,
  47026. args_op + 8, /* e.g. DUK_OP_POSTINCP */
  47027. (duk_regconst_t) reg_res,
  47028. (duk_regconst_t) reg_obj,
  47029. rc_key);
  47030. } else {
  47031. /* Technically return value is not needed because INVLHS will
  47032. * unconditially throw a ReferenceError. Coercion is necessary
  47033. * for proper semantics (consider ToNumber() called for an object).
  47034. * Use DUK_EXTRAOP_UNP with a dummy register to get ToNumber().
  47035. */
  47036. duk__ivalue_toforcedreg(comp_ctx, left, reg_res);
  47037. duk__emit_extraop_bc(comp_ctx,
  47038. DUK_EXTRAOP_UNP,
  47039. reg_res); /* for side effects, result ignored */
  47040. duk__emit_extraop_only(comp_ctx,
  47041. DUK_EXTRAOP_INVLHS);
  47042. }
  47043. res->t = DUK_IVAL_PLAIN;
  47044. res->x1.t = DUK_ISPEC_REGCONST;
  47045. res->x1.regconst = (duk_regconst_t) reg_res;
  47046. DUK__SETTEMP(comp_ctx, reg_res + 1);
  47047. return;
  47048. }
  47049. syntax_error:
  47050. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_EXPRESSION);
  47051. return;
  47052. syntax_error_lvalue:
  47053. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_LVALUE);
  47054. return;
  47055. }
  47056. DUK_LOCAL duk_small_uint_t duk__expr_lbp(duk_compiler_ctx *comp_ctx) {
  47057. duk_small_int_t tok = comp_ctx->curr_token.t;
  47058. DUK_ASSERT(tok >= DUK_TOK_MINVAL && tok <= DUK_TOK_MAXVAL);
  47059. DUK_ASSERT(sizeof(duk__token_lbp) == DUK_TOK_MAXVAL + 1);
  47060. /* XXX: integrate support for this into led() instead?
  47061. * Similar issue as post-increment/post-decrement.
  47062. */
  47063. /* prevent duk__expr_led() by using a binding power less than anything valid */
  47064. if (tok == DUK_TOK_IN && !comp_ctx->curr_func.allow_in) {
  47065. return 0;
  47066. }
  47067. if ((tok == DUK_TOK_DECREMENT || tok == DUK_TOK_INCREMENT) &&
  47068. (comp_ctx->curr_token.lineterm)) {
  47069. /* '++' or '--' in a post-increment/decrement position,
  47070. * and a LineTerminator occurs between the operator and
  47071. * the preceding expression. Force the previous expr
  47072. * to terminate, in effect treating e.g. "a,b\n++" as
  47073. * "a,b;++" (= SyntaxError).
  47074. */
  47075. return 0;
  47076. }
  47077. return DUK__TOKEN_LBP_GET_BP(duk__token_lbp[tok]); /* format is bit packed */
  47078. }
  47079. /*
  47080. * Expression parsing.
  47081. *
  47082. * Upon entry to 'expr' and its variants, 'curr_tok' is assumed to be the
  47083. * first token of the expression. Upon exit, 'curr_tok' will be the first
  47084. * token not part of the expression (e.g. semicolon terminating an expression
  47085. * statement).
  47086. */
  47087. #define DUK__EXPR_RBP_MASK 0xff
  47088. #define DUK__EXPR_FLAG_REJECT_IN (1 << 8)
  47089. #define DUK__EXPR_FLAG_ALLOW_EMPTY (1 << 9)
  47090. /* main expression parser function */
  47091. DUK_LOCAL void duk__expr(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47092. duk_hthread *thr = comp_ctx->thr;
  47093. duk_context *ctx = (duk_context *) thr;
  47094. duk_ivalue tmp_alloc; /* 'res' is used for "left", and 'tmp' for "right" */
  47095. duk_ivalue *tmp = &tmp_alloc;
  47096. duk_small_uint_t rbp;
  47097. DUK__RECURSION_INCREASE(comp_ctx, thr);
  47098. duk_require_stack(ctx, DUK__PARSE_EXPR_SLOTS);
  47099. /* filter out flags from exprtop rbp_flags here to save space */
  47100. rbp = rbp_flags & DUK__EXPR_RBP_MASK;
  47101. DUK_DDD(DUK_DDDPRINT("duk__expr(), rbp_flags=%ld, rbp=%ld, allow_in=%ld, paren_level=%ld",
  47102. (long) rbp_flags, (long) rbp, (long) comp_ctx->curr_func.allow_in,
  47103. (long) comp_ctx->curr_func.paren_level));
  47104. DUK_MEMZERO(&tmp_alloc, sizeof(tmp_alloc));
  47105. tmp->x1.valstack_idx = duk_get_top(ctx);
  47106. tmp->x2.valstack_idx = tmp->x1.valstack_idx + 1;
  47107. duk_push_undefined(ctx);
  47108. duk_push_undefined(ctx);
  47109. /* XXX: where to release temp regs in intermediate expressions?
  47110. * e.g. 1+2+3 -> don't inflate temp register count when parsing this.
  47111. * that particular expression temp regs can be forced here.
  47112. */
  47113. /* XXX: increase ctx->expr_tokens here for every consumed token
  47114. * (this would be a nice statistic)?
  47115. */
  47116. if (comp_ctx->curr_token.t == DUK_TOK_SEMICOLON || comp_ctx->curr_token.t == DUK_TOK_RPAREN) {
  47117. /* XXX: possibly incorrect handling of empty expression */
  47118. DUK_DDD(DUK_DDDPRINT("empty expression"));
  47119. if (!(rbp_flags & DUK__EXPR_FLAG_ALLOW_EMPTY)) {
  47120. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_EMPTY_EXPR_NOT_ALLOWED);
  47121. }
  47122. res->t = DUK_IVAL_PLAIN;
  47123. res->x1.t = DUK_ISPEC_VALUE;
  47124. duk_push_undefined(ctx);
  47125. duk_replace(ctx, res->x1.valstack_idx);
  47126. goto cleanup;
  47127. }
  47128. duk__advance(comp_ctx);
  47129. duk__expr_nud(comp_ctx, res); /* reuse 'res' as 'left' */
  47130. while (rbp < duk__expr_lbp(comp_ctx)) {
  47131. duk__advance(comp_ctx);
  47132. duk__expr_led(comp_ctx, res, tmp);
  47133. duk__copy_ivalue(comp_ctx, tmp, res); /* tmp -> res */
  47134. }
  47135. cleanup:
  47136. /* final result is already in 'res' */
  47137. duk_pop_2(ctx);
  47138. DUK__RECURSION_DECREASE(comp_ctx, thr);
  47139. }
  47140. DUK_LOCAL void duk__exprtop(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47141. duk_hthread *thr = comp_ctx->thr;
  47142. /* Note: these variables must reside in 'curr_func' instead of the global
  47143. * context: when parsing function expressions, expression parsing is nested.
  47144. */
  47145. comp_ctx->curr_func.nud_count = 0;
  47146. comp_ctx->curr_func.led_count = 0;
  47147. comp_ctx->curr_func.paren_level = 0;
  47148. comp_ctx->curr_func.expr_lhs = 1;
  47149. comp_ctx->curr_func.allow_in = (rbp_flags & DUK__EXPR_FLAG_REJECT_IN ? 0 : 1);
  47150. duk__expr(comp_ctx, res, rbp_flags);
  47151. if (!(rbp_flags & DUK__EXPR_FLAG_ALLOW_EMPTY) && duk__expr_is_empty(comp_ctx)) {
  47152. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_EMPTY_EXPR_NOT_ALLOWED);
  47153. }
  47154. }
  47155. /* A bunch of helpers (for size optimization) that combine duk__expr()/duk__exprtop()
  47156. * and result conversions.
  47157. *
  47158. * Each helper needs at least 2-3 calls to make it worth while to wrap.
  47159. */
  47160. DUK_LOCAL duk_reg_t duk__expr_toreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47161. duk__expr(comp_ctx, res, rbp_flags);
  47162. return duk__ivalue_toreg(comp_ctx, res);
  47163. }
  47164. #if 0 /* unused */
  47165. DUK_LOCAL duk_reg_t duk__expr_totempreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47166. duk__expr(comp_ctx, res, rbp_flags);
  47167. return duk__ivalue_totempreg(comp_ctx, res);
  47168. }
  47169. #endif
  47170. DUK_LOCAL void duk__expr_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags, duk_reg_t forced_reg) {
  47171. DUK_ASSERT(forced_reg >= 0);
  47172. duk__expr(comp_ctx, res, rbp_flags);
  47173. duk__ivalue_toforcedreg(comp_ctx, res, forced_reg);
  47174. }
  47175. DUK_LOCAL duk_regconst_t duk__expr_toregconst(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47176. duk__expr(comp_ctx, res, rbp_flags);
  47177. return duk__ivalue_toregconst(comp_ctx, res);
  47178. }
  47179. DUK_LOCAL void duk__expr_toplain(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47180. duk__expr(comp_ctx, res, rbp_flags);
  47181. duk__ivalue_toplain(comp_ctx, res);
  47182. }
  47183. DUK_LOCAL void duk__expr_toplain_ignore(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47184. duk__expr(comp_ctx, res, rbp_flags);
  47185. duk__ivalue_toplain_ignore(comp_ctx, res);
  47186. }
  47187. DUK_LOCAL duk_reg_t duk__exprtop_toreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47188. duk__exprtop(comp_ctx, res, rbp_flags);
  47189. return duk__ivalue_toreg(comp_ctx, res);
  47190. }
  47191. #if 0 /* unused */
  47192. DUK_LOCAL duk_reg_t duk__exprtop_totempreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47193. duk__exprtop(comp_ctx, res, rbp_flags);
  47194. return duk__ivalue_totempreg(comp_ctx, res);
  47195. }
  47196. #endif
  47197. #if 0 /* unused */
  47198. DUK_LOCAL void duk__exprtop_toforcedreg(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags, duk_reg_t forced_reg) {
  47199. DUK_ASSERT(forced_reg >= 0);
  47200. duk__exprtop(comp_ctx, res, rbp_flags);
  47201. duk__ivalue_toforcedreg(comp_ctx, res, forced_reg);
  47202. }
  47203. #endif
  47204. DUK_LOCAL duk_regconst_t duk__exprtop_toregconst(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t rbp_flags) {
  47205. duk__exprtop(comp_ctx, res, rbp_flags);
  47206. return duk__ivalue_toregconst(comp_ctx, res);
  47207. }
  47208. #if 0 /* unused */
  47209. DUK_LOCAL void duk__exprtop_toplain_ignore(duk_compiler_ctx *comp_ctx, duk_ivalue *res, int rbp_flags) {
  47210. duk__exprtop(comp_ctx, res, rbp_flags);
  47211. duk__ivalue_toplain_ignore(comp_ctx, res);
  47212. }
  47213. #endif
  47214. /*
  47215. * Parse an individual source element (top level statement) or a statement.
  47216. *
  47217. * Handles labeled statements automatically (peeling away labels before
  47218. * parsing an expression that follows the label(s)).
  47219. *
  47220. * Upon entry, 'curr_tok' contains the first token of the statement (parsed
  47221. * in "allow regexp literal" mode). Upon exit, 'curr_tok' contains the first
  47222. * token following the statement (if the statement has a terminator, this is
  47223. * the token after the terminator).
  47224. */
  47225. #ifdef DUK__HAS_VAL
  47226. #undef DUK__HAS_VAL
  47227. #endif
  47228. #ifdef DUK__HAS_TERM
  47229. #undef DUK__HAS_TERM
  47230. #endif
  47231. #ifdef DUK__ALLOW_AUTO_SEMI_ALWAYS
  47232. #undef DUK__ALLOW_AUTO_SEMI_ALWAYS
  47233. #endif
  47234. #ifdef DUK__STILL_PROLOGUE
  47235. #undef DUK__STILL_PROLOGUE
  47236. #endif
  47237. #ifdef DUK__IS_TERMINAL
  47238. #undef DUK__IS_TERMINAL
  47239. #endif
  47240. #define DUK__HAS_VAL (1 << 0) /* stmt has non-empty value */
  47241. #define DUK__HAS_TERM (1 << 1) /* stmt has explicit/implicit semicolon terminator */
  47242. #define DUK__ALLOW_AUTO_SEMI_ALWAYS (1 << 2) /* allow automatic semicolon even without lineterm (compatibility) */
  47243. #define DUK__STILL_PROLOGUE (1 << 3) /* statement does not terminate directive prologue */
  47244. #define DUK__IS_TERMINAL (1 << 4) /* statement is guaranteed to be terminal (control doesn't flow to next statement) */
  47245. /* Parse a single variable declaration (e.g. "i" or "i=10"). A leading 'var'
  47246. * has already been eaten. These is no return value in 'res', it is used only
  47247. * as a temporary.
  47248. *
  47249. * When called from 'for-in' statement parser, the initializer expression must
  47250. * not allow the 'in' token. The caller supply additional expression parsing
  47251. * flags (like DUK__EXPR_FLAG_REJECT_IN) in 'expr_flags'.
  47252. *
  47253. * Finally, out_rc_varname and out_reg_varbind are updated to reflect where
  47254. * the identifier is bound:
  47255. *
  47256. * If register bound: out_reg_varbind >= 0, out_rc_varname == 0 (ignore)
  47257. * If not register bound: out_reg_varbind < 0, out_rc_varname >= 0
  47258. *
  47259. * These allow the caller to use the variable for further assignment, e.g.
  47260. * as is done in 'for-in' parsing.
  47261. */
  47262. DUK_LOCAL void duk__parse_var_decl(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_small_uint_t expr_flags, duk_reg_t *out_reg_varbind, duk_regconst_t *out_rc_varname) {
  47263. duk_hthread *thr = comp_ctx->thr;
  47264. duk_context *ctx = (duk_context *) thr;
  47265. duk_hstring *h_varname;
  47266. duk_reg_t reg_varbind;
  47267. duk_regconst_t rc_varname;
  47268. /* assume 'var' has been eaten */
  47269. /* Note: Identifier rejects reserved words */
  47270. if (comp_ctx->curr_token.t != DUK_TOK_IDENTIFIER) {
  47271. goto syntax_error;
  47272. }
  47273. h_varname = comp_ctx->curr_token.str1;
  47274. DUK_ASSERT(h_varname != NULL);
  47275. /* strict mode restrictions (E5 Section 12.2.1) */
  47276. if (duk__hstring_is_eval_or_arguments_in_strict_mode(comp_ctx, h_varname)) {
  47277. goto syntax_error;
  47278. }
  47279. /* register declarations in first pass */
  47280. if (comp_ctx->curr_func.in_scanning) {
  47281. duk_uarridx_t n;
  47282. DUK_DDD(DUK_DDDPRINT("register variable declaration %!O in pass 1",
  47283. (duk_heaphdr *) h_varname));
  47284. n = (duk_uarridx_t) duk_get_length(ctx, comp_ctx->curr_func.decls_idx);
  47285. duk_push_hstring(ctx, h_varname);
  47286. duk_put_prop_index(ctx, comp_ctx->curr_func.decls_idx, n);
  47287. duk_push_int(ctx, DUK_DECL_TYPE_VAR + (0 << 8));
  47288. duk_put_prop_index(ctx, comp_ctx->curr_func.decls_idx, n + 1);
  47289. }
  47290. duk_push_hstring(ctx, h_varname); /* push before advancing to keep reachable */
  47291. /* register binding lookup is based on varmap (even in first pass) */
  47292. duk_dup_top(ctx);
  47293. (void) duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname);
  47294. duk__advance(comp_ctx); /* eat identifier */
  47295. if (comp_ctx->curr_token.t == DUK_TOK_EQUALSIGN) {
  47296. duk__advance(comp_ctx);
  47297. DUK_DDD(DUK_DDDPRINT("vardecl, assign to '%!O' -> reg_varbind=%ld, rc_varname=%ld",
  47298. (duk_heaphdr *) h_varname, (long) reg_varbind, (long) rc_varname));
  47299. duk__exprtop(comp_ctx, res, DUK__BP_COMMA | expr_flags /*rbp_flags*/); /* AssignmentExpression */
  47300. if (reg_varbind >= 0) {
  47301. duk__ivalue_toforcedreg(comp_ctx, res, reg_varbind);
  47302. } else {
  47303. duk_reg_t reg_val;
  47304. reg_val = duk__ivalue_toreg(comp_ctx, res);
  47305. duk__emit_a_bc(comp_ctx,
  47306. DUK_OP_PUTVAR | DUK__EMIT_FLAG_A_IS_SOURCE,
  47307. (duk_regconst_t) reg_val,
  47308. rc_varname);
  47309. }
  47310. }
  47311. duk_pop(ctx); /* pop varname */
  47312. *out_rc_varname = rc_varname;
  47313. *out_reg_varbind = reg_varbind;
  47314. return;
  47315. syntax_error:
  47316. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_VAR_DECLARATION);
  47317. }
  47318. DUK_LOCAL void duk__parse_var_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  47319. duk_reg_t reg_varbind;
  47320. duk_regconst_t rc_varname;
  47321. duk__advance(comp_ctx); /* eat 'var' */
  47322. for (;;) {
  47323. /* rc_varname and reg_varbind are ignored here */
  47324. duk__parse_var_decl(comp_ctx, res, 0, &reg_varbind, &rc_varname);
  47325. if (comp_ctx->curr_token.t != DUK_TOK_COMMA) {
  47326. break;
  47327. }
  47328. duk__advance(comp_ctx);
  47329. }
  47330. }
  47331. DUK_LOCAL void duk__parse_for_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site) {
  47332. duk_hthread *thr = comp_ctx->thr;
  47333. duk_context *ctx = (duk_context *) thr;
  47334. duk_int_t pc_v34_lhs; /* start variant 3/4 left-hand-side code (L1 in doc/compiler.txt example) */
  47335. duk_reg_t temp_reset; /* knock back "next temp" to this whenever possible */
  47336. duk_reg_t reg_temps; /* preallocated temporaries (2) for variants 3 and 4 */
  47337. DUK_DDD(DUK_DDDPRINT("start parsing a for/for-in statement"));
  47338. /* Two temporaries are preallocated here for variants 3 and 4 which need
  47339. * registers which are never clobbered by expressions in the loop
  47340. * (concretely: for the enumerator object and the next enumerated value).
  47341. * Variants 1 and 2 "release" these temps.
  47342. */
  47343. reg_temps = DUK__ALLOCTEMPS(comp_ctx, 2);
  47344. temp_reset = DUK__GETTEMP(comp_ctx);
  47345. /*
  47346. * For/for-in main variants are:
  47347. *
  47348. * 1. for (ExpressionNoIn_opt; Expression_opt; Expression_opt) Statement
  47349. * 2. for (var VariableDeclarationNoIn; Expression_opt; Expression_opt) Statement
  47350. * 3. for (LeftHandSideExpression in Expression) Statement
  47351. * 4. for (var VariableDeclarationNoIn in Expression) Statement
  47352. *
  47353. * Parsing these without arbitrary lookahead or backtracking is relatively
  47354. * tricky but we manage to do so for now.
  47355. *
  47356. * See doc/compiler.txt for a detailed discussion of control flow
  47357. * issues, evaluation order issues, etc.
  47358. */
  47359. duk__advance(comp_ctx); /* eat 'for' */
  47360. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  47361. DUK_DDD(DUK_DDDPRINT("detecting for/for-in loop variant, pc=%ld", (long) duk__get_current_pc(comp_ctx)));
  47362. /* a label site has been emitted by duk__parse_stmt() automatically
  47363. * (it will also emit the ENDLABEL).
  47364. */
  47365. if (comp_ctx->curr_token.t == DUK_TOK_VAR) {
  47366. /*
  47367. * Variant 2 or 4
  47368. */
  47369. duk_reg_t reg_varbind; /* variable binding register if register-bound (otherwise < 0) */
  47370. duk_regconst_t rc_varname; /* variable name reg/const, if variable not register-bound */
  47371. duk__advance(comp_ctx); /* eat 'var' */
  47372. duk__parse_var_decl(comp_ctx, res, DUK__EXPR_FLAG_REJECT_IN, &reg_varbind, &rc_varname);
  47373. DUK__SETTEMP(comp_ctx, temp_reset);
  47374. if (comp_ctx->curr_token.t == DUK_TOK_IN) {
  47375. /*
  47376. * Variant 4
  47377. */
  47378. DUK_DDD(DUK_DDDPRINT("detected for variant 4: for (var VariableDeclarationNoIn in Expression) Statement"));
  47379. pc_v34_lhs = duk__get_current_pc(comp_ctx); /* jump is inserted here */
  47380. if (reg_varbind >= 0) {
  47381. duk__emit_a_bc(comp_ctx,
  47382. DUK_OP_LDREG,
  47383. (duk_regconst_t) reg_varbind,
  47384. (duk_regconst_t) (reg_temps + 0));
  47385. } else {
  47386. duk__emit_a_bc(comp_ctx,
  47387. DUK_OP_PUTVAR | DUK__EMIT_FLAG_A_IS_SOURCE,
  47388. (duk_regconst_t) (reg_temps + 0),
  47389. rc_varname);
  47390. }
  47391. goto parse_3_or_4;
  47392. } else {
  47393. /*
  47394. * Variant 2
  47395. */
  47396. DUK_DDD(DUK_DDDPRINT("detected for variant 2: for (var VariableDeclarationNoIn; Expression_opt; Expression_opt) Statement"));
  47397. for (;;) {
  47398. /* more initializers */
  47399. if (comp_ctx->curr_token.t != DUK_TOK_COMMA) {
  47400. break;
  47401. }
  47402. DUK_DDD(DUK_DDDPRINT("variant 2 has another variable initializer"));
  47403. duk__advance(comp_ctx); /* eat comma */
  47404. duk__parse_var_decl(comp_ctx, res, DUK__EXPR_FLAG_REJECT_IN, &reg_varbind, &rc_varname);
  47405. }
  47406. goto parse_1_or_2;
  47407. }
  47408. } else {
  47409. /*
  47410. * Variant 1 or 3
  47411. */
  47412. pc_v34_lhs = duk__get_current_pc(comp_ctx); /* jump is inserted here (variant 3) */
  47413. /* Note that duk__exprtop() here can clobber any reg above current temp_next,
  47414. * so any loop variables (e.g. enumerator) must be "preallocated".
  47415. */
  47416. /* don't coerce yet to a plain value (variant 3 needs special handling) */
  47417. duk__exprtop(comp_ctx, res, DUK__BP_FOR_EXPR | DUK__EXPR_FLAG_REJECT_IN | DUK__EXPR_FLAG_ALLOW_EMPTY /*rbp_flags*/); /* Expression */
  47418. if (comp_ctx->curr_token.t == DUK_TOK_IN) {
  47419. /*
  47420. * Variant 3
  47421. */
  47422. /* XXX: need to determine LHS type, and check that it is LHS compatible */
  47423. DUK_DDD(DUK_DDDPRINT("detected for variant 3: for (LeftHandSideExpression in Expression) Statement"));
  47424. if (duk__expr_is_empty(comp_ctx)) {
  47425. goto syntax_error; /* LeftHandSideExpression does not allow empty expression */
  47426. }
  47427. if (res->t == DUK_IVAL_VAR) {
  47428. duk_reg_t reg_varbind;
  47429. duk_regconst_t rc_varname;
  47430. duk_dup(ctx, res->x1.valstack_idx);
  47431. if (duk__lookup_lhs(comp_ctx, &reg_varbind, &rc_varname)) {
  47432. duk__emit_a_bc(comp_ctx,
  47433. DUK_OP_LDREG,
  47434. (duk_regconst_t) reg_varbind,
  47435. (duk_regconst_t) (reg_temps + 0));
  47436. } else {
  47437. duk__emit_a_bc(comp_ctx,
  47438. DUK_OP_PUTVAR | DUK__EMIT_FLAG_A_IS_SOURCE,
  47439. (duk_regconst_t) (reg_temps + 0),
  47440. rc_varname);
  47441. }
  47442. } else if (res->t == DUK_IVAL_PROP) {
  47443. /* Don't allow a constant for the object (even for a number etc), as
  47444. * it goes into the 'A' field of the opcode.
  47445. */
  47446. duk_reg_t reg_obj;
  47447. duk_regconst_t rc_key;
  47448. reg_obj = duk__ispec_toregconst_raw(comp_ctx, &res->x1, -1 /*forced_reg*/, 0 /*flags*/); /* don't allow const */
  47449. rc_key = duk__ispec_toregconst_raw(comp_ctx, &res->x2, -1 /*forced_reg*/, DUK__IVAL_FLAG_ALLOW_CONST /*flags*/);
  47450. duk__emit_a_b_c(comp_ctx,
  47451. DUK_OP_PUTPROP | DUK__EMIT_FLAG_A_IS_SOURCE,
  47452. (duk_regconst_t) reg_obj,
  47453. rc_key,
  47454. (duk_regconst_t) (reg_temps + 0));
  47455. } else {
  47456. duk__ivalue_toplain_ignore(comp_ctx, res); /* just in case */
  47457. duk__emit_extraop_only(comp_ctx,
  47458. DUK_EXTRAOP_INVLHS);
  47459. }
  47460. goto parse_3_or_4;
  47461. } else {
  47462. /*
  47463. * Variant 1
  47464. */
  47465. DUK_DDD(DUK_DDDPRINT("detected for variant 1: for (ExpressionNoIn_opt; Expression_opt; Expression_opt) Statement"));
  47466. duk__ivalue_toplain_ignore(comp_ctx, res);
  47467. goto parse_1_or_2;
  47468. }
  47469. }
  47470. parse_1_or_2:
  47471. /*
  47472. * Parse variant 1 or 2. The first part expression (which differs
  47473. * in the variants) has already been parsed and its code emitted.
  47474. *
  47475. * reg_temps + 0: unused
  47476. * reg_temps + 1: unused
  47477. */
  47478. {
  47479. duk_regconst_t rc_cond;
  47480. duk_int_t pc_l1, pc_l2, pc_l3, pc_l4;
  47481. duk_int_t pc_jumpto_l3, pc_jumpto_l4;
  47482. duk_bool_t expr_c_empty;
  47483. DUK_DDD(DUK_DDDPRINT("shared code for parsing variants 1 and 2"));
  47484. /* "release" preallocated temps since we won't need them */
  47485. temp_reset = reg_temps + 0;
  47486. DUK__SETTEMP(comp_ctx, temp_reset);
  47487. duk__advance_expect(comp_ctx, DUK_TOK_SEMICOLON);
  47488. pc_l1 = duk__get_current_pc(comp_ctx);
  47489. duk__exprtop(comp_ctx, res, DUK__BP_FOR_EXPR | DUK__EXPR_FLAG_ALLOW_EMPTY /*rbp_flags*/); /* Expression_opt */
  47490. if (duk__expr_is_empty(comp_ctx)) {
  47491. /* no need to coerce */
  47492. pc_jumpto_l3 = duk__emit_jump_empty(comp_ctx); /* to body */
  47493. pc_jumpto_l4 = -1; /* omitted */
  47494. } else {
  47495. rc_cond = duk__ivalue_toregconst(comp_ctx, res);
  47496. duk__emit_if_false_skip(comp_ctx, rc_cond);
  47497. pc_jumpto_l3 = duk__emit_jump_empty(comp_ctx); /* to body */
  47498. pc_jumpto_l4 = duk__emit_jump_empty(comp_ctx); /* to exit */
  47499. }
  47500. DUK__SETTEMP(comp_ctx, temp_reset);
  47501. duk__advance_expect(comp_ctx, DUK_TOK_SEMICOLON);
  47502. pc_l2 = duk__get_current_pc(comp_ctx);
  47503. duk__exprtop(comp_ctx, res, DUK__BP_FOR_EXPR | DUK__EXPR_FLAG_ALLOW_EMPTY /*rbp_flags*/); /* Expression_opt */
  47504. if (duk__expr_is_empty(comp_ctx)) {
  47505. /* no need to coerce */
  47506. expr_c_empty = 1;
  47507. /* JUMP L1 omitted */
  47508. } else {
  47509. duk__ivalue_toplain_ignore(comp_ctx, res);
  47510. expr_c_empty = 0;
  47511. duk__emit_jump(comp_ctx, pc_l1);
  47512. }
  47513. DUK__SETTEMP(comp_ctx, temp_reset);
  47514. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  47515. pc_l3 = duk__get_current_pc(comp_ctx);
  47516. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  47517. if (expr_c_empty) {
  47518. duk__emit_jump(comp_ctx, pc_l1);
  47519. } else {
  47520. duk__emit_jump(comp_ctx, pc_l2);
  47521. }
  47522. /* temp reset is not necessary after duk__parse_stmt(), which already does it */
  47523. pc_l4 = duk__get_current_pc(comp_ctx);
  47524. DUK_DDD(DUK_DDDPRINT("patching jumps: jumpto_l3: %ld->%ld, jumpto_l4: %ld->%ld, "
  47525. "break: %ld->%ld, continue: %ld->%ld",
  47526. (long) pc_jumpto_l3, (long) pc_l3, (long) pc_jumpto_l4, (long) pc_l4,
  47527. (long) (pc_label_site + 1), (long) pc_l4, (long) (pc_label_site + 2), (long) pc_l2));
  47528. duk__patch_jump(comp_ctx, pc_jumpto_l3, pc_l3);
  47529. duk__patch_jump(comp_ctx, pc_jumpto_l4, pc_l4);
  47530. duk__patch_jump(comp_ctx,
  47531. pc_label_site + 1,
  47532. pc_l4); /* break jump */
  47533. duk__patch_jump(comp_ctx,
  47534. pc_label_site + 2,
  47535. expr_c_empty ? pc_l1 : pc_l2); /* continue jump */
  47536. }
  47537. goto finished;
  47538. parse_3_or_4:
  47539. /*
  47540. * Parse variant 3 or 4.
  47541. *
  47542. * For variant 3 (e.g. "for (A in C) D;") the code for A (except the
  47543. * final property/variable write) has already been emitted. The first
  47544. * instruction of that code is at pc_v34_lhs; a JUMP needs to be inserted
  47545. * there to satisfy control flow needs.
  47546. *
  47547. * For variant 4, if the variable declaration had an initializer
  47548. * (e.g. "for (var A = B in C) D;") the code for the assignment
  47549. * (B) has already been emitted.
  47550. *
  47551. * Variables set before entering here:
  47552. *
  47553. * pc_v34_lhs: insert a "JUMP L2" here (see doc/compiler.txt example).
  47554. * reg_temps + 0: iteration target value (written to LHS)
  47555. * reg_temps + 1: enumerator object
  47556. */
  47557. {
  47558. duk_int_t pc_l1, pc_l2, pc_l3, pc_l4, pc_l5;
  47559. duk_int_t pc_jumpto_l2, pc_jumpto_l3, pc_jumpto_l4, pc_jumpto_l5;
  47560. duk_reg_t reg_target;
  47561. DUK_DDD(DUK_DDDPRINT("shared code for parsing variants 3 and 4, pc_v34_lhs=%ld", (long) pc_v34_lhs));
  47562. DUK__SETTEMP(comp_ctx, temp_reset);
  47563. /* First we need to insert a jump in the middle of previously
  47564. * emitted code to get the control flow right. No jumps can
  47565. * cross the position where the jump is inserted. See doc/compiler.txt
  47566. * for discussion on the intricacies of control flow and side effects
  47567. * for variants 3 and 4.
  47568. */
  47569. duk__insert_jump_entry(comp_ctx, pc_v34_lhs);
  47570. pc_jumpto_l2 = pc_v34_lhs; /* inserted jump */
  47571. pc_l1 = pc_v34_lhs + 1; /* +1, right after inserted jump */
  47572. /* The code for writing reg_temps + 0 to the left hand side has already
  47573. * been emitted.
  47574. */
  47575. pc_jumpto_l3 = duk__emit_jump_empty(comp_ctx); /* -> loop body */
  47576. duk__advance(comp_ctx); /* eat 'in' */
  47577. /* Parse enumeration target and initialize enumerator. For 'null' and 'undefined',
  47578. * INITENUM will creates a 'null' enumerator which works like an empty enumerator
  47579. * (E5 Section 12.6.4, step 3). Note that INITENUM requires the value to be in a
  47580. * register (constant not allowed).
  47581. */
  47582. pc_l2 = duk__get_current_pc(comp_ctx);
  47583. reg_target = duk__exprtop_toreg(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/); /* Expression */
  47584. duk__emit_extraop_b_c(comp_ctx,
  47585. DUK_EXTRAOP_INITENUM | DUK__EMIT_FLAG_B_IS_TARGET,
  47586. (duk_regconst_t) (reg_temps + 1),
  47587. (duk_regconst_t) reg_target);
  47588. pc_jumpto_l4 = duk__emit_jump_empty(comp_ctx);
  47589. DUK__SETTEMP(comp_ctx, temp_reset);
  47590. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  47591. pc_l3 = duk__get_current_pc(comp_ctx);
  47592. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  47593. /* temp reset is not necessary after duk__parse_stmt(), which already does it */
  47594. /* NEXTENUM needs a jump slot right after the main opcode.
  47595. * We need the code emitter to reserve the slot: if there's
  47596. * target shuffling, the target shuffle opcodes must happen
  47597. * after the jump slot (for NEXTENUM the shuffle opcodes are
  47598. * not needed if the enum is finished).
  47599. */
  47600. pc_l4 = duk__get_current_pc(comp_ctx);
  47601. duk__emit_extraop_b_c(comp_ctx,
  47602. DUK_EXTRAOP_NEXTENUM | DUK__EMIT_FLAG_B_IS_TARGET | DUK__EMIT_FLAG_RESERVE_JUMPSLOT,
  47603. (duk_regconst_t) (reg_temps + 0),
  47604. (duk_regconst_t) (reg_temps + 1));
  47605. pc_jumpto_l5 = comp_ctx->emit_jumpslot_pc; /* NEXTENUM jump slot: executed when enum finished */
  47606. duk__emit_jump(comp_ctx, pc_l1); /* jump to next loop, using reg_v34_iter as iterated value */
  47607. pc_l5 = duk__get_current_pc(comp_ctx);
  47608. /* XXX: since the enumerator may be a memory expensive object,
  47609. * perhaps clear it explicitly here? If so, break jump must
  47610. * go through this clearing operation.
  47611. */
  47612. DUK_DDD(DUK_DDDPRINT("patching jumps: jumpto_l2: %ld->%ld, jumpto_l3: %ld->%ld, "
  47613. "jumpto_l4: %ld->%ld, jumpto_l5: %ld->%ld, "
  47614. "break: %ld->%ld, continue: %ld->%ld",
  47615. (long) pc_jumpto_l2, (long) pc_l2, (long) pc_jumpto_l3, (long) pc_l3,
  47616. (long) pc_jumpto_l4, (long) pc_l4, (long) pc_jumpto_l5, (long) pc_l5,
  47617. (long) (pc_label_site + 1), (long) pc_l5, (long) (pc_label_site + 2), (long) pc_l4));
  47618. duk__patch_jump(comp_ctx, pc_jumpto_l2, pc_l2);
  47619. duk__patch_jump(comp_ctx, pc_jumpto_l3, pc_l3);
  47620. duk__patch_jump(comp_ctx, pc_jumpto_l4, pc_l4);
  47621. duk__patch_jump(comp_ctx, pc_jumpto_l5, pc_l5);
  47622. duk__patch_jump(comp_ctx, pc_label_site + 1, pc_l5); /* break jump */
  47623. duk__patch_jump(comp_ctx, pc_label_site + 2, pc_l4); /* continue jump */
  47624. }
  47625. goto finished;
  47626. finished:
  47627. DUK_DDD(DUK_DDDPRINT("end parsing a for/for-in statement"));
  47628. return;
  47629. syntax_error:
  47630. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_FOR);
  47631. }
  47632. DUK_LOCAL void duk__parse_switch_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site) {
  47633. duk_hthread *thr = comp_ctx->thr;
  47634. duk_reg_t temp_at_loop;
  47635. duk_regconst_t rc_switch; /* reg/const for switch value */
  47636. duk_regconst_t rc_case; /* reg/const for case value */
  47637. duk_reg_t reg_temp; /* general temp register */
  47638. duk_int_t pc_prevcase = -1;
  47639. duk_int_t pc_prevstmt = -1;
  47640. duk_int_t pc_default = -1; /* -1 == not set, -2 == pending (next statement list) */
  47641. /* Note: negative pc values are ignored when patching jumps, so no explicit checks needed */
  47642. /*
  47643. * Switch is pretty complicated because of several conflicting concerns:
  47644. *
  47645. * - Want to generate code without an intermediate representation,
  47646. * i.e., in one go
  47647. *
  47648. * - Case selectors are expressions, not values, and may thus e.g. throw
  47649. * exceptions (which causes evaluation order concerns)
  47650. *
  47651. * - Evaluation semantics of case selectors and default clause need to be
  47652. * carefully implemented to provide correct behavior even with case value
  47653. * side effects
  47654. *
  47655. * - Fall through case and default clauses; avoiding dead JUMPs if case
  47656. * ends with an unconditional jump (a break or a continue)
  47657. *
  47658. * - The same case value may occur multiple times, but evaluation rules
  47659. * only process the first match before switching to a "propagation" mode
  47660. * where case values are no longer evaluated
  47661. *
  47662. * See E5 Section 12.11. Also see doc/compiler.txt for compilation
  47663. * discussion.
  47664. */
  47665. duk__advance(comp_ctx);
  47666. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  47667. rc_switch = duk__exprtop_toregconst(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  47668. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  47669. duk__advance_expect(comp_ctx, DUK_TOK_LCURLY);
  47670. DUK_DDD(DUK_DDDPRINT("switch value in register %ld", (long) rc_switch));
  47671. temp_at_loop = DUK__GETTEMP(comp_ctx);
  47672. for (;;) {
  47673. duk_int_t num_stmts;
  47674. duk_small_int_t tok;
  47675. /* sufficient for keeping temp reg numbers in check */
  47676. DUK__SETTEMP(comp_ctx, temp_at_loop);
  47677. if (comp_ctx->curr_token.t == DUK_TOK_RCURLY) {
  47678. break;
  47679. }
  47680. /*
  47681. * Parse a case or default clause.
  47682. */
  47683. if (comp_ctx->curr_token.t == DUK_TOK_CASE) {
  47684. /*
  47685. * Case clause.
  47686. *
  47687. * Note: cannot use reg_case as a temp register (for SEQ target)
  47688. * because it may be a constant.
  47689. */
  47690. duk__patch_jump_here(comp_ctx, pc_prevcase); /* chain jumps for case
  47691. * evaluation and checking
  47692. */
  47693. duk__advance(comp_ctx);
  47694. rc_case = duk__exprtop_toregconst(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  47695. duk__advance_expect(comp_ctx, DUK_TOK_COLON);
  47696. reg_temp = DUK__ALLOCTEMP(comp_ctx);
  47697. duk__emit_a_b_c(comp_ctx,
  47698. DUK_OP_SEQ,
  47699. (duk_regconst_t) reg_temp,
  47700. rc_switch,
  47701. rc_case);
  47702. duk__emit_if_true_skip(comp_ctx, (duk_regconst_t) reg_temp);
  47703. /* jump to next case clause */
  47704. pc_prevcase = duk__emit_jump_empty(comp_ctx); /* no match, next case */
  47705. /* statements go here (if any) on next loop */
  47706. } else if (comp_ctx->curr_token.t == DUK_TOK_DEFAULT) {
  47707. /*
  47708. * Default clause.
  47709. */
  47710. if (pc_default >= 0) {
  47711. goto syntax_error;
  47712. }
  47713. duk__advance(comp_ctx);
  47714. duk__advance_expect(comp_ctx, DUK_TOK_COLON);
  47715. /* Fix for https://github.com/svaarala/duktape/issues/155:
  47716. * If 'default' is first clause (detected by pc_prevcase < 0)
  47717. * we need to ensure we stay in the matching chain.
  47718. */
  47719. if (pc_prevcase < 0) {
  47720. DUK_DD(DUK_DDPRINT("default clause is first, emit prevcase jump"));
  47721. pc_prevcase = duk__emit_jump_empty(comp_ctx);
  47722. }
  47723. /* default clause matches next statement list (if any) */
  47724. pc_default = -2;
  47725. } else {
  47726. /* Code is not accepted before the first case/default clause */
  47727. goto syntax_error;
  47728. }
  47729. /*
  47730. * Parse code after the clause. Possible terminators are
  47731. * 'case', 'default', and '}'.
  47732. *
  47733. * Note that there may be no code at all, not even an empty statement,
  47734. * between case clauses. This must be handled just like an empty statement
  47735. * (omitting seemingly pointless JUMPs), to avoid situations like
  47736. * test-bug-case-fallthrough.js.
  47737. */
  47738. num_stmts = 0;
  47739. if (pc_default == -2) {
  47740. pc_default = duk__get_current_pc(comp_ctx);
  47741. }
  47742. /* Note: this is correct even for default clause statements:
  47743. * they participate in 'fall-through' behavior even if the
  47744. * default clause is in the middle.
  47745. */
  47746. duk__patch_jump_here(comp_ctx, pc_prevstmt); /* chain jumps for 'fall-through'
  47747. * after a case matches.
  47748. */
  47749. for (;;) {
  47750. tok = comp_ctx->curr_token.t;
  47751. if (tok == DUK_TOK_CASE || tok == DUK_TOK_DEFAULT ||
  47752. tok == DUK_TOK_RCURLY) {
  47753. break;
  47754. }
  47755. num_stmts++;
  47756. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  47757. }
  47758. /* fall-through jump to next code of next case (backpatched) */
  47759. pc_prevstmt = duk__emit_jump_empty(comp_ctx);
  47760. /* XXX: would be nice to omit this jump when the jump is not
  47761. * reachable, at least in the obvious cases (such as the case
  47762. * ending with a 'break'.
  47763. *
  47764. * Perhaps duk__parse_stmt() could provide some info on whether
  47765. * the statement is a "dead end"?
  47766. *
  47767. * If implemented, just set pc_prevstmt to -1 when not needed.
  47768. */
  47769. }
  47770. DUK_ASSERT(comp_ctx->curr_token.t == DUK_TOK_RCURLY);
  47771. duk__advance(comp_ctx);
  47772. /* default case control flow patchup; note that if pc_prevcase < 0
  47773. * (i.e. no case clauses), control enters default case automatically.
  47774. */
  47775. if (pc_default >= 0) {
  47776. /* default case exists: go there if no case matches */
  47777. duk__patch_jump(comp_ctx, pc_prevcase, pc_default);
  47778. } else {
  47779. /* default case does not exist, or no statements present
  47780. * after default case: finish case evaluation
  47781. */
  47782. duk__patch_jump_here(comp_ctx, pc_prevcase);
  47783. }
  47784. /* fall-through control flow patchup; note that pc_prevstmt may be
  47785. * < 0 (i.e. no case clauses), in which case this is a no-op.
  47786. */
  47787. duk__patch_jump_here(comp_ctx, pc_prevstmt);
  47788. /* continue jump not patched, an INVALID opcode remains there */
  47789. duk__patch_jump_here(comp_ctx, pc_label_site + 1); /* break jump */
  47790. /* Note: 'fast' breaks will jump to pc_label_site + 1, which will
  47791. * then jump here. The double jump will be eliminated by a
  47792. * peephole pass, resulting in an optimal jump here. The label
  47793. * site jumps will remain in bytecode and will waste code size.
  47794. */
  47795. return;
  47796. syntax_error:
  47797. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_SWITCH);
  47798. }
  47799. DUK_LOCAL void duk__parse_if_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  47800. duk_reg_t temp_reset;
  47801. duk_regconst_t rc_cond;
  47802. duk_int_t pc_jump_false;
  47803. DUK_DDD(DUK_DDDPRINT("begin parsing if statement"));
  47804. temp_reset = DUK__GETTEMP(comp_ctx);
  47805. duk__advance(comp_ctx); /* eat 'if' */
  47806. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  47807. rc_cond = duk__exprtop_toregconst(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  47808. duk__emit_if_true_skip(comp_ctx, rc_cond);
  47809. pc_jump_false = duk__emit_jump_empty(comp_ctx); /* jump to end or else part */
  47810. DUK__SETTEMP(comp_ctx, temp_reset);
  47811. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  47812. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  47813. /* The 'else' ambiguity is resolved by 'else' binding to the innermost
  47814. * construct, so greedy matching is correct here.
  47815. */
  47816. if (comp_ctx->curr_token.t == DUK_TOK_ELSE) {
  47817. duk_int_t pc_jump_end;
  47818. DUK_DDD(DUK_DDDPRINT("if has else part"));
  47819. duk__advance(comp_ctx);
  47820. pc_jump_end = duk__emit_jump_empty(comp_ctx); /* jump from true part to end */
  47821. duk__patch_jump_here(comp_ctx, pc_jump_false);
  47822. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  47823. duk__patch_jump_here(comp_ctx, pc_jump_end);
  47824. } else {
  47825. DUK_DDD(DUK_DDDPRINT("if does not have else part"));
  47826. duk__patch_jump_here(comp_ctx, pc_jump_false);
  47827. }
  47828. DUK_DDD(DUK_DDDPRINT("end parsing if statement"));
  47829. }
  47830. DUK_LOCAL void duk__parse_do_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site) {
  47831. duk_regconst_t rc_cond;
  47832. duk_int_t pc_start;
  47833. DUK_DDD(DUK_DDDPRINT("begin parsing do statement"));
  47834. duk__advance(comp_ctx); /* eat 'do' */
  47835. pc_start = duk__get_current_pc(comp_ctx);
  47836. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  47837. duk__patch_jump_here(comp_ctx, pc_label_site + 2); /* continue jump */
  47838. duk__advance_expect(comp_ctx, DUK_TOK_WHILE);
  47839. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  47840. rc_cond = duk__exprtop_toregconst(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  47841. duk__emit_if_false_skip(comp_ctx, rc_cond);
  47842. duk__emit_jump(comp_ctx, pc_start);
  47843. /* no need to reset temps, as we're finished emitting code */
  47844. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  47845. duk__patch_jump_here(comp_ctx, pc_label_site + 1); /* break jump */
  47846. DUK_DDD(DUK_DDDPRINT("end parsing do statement"));
  47847. }
  47848. DUK_LOCAL void duk__parse_while_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_int_t pc_label_site) {
  47849. duk_reg_t temp_reset;
  47850. duk_regconst_t rc_cond;
  47851. duk_int_t pc_start;
  47852. duk_int_t pc_jump_false;
  47853. DUK_DDD(DUK_DDDPRINT("begin parsing while statement"));
  47854. temp_reset = DUK__GETTEMP(comp_ctx);
  47855. duk__advance(comp_ctx); /* eat 'while' */
  47856. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  47857. pc_start = duk__get_current_pc(comp_ctx);
  47858. duk__patch_jump_here(comp_ctx, pc_label_site + 2); /* continue jump */
  47859. rc_cond = duk__exprtop_toregconst(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  47860. duk__emit_if_true_skip(comp_ctx, rc_cond);
  47861. pc_jump_false = duk__emit_jump_empty(comp_ctx);
  47862. DUK__SETTEMP(comp_ctx, temp_reset);
  47863. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  47864. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  47865. duk__emit_jump(comp_ctx, pc_start);
  47866. duk__patch_jump_here(comp_ctx, pc_jump_false);
  47867. duk__patch_jump_here(comp_ctx, pc_label_site + 1); /* break jump */
  47868. DUK_DDD(DUK_DDDPRINT("end parsing while statement"));
  47869. }
  47870. DUK_LOCAL void duk__parse_break_or_continue_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  47871. duk_hthread *thr = comp_ctx->thr;
  47872. duk_bool_t is_break = (comp_ctx->curr_token.t == DUK_TOK_BREAK);
  47873. duk_int_t label_id;
  47874. duk_int_t label_catch_depth;
  47875. duk_int_t label_pc; /* points to LABEL; pc+1 = jump site for break; pc+2 = jump site for continue */
  47876. duk_bool_t label_is_closest;
  47877. DUK_UNREF(res);
  47878. duk__advance(comp_ctx); /* eat 'break' or 'continue' */
  47879. if (comp_ctx->curr_token.t == DUK_TOK_SEMICOLON || /* explicit semi follows */
  47880. comp_ctx->curr_token.lineterm || /* automatic semi will be inserted */
  47881. comp_ctx->curr_token.allow_auto_semi) { /* automatic semi will be inserted */
  47882. /* break/continue without label */
  47883. duk__lookup_active_label(comp_ctx, DUK_HTHREAD_STRING_EMPTY_STRING(thr), is_break, &label_id, &label_catch_depth, &label_pc, &label_is_closest);
  47884. } else if (comp_ctx->curr_token.t == DUK_TOK_IDENTIFIER) {
  47885. /* break/continue with label (label cannot be a reserved word, production is 'Identifier' */
  47886. DUK_ASSERT(comp_ctx->curr_token.str1 != NULL);
  47887. duk__lookup_active_label(comp_ctx, comp_ctx->curr_token.str1, is_break, &label_id, &label_catch_depth, &label_pc, &label_is_closest);
  47888. duk__advance(comp_ctx);
  47889. } else {
  47890. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_BREAK_CONT_LABEL);
  47891. }
  47892. /* Use a fast break/continue when possible. A fast break/continue is
  47893. * just a jump to the LABEL break/continue jump slot, which then jumps
  47894. * to an appropriate place (for break, going through ENDLABEL correctly).
  47895. * The peephole optimizer will optimize the jump to a direct one.
  47896. */
  47897. if (label_catch_depth == comp_ctx->curr_func.catch_depth &&
  47898. label_is_closest) {
  47899. DUK_DDD(DUK_DDDPRINT("break/continue: is_break=%ld, label_id=%ld, label_is_closest=%ld, "
  47900. "label_catch_depth=%ld, catch_depth=%ld "
  47901. "-> use fast variant (direct jump)",
  47902. (long) is_break, (long) label_id, (long) label_is_closest,
  47903. (long) label_catch_depth, (long) comp_ctx->curr_func.catch_depth));
  47904. duk__emit_jump(comp_ctx, label_pc + (is_break ? 1 : 2));
  47905. } else {
  47906. DUK_DDD(DUK_DDDPRINT("break/continue: is_break=%ld, label_id=%ld, label_is_closest=%ld, "
  47907. "label_catch_depth=%ld, catch_depth=%ld "
  47908. "-> use slow variant (longjmp)",
  47909. (long) is_break, (long) label_id, (long) label_is_closest,
  47910. (long) label_catch_depth, (long) comp_ctx->curr_func.catch_depth));
  47911. duk__emit_extraop_bc(comp_ctx,
  47912. is_break ? DUK_EXTRAOP_BREAK : DUK_EXTRAOP_CONTINUE,
  47913. (duk_regconst_t) label_id);
  47914. }
  47915. }
  47916. DUK_LOCAL void duk__parse_return_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  47917. duk_hthread *thr = comp_ctx->thr;
  47918. duk_regconst_t rc_val;
  47919. duk_small_uint_t ret_flags;
  47920. duk__advance(comp_ctx); /* eat 'return' */
  47921. /* A 'return' statement is only allowed inside an actual function body,
  47922. * not as part of eval or global code.
  47923. */
  47924. if (!comp_ctx->curr_func.is_function) {
  47925. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_RETURN);
  47926. }
  47927. /* Use a fast return when possible. A fast return does not cause a longjmp()
  47928. * unnecessarily. A fast return can be done when no TCF catchers are active
  47929. * (this includes 'try' and 'with' statements). Active label catches do not
  47930. * prevent a fast return; they're unwound on return automatically.
  47931. */
  47932. ret_flags = 0;
  47933. if (comp_ctx->curr_token.t == DUK_TOK_SEMICOLON || /* explicit semi follows */
  47934. comp_ctx->curr_token.lineterm || /* automatic semi will be inserted */
  47935. comp_ctx->curr_token.allow_auto_semi) { /* automatic semi will be inserted */
  47936. DUK_DDD(DUK_DDDPRINT("empty return value -> undefined"));
  47937. rc_val = 0;
  47938. } else {
  47939. duk_int_t pc_before_expr;
  47940. duk_int_t pc_after_expr;
  47941. DUK_DDD(DUK_DDDPRINT("return with a value"));
  47942. DUK_UNREF(pc_before_expr);
  47943. DUK_UNREF(pc_after_expr);
  47944. pc_before_expr = duk__get_current_pc(comp_ctx);
  47945. rc_val = duk__exprtop_toregconst(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  47946. pc_after_expr = duk__get_current_pc(comp_ctx);
  47947. /* Tail call check: if last opcode emitted was CALL(I), and
  47948. * the context allows it, change the CALL(I) to a tailcall.
  47949. * This doesn't guarantee that a tailcall will be allowed at
  47950. * runtime, so the RETURN must still be emitted. (Duktape
  47951. * 0.10.0 avoided this and simulated a RETURN if a tailcall
  47952. * couldn't be used at runtime; but this didn't work
  47953. * correctly with a thread yield/resume, see
  47954. * test-bug-tailcall-thread-yield-resume.js for discussion.)
  47955. *
  47956. * In addition to the last opcode being CALL, we also need to
  47957. * be sure that 'rc_val' is the result register of the CALL(I).
  47958. * For instance, for the expression 'return 0, (function ()
  47959. * { return 1; }), 2' the last opcode emitted is CALL (no
  47960. * bytecode is emitted for '2') but 'rc_val' indicates
  47961. * constant '2'. Similarly if '2' is replaced by a register
  47962. * bound variable, no opcodes are emitted but tailcall would
  47963. * be incorrect.
  47964. *
  47965. * This is tricky and easy to get wrong. It would be best to
  47966. * track enough expression metadata to check that 'rc_val' came
  47967. * from that last CALL instruction. We don't have that metadata
  47968. * now, so we check that 'rc_val' is a temporary register result
  47969. * (not a constant or a register bound variable). There should
  47970. * be no way currently for 'rc_val' to be a temporary for an
  47971. * expression following the CALL instruction without emitting
  47972. * some opcodes following the CALL. This proxy check is used
  47973. * below.
  47974. *
  47975. * See: test-bug-comma-expr-gh131.js.
  47976. *
  47977. * The non-standard 'caller' property disables tail calls
  47978. * because they pose some special cases which haven't been
  47979. * fixed yet.
  47980. */
  47981. #if defined(DUK_USE_TAILCALL)
  47982. if (comp_ctx->curr_func.catch_depth == 0 && /* no catchers */
  47983. pc_after_expr > pc_before_expr) { /* at least one opcode emitted */
  47984. duk_compiler_instr *instr;
  47985. duk_small_uint_t op;
  47986. instr = duk__get_instr_ptr(comp_ctx, pc_after_expr - 1);
  47987. DUK_ASSERT(instr != NULL);
  47988. op = (duk_small_uint_t) DUK_DEC_OP(instr->ins);
  47989. if ((op == DUK_OP_CALL || op == DUK_OP_CALLI) &&
  47990. DUK__ISTEMP(comp_ctx, rc_val) /* see above */) {
  47991. DUK_DDD(DUK_DDDPRINT("return statement detected a tail call opportunity: "
  47992. "catch depth is 0, duk__exprtop() emitted >= 1 instructions, "
  47993. "and last instruction is a CALL "
  47994. "-> set TAILCALL flag"));
  47995. /* Just flip the single bit. */
  47996. instr->ins |= DUK_ENC_OP_A_B_C(0, DUK_BC_CALL_FLAG_TAILCALL, 0, 0);
  47997. }
  47998. }
  47999. #endif /* DUK_USE_TAILCALL */
  48000. ret_flags = DUK_BC_RETURN_FLAG_HAVE_RETVAL;
  48001. }
  48002. /* XXX: For now, "fast returns" are disabled. The compiler doesn't track
  48003. * label site depth so when it emits a fast return, it doesn't know whether
  48004. * label sites exist or not. Label sites are emitted for e.g. for loops,
  48005. * so it's probably quite relevant to handle them in the executor's fast
  48006. * return handler.
  48007. */
  48008. #if 0
  48009. if (comp_ctx->curr_func.catch_depth == 0) {
  48010. DUK_DDD(DUK_DDDPRINT("fast return allowed -> use fast return"));
  48011. ret_flags |= DUK_BC_RETURN_FLAG_FAST;
  48012. } else {
  48013. DUK_DDD(DUK_DDDPRINT("fast return not allowed -> use slow return"));
  48014. }
  48015. #endif
  48016. duk__emit_a_b(comp_ctx,
  48017. DUK_OP_RETURN | DUK__EMIT_FLAG_NO_SHUFFLE_A,
  48018. (duk_regconst_t) ret_flags /*flags*/,
  48019. rc_val /*reg*/);
  48020. }
  48021. DUK_LOCAL void duk__parse_throw_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  48022. duk_reg_t reg_val;
  48023. duk__advance(comp_ctx); /* eat 'throw' */
  48024. /* Unlike break/continue, throw statement does not allow an empty value. */
  48025. if (comp_ctx->curr_token.lineterm) {
  48026. DUK_ERROR(comp_ctx->thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_THROW);
  48027. }
  48028. reg_val = duk__exprtop_toreg(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  48029. duk__emit_extraop_bc(comp_ctx,
  48030. DUK_EXTRAOP_THROW,
  48031. (duk_regconst_t) reg_val);
  48032. }
  48033. DUK_LOCAL void duk__parse_try_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  48034. duk_hthread *thr = comp_ctx->thr;
  48035. duk_context *ctx = (duk_context *) thr;
  48036. duk_reg_t reg_catch; /* reg_catch+0 and reg_catch+1 are reserved for TRYCATCH */
  48037. duk_regconst_t rc_varname = 0;
  48038. duk_small_uint_t trycatch_flags = 0;
  48039. duk_int_t pc_trycatch = -1;
  48040. duk_int_t pc_catch = -1;
  48041. duk_int_t pc_finally = -1;
  48042. DUK_UNREF(res);
  48043. /*
  48044. * See the following documentation for discussion:
  48045. *
  48046. * doc/execution.txt: control flow details
  48047. *
  48048. * Try, catch, and finally "parts" are Blocks, not Statements, so
  48049. * they must always be delimited by curly braces. This is unlike e.g.
  48050. * the if statement, which accepts any Statement. This eliminates any
  48051. * questions of matching parts of nested try statements. The Block
  48052. * parsing is implemented inline here (instead of calling out).
  48053. *
  48054. * Finally part has a 'let scoped' variable, which requires a few kinks
  48055. * here.
  48056. */
  48057. comp_ctx->curr_func.catch_depth++;
  48058. duk__advance(comp_ctx); /* eat 'try' */
  48059. reg_catch = DUK__ALLOCTEMPS(comp_ctx, 2);
  48060. pc_trycatch = duk__get_current_pc(comp_ctx);
  48061. duk__emit_invalid(comp_ctx); /* TRYCATCH, cannot emit now (not enough info) */
  48062. duk__emit_invalid(comp_ctx); /* jump for 'catch' case */
  48063. duk__emit_invalid(comp_ctx); /* jump for 'finally' case or end (if no finally) */
  48064. /* try part */
  48065. duk__advance_expect(comp_ctx, DUK_TOK_LCURLY);
  48066. duk__parse_stmts(comp_ctx, 0 /*allow_source_elem*/, 0 /*expect_eof*/);
  48067. /* the DUK_TOK_RCURLY is eaten by duk__parse_stmts() */
  48068. duk__emit_extraop_only(comp_ctx,
  48069. DUK_EXTRAOP_ENDTRY);
  48070. if (comp_ctx->curr_token.t == DUK_TOK_CATCH) {
  48071. /*
  48072. * The catch variable must be updated to reflect the new allocated
  48073. * register for the duration of the catch clause. We need to store
  48074. * and restore the original value for the varmap entry (if any).
  48075. */
  48076. /*
  48077. * Note: currently register bindings must be fixed for the entire
  48078. * function. So, even though the catch variable is in a register
  48079. * we know, we must use an explicit environment record and slow path
  48080. * accesses to read/write the catch binding to make closures created
  48081. * within the catch clause work correctly. This restriction should
  48082. * be fixable (at least in common cases) later.
  48083. *
  48084. * See: test-bug-catch-binding-2.js.
  48085. *
  48086. * XXX: improve to get fast path access to most catch clauses.
  48087. */
  48088. duk_hstring *h_var;
  48089. duk_int_t varmap_value; /* for storing/restoring the varmap binding for catch variable */
  48090. DUK_DDD(DUK_DDDPRINT("stack top at start of catch clause: %ld", (long) duk_get_top(ctx)));
  48091. trycatch_flags |= DUK_BC_TRYCATCH_FLAG_HAVE_CATCH;
  48092. pc_catch = duk__get_current_pc(comp_ctx);
  48093. duk__advance(comp_ctx);
  48094. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  48095. if (comp_ctx->curr_token.t != DUK_TOK_IDENTIFIER) {
  48096. /* Identifier, i.e. don't allow reserved words */
  48097. goto syntax_error;
  48098. }
  48099. h_var = comp_ctx->curr_token.str1;
  48100. DUK_ASSERT(h_var != NULL);
  48101. duk_push_hstring(ctx, h_var); /* keep in on valstack, use borrowed ref below */
  48102. if (comp_ctx->curr_func.is_strict &&
  48103. ((h_var == DUK_HTHREAD_STRING_EVAL(thr)) ||
  48104. (h_var == DUK_HTHREAD_STRING_LC_ARGUMENTS(thr)))) {
  48105. DUK_DDD(DUK_DDDPRINT("catch identifier 'eval' or 'arguments' in strict mode -> SyntaxError"));
  48106. goto syntax_error;
  48107. }
  48108. duk_dup_top(ctx);
  48109. rc_varname = duk__getconst(comp_ctx);
  48110. DUK_DDD(DUK_DDDPRINT("catch clause, rc_varname=0x%08lx (%ld)",
  48111. (unsigned long) rc_varname, (long) rc_varname));
  48112. duk__advance(comp_ctx);
  48113. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  48114. duk__advance_expect(comp_ctx, DUK_TOK_LCURLY);
  48115. DUK_DDD(DUK_DDDPRINT("varmap before modifying for catch clause: %!iT",
  48116. (duk_tval *) duk_get_tval(ctx, comp_ctx->curr_func.varmap_idx)));
  48117. duk_dup_top(ctx);
  48118. duk_get_prop(ctx, comp_ctx->curr_func.varmap_idx);
  48119. if (duk_is_undefined(ctx, -1)) {
  48120. varmap_value = -2;
  48121. } else if (duk_is_null(ctx, -1)) {
  48122. varmap_value = -1;
  48123. } else {
  48124. DUK_ASSERT(duk_is_number(ctx, -1));
  48125. varmap_value = duk_get_int(ctx, -1);
  48126. DUK_ASSERT(varmap_value >= 0);
  48127. }
  48128. duk_pop(ctx);
  48129. #if 0
  48130. /* It'd be nice to do something like this - but it doesn't
  48131. * work for closures created inside the catch clause.
  48132. */
  48133. duk_dup_top(ctx);
  48134. duk_push_int(ctx, (duk_int_t) (reg_catch + 0));
  48135. duk_put_prop(ctx, comp_ctx->curr_func.varmap_idx);
  48136. #endif
  48137. duk_dup_top(ctx);
  48138. duk_push_null(ctx);
  48139. duk_put_prop(ctx, comp_ctx->curr_func.varmap_idx);
  48140. duk__emit_a_bc(comp_ctx,
  48141. DUK_OP_PUTVAR | DUK__EMIT_FLAG_A_IS_SOURCE,
  48142. (duk_regconst_t) (reg_catch + 0) /*value*/,
  48143. rc_varname /*varname*/);
  48144. DUK_DDD(DUK_DDDPRINT("varmap before parsing catch clause: %!iT",
  48145. (duk_tval *) duk_get_tval(ctx, comp_ctx->curr_func.varmap_idx)));
  48146. duk__parse_stmts(comp_ctx, 0 /*allow_source_elem*/, 0 /*expect_eof*/);
  48147. /* the DUK_TOK_RCURLY is eaten by duk__parse_stmts() */
  48148. if (varmap_value == -2) {
  48149. /* not present */
  48150. duk_del_prop(ctx, comp_ctx->curr_func.varmap_idx);
  48151. } else {
  48152. if (varmap_value == -1) {
  48153. duk_push_null(ctx);
  48154. } else {
  48155. DUK_ASSERT(varmap_value >= 0);
  48156. duk_push_int(ctx, varmap_value);
  48157. }
  48158. duk_put_prop(ctx, comp_ctx->curr_func.varmap_idx);
  48159. }
  48160. /* varname is popped by above code */
  48161. DUK_DDD(DUK_DDDPRINT("varmap after restore catch clause: %!iT",
  48162. (duk_tval *) duk_get_tval(ctx, comp_ctx->curr_func.varmap_idx)));
  48163. duk__emit_extraop_only(comp_ctx,
  48164. DUK_EXTRAOP_ENDCATCH);
  48165. /*
  48166. * XXX: for now, indicate that an expensive catch binding
  48167. * declarative environment is always needed. If we don't
  48168. * need it, we don't need the const_varname either.
  48169. */
  48170. trycatch_flags |= DUK_BC_TRYCATCH_FLAG_CATCH_BINDING;
  48171. DUK_DDD(DUK_DDDPRINT("stack top at end of catch clause: %ld", (long) duk_get_top(ctx)));
  48172. }
  48173. if (comp_ctx->curr_token.t == DUK_TOK_FINALLY) {
  48174. trycatch_flags |= DUK_BC_TRYCATCH_FLAG_HAVE_FINALLY;
  48175. pc_finally = duk__get_current_pc(comp_ctx);
  48176. duk__advance(comp_ctx);
  48177. duk__advance_expect(comp_ctx, DUK_TOK_LCURLY);
  48178. duk__parse_stmts(comp_ctx, 0 /*allow_source_elem*/, 0 /*expect_eof*/);
  48179. /* the DUK_TOK_RCURLY is eaten by duk__parse_stmts() */
  48180. duk__emit_extraop_b(comp_ctx,
  48181. DUK_EXTRAOP_ENDFIN,
  48182. reg_catch); /* rethrow */
  48183. }
  48184. if (!(trycatch_flags & DUK_BC_TRYCATCH_FLAG_HAVE_CATCH) &&
  48185. !(trycatch_flags & DUK_BC_TRYCATCH_FLAG_HAVE_FINALLY)) {
  48186. /* must have catch and/or finally */
  48187. goto syntax_error;
  48188. }
  48189. duk__patch_trycatch(comp_ctx,
  48190. pc_trycatch,
  48191. reg_catch,
  48192. rc_varname,
  48193. trycatch_flags);
  48194. if (trycatch_flags & DUK_BC_TRYCATCH_FLAG_HAVE_CATCH) {
  48195. DUK_ASSERT(pc_catch >= 0);
  48196. duk__patch_jump(comp_ctx, pc_trycatch + 1, pc_catch);
  48197. }
  48198. if (trycatch_flags & DUK_BC_TRYCATCH_FLAG_HAVE_FINALLY) {
  48199. DUK_ASSERT(pc_finally >= 0);
  48200. duk__patch_jump(comp_ctx, pc_trycatch + 2, pc_finally);
  48201. } else {
  48202. /* without finally, the second jump slot is used to jump to end of stmt */
  48203. duk__patch_jump_here(comp_ctx, pc_trycatch + 2);
  48204. }
  48205. comp_ctx->curr_func.catch_depth--;
  48206. return;
  48207. syntax_error:
  48208. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_TRY);
  48209. }
  48210. DUK_LOCAL void duk__parse_with_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res) {
  48211. duk_int_t pc_trycatch;
  48212. duk_int_t pc_finished;
  48213. duk_reg_t reg_catch;
  48214. duk_regconst_t rc_target;
  48215. duk_small_uint_t trycatch_flags;
  48216. if (comp_ctx->curr_func.is_strict) {
  48217. DUK_ERROR(comp_ctx->thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_WITH_IN_STRICT_MODE);
  48218. }
  48219. comp_ctx->curr_func.catch_depth++;
  48220. duk__advance(comp_ctx); /* eat 'with' */
  48221. reg_catch = DUK__ALLOCTEMPS(comp_ctx, 2);
  48222. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  48223. rc_target = duk__exprtop_toregconst(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  48224. duk__advance_expect(comp_ctx, DUK_TOK_RPAREN);
  48225. /* XXX: the trycatch shuffle flags are now very limiting and a fix
  48226. * is needed to allow trycatch to work in functions with a very large
  48227. * number of temporaries or constants.
  48228. */
  48229. pc_trycatch = duk__get_current_pc(comp_ctx);
  48230. trycatch_flags = DUK_BC_TRYCATCH_FLAG_WITH_BINDING;
  48231. duk__emit_a_b_c(comp_ctx,
  48232. DUK_OP_TRYCATCH | DUK__EMIT_FLAG_NO_SHUFFLE_A
  48233. | DUK__EMIT_FLAG_NO_SHUFFLE_B
  48234. | DUK__EMIT_FLAG_NO_SHUFFLE_C,
  48235. (duk_regconst_t) trycatch_flags /*a*/,
  48236. (duk_regconst_t) reg_catch /*b*/,
  48237. rc_target /*c*/);
  48238. duk__emit_invalid(comp_ctx); /* catch jump */
  48239. duk__emit_invalid(comp_ctx); /* finished jump */
  48240. duk__parse_stmt(comp_ctx, res, 0 /*allow_source_elem*/);
  48241. duk__emit_extraop_only(comp_ctx,
  48242. DUK_EXTRAOP_ENDTRY);
  48243. pc_finished = duk__get_current_pc(comp_ctx);
  48244. duk__patch_jump(comp_ctx, pc_trycatch + 2, pc_finished);
  48245. comp_ctx->curr_func.catch_depth--;
  48246. }
  48247. DUK_LOCAL duk_int_t duk__stmt_label_site(duk_compiler_ctx *comp_ctx, duk_int_t label_id) {
  48248. /* if a site already exists, nop: max one label site per statement */
  48249. if (label_id >= 0) {
  48250. return label_id;
  48251. }
  48252. label_id = comp_ctx->curr_func.label_next++;
  48253. DUK_DDD(DUK_DDDPRINT("allocated new label id for label site: %ld", (long) label_id));
  48254. duk__emit_extraop_bc(comp_ctx,
  48255. DUK_EXTRAOP_LABEL,
  48256. (duk_regconst_t) label_id);
  48257. duk__emit_invalid(comp_ctx);
  48258. duk__emit_invalid(comp_ctx);
  48259. return label_id;
  48260. }
  48261. /* Parse a single statement.
  48262. *
  48263. * Creates a label site (with an empty label) automatically for iteration
  48264. * statements. Also "peels off" any label statements for explicit labels.
  48265. */
  48266. DUK_LOCAL void duk__parse_stmt(duk_compiler_ctx *comp_ctx, duk_ivalue *res, duk_bool_t allow_source_elem) {
  48267. duk_hthread *thr = comp_ctx->thr;
  48268. duk_context *ctx = (duk_context *) thr;
  48269. duk_bool_t dir_prol_at_entry; /* directive prologue status at entry */
  48270. duk_reg_t temp_at_entry;
  48271. duk_uarridx_t labels_len_at_entry;
  48272. duk_int_t pc_at_entry; /* assumed to also be PC of "LABEL" */
  48273. duk_int_t stmt_id;
  48274. duk_small_uint_t stmt_flags = 0;
  48275. duk_int_t label_id = -1;
  48276. duk_small_uint_t tok;
  48277. DUK__RECURSION_INCREASE(comp_ctx, thr);
  48278. temp_at_entry = DUK__GETTEMP(comp_ctx);
  48279. pc_at_entry = duk__get_current_pc(comp_ctx);
  48280. labels_len_at_entry = (duk_uarridx_t) duk_get_length(ctx, comp_ctx->curr_func.labelnames_idx);
  48281. stmt_id = comp_ctx->curr_func.stmt_next++;
  48282. dir_prol_at_entry = comp_ctx->curr_func.in_directive_prologue;
  48283. DUK_UNREF(stmt_id);
  48284. DUK_DDD(DUK_DDDPRINT("parsing a statement, stmt_id=%ld, temp_at_entry=%ld, labels_len_at_entry=%ld, "
  48285. "is_strict=%ld, in_directive_prologue=%ld, catch_depth=%ld",
  48286. (long) stmt_id, (long) temp_at_entry, (long) labels_len_at_entry,
  48287. (long) comp_ctx->curr_func.is_strict, (long) comp_ctx->curr_func.in_directive_prologue,
  48288. (long) comp_ctx->curr_func.catch_depth));
  48289. /* The directive prologue flag is cleared by default so that it is
  48290. * unset for any recursive statement parsing. It is only "revived"
  48291. * if a directive is detected. (We could also make directives only
  48292. * allowed if 'allow_source_elem' was true.)
  48293. */
  48294. comp_ctx->curr_func.in_directive_prologue = 0;
  48295. retry_parse:
  48296. DUK_DDD(DUK_DDDPRINT("try stmt parse, stmt_id=%ld, label_id=%ld, allow_source_elem=%ld, catch_depth=%ld",
  48297. (long) stmt_id, (long) label_id, (long) allow_source_elem,
  48298. (long) comp_ctx->curr_func.catch_depth));
  48299. /*
  48300. * Detect iteration statements; if encountered, establish an
  48301. * empty label.
  48302. */
  48303. tok = comp_ctx->curr_token.t;
  48304. if (tok == DUK_TOK_FOR || tok == DUK_TOK_DO || tok == DUK_TOK_WHILE ||
  48305. tok == DUK_TOK_SWITCH) {
  48306. DUK_DDD(DUK_DDDPRINT("iteration/switch statement -> add empty label"));
  48307. label_id = duk__stmt_label_site(comp_ctx, label_id);
  48308. duk__add_label(comp_ctx,
  48309. DUK_HTHREAD_STRING_EMPTY_STRING(thr),
  48310. pc_at_entry /*pc_label*/,
  48311. label_id);
  48312. }
  48313. /*
  48314. * Main switch for statement / source element type.
  48315. */
  48316. switch (comp_ctx->curr_token.t) {
  48317. case DUK_TOK_FUNCTION: {
  48318. /*
  48319. * Function declaration, function expression, or (non-standard)
  48320. * function statement.
  48321. *
  48322. * The E5 specification only allows function declarations at
  48323. * the top level (in "source elements"). An ExpressionStatement
  48324. * is explicitly not allowed to begin with a "function" keyword
  48325. * (E5 Section 12.4). Hence any non-error semantics for such
  48326. * non-top-level statements are non-standard. Duktape semantics
  48327. * for function statements are modelled after V8, see
  48328. * test-dev-func-decl-outside-top.js.
  48329. */
  48330. #if defined(DUK_USE_NONSTD_FUNC_STMT)
  48331. /* Lenient: allow function declarations outside top level in
  48332. * non-strict mode but reject them in strict mode.
  48333. */
  48334. if (allow_source_elem || !comp_ctx->curr_func.is_strict)
  48335. #else /* DUK_USE_NONSTD_FUNC_STMT */
  48336. /* Strict: never allow function declarations outside top level. */
  48337. if (allow_source_elem)
  48338. #endif /* DUK_USE_NONSTD_FUNC_STMT */
  48339. {
  48340. /* FunctionDeclaration: not strictly a statement but handled as such.
  48341. *
  48342. * O(depth^2) parse count for inner functions is handled by recording a
  48343. * lexer offset on the first compilation pass, so that the function can
  48344. * be efficiently skipped on the second pass. This is encapsulated into
  48345. * duk__parse_func_like_fnum().
  48346. */
  48347. duk_int_t fnum;
  48348. DUK_DDD(DUK_DDDPRINT("function declaration statement"));
  48349. duk__advance(comp_ctx); /* eat 'function' */
  48350. fnum = duk__parse_func_like_fnum(comp_ctx, 1 /*is_decl*/, 0 /*is_setget*/);
  48351. if (comp_ctx->curr_func.in_scanning) {
  48352. duk_uarridx_t n;
  48353. duk_hstring *h_funcname;
  48354. duk_get_prop_index(ctx, comp_ctx->curr_func.funcs_idx, fnum * 3);
  48355. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_NAME); /* -> [ ... func name ] */
  48356. h_funcname = duk_get_hstring(ctx, -1);
  48357. DUK_ASSERT(h_funcname != NULL);
  48358. DUK_DDD(DUK_DDDPRINT("register function declaration %!O in pass 1, fnum %ld",
  48359. (duk_heaphdr *) h_funcname, (long) fnum));
  48360. n = (duk_uarridx_t) duk_get_length(ctx, comp_ctx->curr_func.decls_idx);
  48361. duk_push_hstring(ctx, h_funcname);
  48362. duk_put_prop_index(ctx, comp_ctx->curr_func.decls_idx, n);
  48363. duk_push_int(ctx, (duk_int_t) (DUK_DECL_TYPE_FUNC + (fnum << 8)));
  48364. duk_put_prop_index(ctx, comp_ctx->curr_func.decls_idx, n + 1);
  48365. duk_pop_n(ctx, 2);
  48366. }
  48367. /* no statement value (unlike function expression) */
  48368. stmt_flags = 0;
  48369. break;
  48370. } else {
  48371. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_FUNC_STMT_NOT_ALLOWED);
  48372. }
  48373. break;
  48374. }
  48375. case DUK_TOK_LCURLY: {
  48376. DUK_DDD(DUK_DDDPRINT("block statement"));
  48377. duk__advance(comp_ctx);
  48378. duk__parse_stmts(comp_ctx, 0 /*allow_source_elem*/, 0 /*expect_eof*/);
  48379. /* the DUK_TOK_RCURLY is eaten by duk__parse_stmts() */
  48380. if (label_id >= 0) {
  48381. duk__patch_jump_here(comp_ctx, pc_at_entry + 1); /* break jump */
  48382. }
  48383. stmt_flags = 0;
  48384. break;
  48385. }
  48386. case DUK_TOK_VAR: {
  48387. DUK_DDD(DUK_DDDPRINT("variable declaration statement"));
  48388. duk__parse_var_stmt(comp_ctx, res);
  48389. stmt_flags = DUK__HAS_TERM;
  48390. break;
  48391. }
  48392. case DUK_TOK_SEMICOLON: {
  48393. /* empty statement with an explicit semicolon */
  48394. DUK_DDD(DUK_DDDPRINT("empty statement"));
  48395. stmt_flags = DUK__HAS_TERM;
  48396. break;
  48397. }
  48398. case DUK_TOK_IF: {
  48399. DUK_DDD(DUK_DDDPRINT("if statement"));
  48400. duk__parse_if_stmt(comp_ctx, res);
  48401. if (label_id >= 0) {
  48402. duk__patch_jump_here(comp_ctx, pc_at_entry + 1); /* break jump */
  48403. }
  48404. stmt_flags = 0;
  48405. break;
  48406. }
  48407. case DUK_TOK_DO: {
  48408. /*
  48409. * Do-while statement is mostly trivial, but there is special
  48410. * handling for automatic semicolon handling (triggered by the
  48411. * DUK__ALLOW_AUTO_SEMI_ALWAYS) flag related to a bug filed at:
  48412. *
  48413. * https://bugs.ecmascript.org/show_bug.cgi?id=8
  48414. *
  48415. * See doc/compiler.txt for details.
  48416. */
  48417. DUK_DDD(DUK_DDDPRINT("do statement"));
  48418. DUK_ASSERT(label_id >= 0);
  48419. duk__update_label_flags(comp_ctx,
  48420. label_id,
  48421. DUK_LABEL_FLAG_ALLOW_BREAK | DUK_LABEL_FLAG_ALLOW_CONTINUE);
  48422. duk__parse_do_stmt(comp_ctx, res, pc_at_entry);
  48423. stmt_flags = DUK__HAS_TERM | DUK__ALLOW_AUTO_SEMI_ALWAYS; /* DUK__ALLOW_AUTO_SEMI_ALWAYS workaround */
  48424. break;
  48425. }
  48426. case DUK_TOK_WHILE: {
  48427. DUK_DDD(DUK_DDDPRINT("while statement"));
  48428. DUK_ASSERT(label_id >= 0);
  48429. duk__update_label_flags(comp_ctx,
  48430. label_id,
  48431. DUK_LABEL_FLAG_ALLOW_BREAK | DUK_LABEL_FLAG_ALLOW_CONTINUE);
  48432. duk__parse_while_stmt(comp_ctx, res, pc_at_entry);
  48433. stmt_flags = 0;
  48434. break;
  48435. }
  48436. case DUK_TOK_FOR: {
  48437. /*
  48438. * For/for-in statement is complicated to parse because
  48439. * determining the statement type (three-part for vs. a
  48440. * for-in) requires potential backtracking.
  48441. *
  48442. * See the helper for the messy stuff.
  48443. */
  48444. DUK_DDD(DUK_DDDPRINT("for/for-in statement"));
  48445. DUK_ASSERT(label_id >= 0);
  48446. duk__update_label_flags(comp_ctx,
  48447. label_id,
  48448. DUK_LABEL_FLAG_ALLOW_BREAK | DUK_LABEL_FLAG_ALLOW_CONTINUE);
  48449. duk__parse_for_stmt(comp_ctx, res, pc_at_entry);
  48450. stmt_flags = 0;
  48451. break;
  48452. }
  48453. case DUK_TOK_CONTINUE:
  48454. case DUK_TOK_BREAK: {
  48455. DUK_DDD(DUK_DDDPRINT("break/continue statement"));
  48456. duk__parse_break_or_continue_stmt(comp_ctx, res);
  48457. stmt_flags = DUK__HAS_TERM | DUK__IS_TERMINAL;
  48458. break;
  48459. }
  48460. case DUK_TOK_RETURN: {
  48461. DUK_DDD(DUK_DDDPRINT("return statement"));
  48462. duk__parse_return_stmt(comp_ctx, res);
  48463. stmt_flags = DUK__HAS_TERM | DUK__IS_TERMINAL;
  48464. break;
  48465. }
  48466. case DUK_TOK_WITH: {
  48467. DUK_DDD(DUK_DDDPRINT("with statement"));
  48468. comp_ctx->curr_func.with_depth++;
  48469. duk__parse_with_stmt(comp_ctx, res);
  48470. if (label_id >= 0) {
  48471. duk__patch_jump_here(comp_ctx, pc_at_entry + 1); /* break jump */
  48472. }
  48473. comp_ctx->curr_func.with_depth--;
  48474. stmt_flags = 0;
  48475. break;
  48476. }
  48477. case DUK_TOK_SWITCH: {
  48478. /*
  48479. * The switch statement is pretty messy to compile.
  48480. * See the helper for details.
  48481. */
  48482. DUK_DDD(DUK_DDDPRINT("switch statement"));
  48483. DUK_ASSERT(label_id >= 0);
  48484. duk__update_label_flags(comp_ctx,
  48485. label_id,
  48486. DUK_LABEL_FLAG_ALLOW_BREAK); /* don't allow continue */
  48487. duk__parse_switch_stmt(comp_ctx, res, pc_at_entry);
  48488. stmt_flags = 0;
  48489. break;
  48490. }
  48491. case DUK_TOK_THROW: {
  48492. DUK_DDD(DUK_DDDPRINT("throw statement"));
  48493. duk__parse_throw_stmt(comp_ctx, res);
  48494. stmt_flags = DUK__HAS_TERM | DUK__IS_TERMINAL;
  48495. break;
  48496. }
  48497. case DUK_TOK_TRY: {
  48498. DUK_DDD(DUK_DDDPRINT("try statement"));
  48499. duk__parse_try_stmt(comp_ctx, res);
  48500. stmt_flags = 0;
  48501. break;
  48502. }
  48503. case DUK_TOK_DEBUGGER: {
  48504. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  48505. DUK_DDD(DUK_DDDPRINT("debugger statement: debugging enabled, emit debugger opcode"));
  48506. duk__emit_extraop_only(comp_ctx, DUK_EXTRAOP_DEBUGGER);
  48507. #else
  48508. DUK_DDD(DUK_DDDPRINT("debugger statement: ignored"));
  48509. #endif
  48510. duk__advance(comp_ctx);
  48511. stmt_flags = DUK__HAS_TERM;
  48512. break;
  48513. }
  48514. default: {
  48515. /*
  48516. * Else, must be one of:
  48517. * - ExpressionStatement, possibly a directive (String)
  48518. * - LabelledStatement (Identifier followed by ':')
  48519. *
  48520. * Expressions beginning with 'function' keyword are covered by a case
  48521. * above (such expressions are not allowed in standard E5 anyway).
  48522. * Also expressions starting with '{' are interpreted as block
  48523. * statements. See E5 Section 12.4.
  48524. *
  48525. * Directive detection is tricky; see E5 Section 14.1 on directive
  48526. * prologue. A directive is an expression statement with a single
  48527. * string literal and an explicit or automatic semicolon. Escape
  48528. * characters are significant and no parens etc are allowed:
  48529. *
  48530. * 'use strict'; // valid 'use strict' directive
  48531. * 'use\u0020strict'; // valid directive, not a 'use strict' directive
  48532. * ('use strict'); // not a valid directive
  48533. *
  48534. * The expression is determined to consist of a single string literal
  48535. * based on duk__expr_nud() and duk__expr_led() call counts. The string literal
  48536. * of a 'use strict' directive is determined to lack any escapes based
  48537. * num_escapes count from the lexer. Note that other directives may be
  48538. * allowed to contain escapes, so a directive with escapes does not
  48539. * terminate a directive prologue.
  48540. *
  48541. * We rely on the fact that the expression parser will not emit any
  48542. * code for a single token expression. However, it will generate an
  48543. * intermediate value which we will then successfully ignore.
  48544. *
  48545. * A similar approach is used for labels.
  48546. */
  48547. duk_bool_t single_token;
  48548. DUK_DDD(DUK_DDDPRINT("expression statement"));
  48549. duk__exprtop(comp_ctx, res, DUK__BP_FOR_EXPR /*rbp_flags*/);
  48550. single_token = (comp_ctx->curr_func.nud_count == 1 && /* one token */
  48551. comp_ctx->curr_func.led_count == 0); /* no operators */
  48552. if (single_token &&
  48553. comp_ctx->prev_token.t == DUK_TOK_IDENTIFIER &&
  48554. comp_ctx->curr_token.t == DUK_TOK_COLON) {
  48555. /*
  48556. * Detected label
  48557. */
  48558. duk_hstring *h_lab;
  48559. /* expected ival */
  48560. DUK_ASSERT(res->t == DUK_IVAL_VAR);
  48561. DUK_ASSERT(res->x1.t == DUK_ISPEC_VALUE);
  48562. DUK_ASSERT(DUK_TVAL_IS_STRING(duk_get_tval(ctx, res->x1.valstack_idx)));
  48563. h_lab = comp_ctx->prev_token.str1;
  48564. DUK_ASSERT(h_lab != NULL);
  48565. DUK_DDD(DUK_DDDPRINT("explicit label site for label '%!O'",
  48566. (duk_heaphdr *) h_lab));
  48567. duk__advance(comp_ctx); /* eat colon */
  48568. label_id = duk__stmt_label_site(comp_ctx, label_id);
  48569. duk__add_label(comp_ctx,
  48570. h_lab,
  48571. pc_at_entry /*pc_label*/,
  48572. label_id);
  48573. /* a statement following a label cannot be a source element
  48574. * (a function declaration).
  48575. */
  48576. allow_source_elem = 0;
  48577. DUK_DDD(DUK_DDDPRINT("label handled, retry statement parsing"));
  48578. goto retry_parse;
  48579. }
  48580. stmt_flags = 0;
  48581. if (dir_prol_at_entry && /* still in prologue */
  48582. single_token && /* single string token */
  48583. comp_ctx->prev_token.t == DUK_TOK_STRING) {
  48584. /*
  48585. * Detected a directive
  48586. */
  48587. duk_hstring *h_dir;
  48588. /* expected ival */
  48589. DUK_ASSERT(res->t == DUK_IVAL_PLAIN);
  48590. DUK_ASSERT(res->x1.t == DUK_ISPEC_VALUE);
  48591. DUK_ASSERT(DUK_TVAL_IS_STRING(duk_get_tval(ctx, res->x1.valstack_idx)));
  48592. h_dir = comp_ctx->prev_token.str1;
  48593. DUK_ASSERT(h_dir != NULL);
  48594. DUK_DDD(DUK_DDDPRINT("potential directive: %!O", h_dir));
  48595. stmt_flags |= DUK__STILL_PROLOGUE;
  48596. /* Note: escaped characters differentiate directives */
  48597. if (comp_ctx->prev_token.num_escapes > 0) {
  48598. DUK_DDD(DUK_DDDPRINT("directive contains escapes: valid directive "
  48599. "but we ignore such directives"));
  48600. } else {
  48601. /*
  48602. * The length comparisons are present to handle
  48603. * strings like "use strict\u0000foo" as required.
  48604. */
  48605. if (DUK_HSTRING_GET_BYTELEN(h_dir) == 10 &&
  48606. DUK_STRNCMP((const char *) DUK_HSTRING_GET_DATA(h_dir), "use strict", 10) == 0) {
  48607. #if defined(DUK_USE_STRICT_DECL)
  48608. DUK_DDD(DUK_DDDPRINT("use strict directive detected: strict flag %ld -> %ld",
  48609. (long) comp_ctx->curr_func.is_strict, (long) 1));
  48610. comp_ctx->curr_func.is_strict = 1;
  48611. #else
  48612. DUK_DDD(DUK_DDDPRINT("use strict detected but strict declarations disabled, ignoring"));
  48613. #endif
  48614. } else if (DUK_HSTRING_GET_BYTELEN(h_dir) == 14 &&
  48615. DUK_STRNCMP((const char *) DUK_HSTRING_GET_DATA(h_dir), "use duk notail", 14) == 0) {
  48616. DUK_DDD(DUK_DDDPRINT("use duk notail directive detected: notail flag %ld -> %ld",
  48617. (long) comp_ctx->curr_func.is_notail, (long) 1));
  48618. comp_ctx->curr_func.is_notail = 1;
  48619. } else {
  48620. DUK_DD(DUK_DDPRINT("unknown directive: '%!O', ignoring but not terminating "
  48621. "directive prologue", (duk_hobject *) h_dir));
  48622. }
  48623. }
  48624. } else {
  48625. DUK_DDD(DUK_DDDPRINT("non-directive expression statement or no longer in prologue; "
  48626. "prologue terminated if still active"));
  48627. }
  48628. stmt_flags |= DUK__HAS_VAL | DUK__HAS_TERM;
  48629. }
  48630. } /* end switch (tok) */
  48631. /*
  48632. * Statement value handling.
  48633. *
  48634. * Global code and eval code has an implicit return value
  48635. * which comes from the last statement with a value
  48636. * (technically a non-"empty" continuation, which is
  48637. * different from an empty statement).
  48638. *
  48639. * Since we don't know whether a later statement will
  48640. * override the value of the current statement, we need
  48641. * to coerce the statement value to a register allocated
  48642. * for implicit return values. In other cases we need
  48643. * to coerce the statement value to a plain value to get
  48644. * any side effects out (consider e.g. "foo.bar;").
  48645. */
  48646. /* XXX: what about statements which leave a half-cooked value in 'res'
  48647. * but have no stmt value? Any such statements?
  48648. */
  48649. if (stmt_flags & DUK__HAS_VAL) {
  48650. duk_reg_t reg_stmt_value = comp_ctx->curr_func.reg_stmt_value;
  48651. if (reg_stmt_value >= 0) {
  48652. duk__ivalue_toforcedreg(comp_ctx, res, reg_stmt_value);
  48653. } else {
  48654. duk__ivalue_toplain_ignore(comp_ctx, res);
  48655. }
  48656. } else {
  48657. ;
  48658. }
  48659. /*
  48660. * Statement terminator check, including automatic semicolon
  48661. * handling. After this step, 'curr_tok' should be the first
  48662. * token after a possible statement terminator.
  48663. */
  48664. if (stmt_flags & DUK__HAS_TERM) {
  48665. if (comp_ctx->curr_token.t == DUK_TOK_SEMICOLON) {
  48666. DUK_DDD(DUK_DDDPRINT("explicit semicolon terminates statement"));
  48667. duk__advance(comp_ctx);
  48668. } else {
  48669. if (comp_ctx->curr_token.allow_auto_semi) {
  48670. DUK_DDD(DUK_DDDPRINT("automatic semicolon terminates statement"));
  48671. } else if (stmt_flags & DUK__ALLOW_AUTO_SEMI_ALWAYS) {
  48672. /* XXX: make this lenience dependent on flags or strictness? */
  48673. DUK_DDD(DUK_DDDPRINT("automatic semicolon terminates statement (allowed for compatibility "
  48674. "even though no lineterm present before next token)"));
  48675. } else {
  48676. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_UNTERMINATED_STMT);
  48677. }
  48678. }
  48679. } else {
  48680. DUK_DDD(DUK_DDDPRINT("statement has no terminator"));
  48681. }
  48682. /*
  48683. * Directive prologue tracking.
  48684. */
  48685. if (stmt_flags & DUK__STILL_PROLOGUE) {
  48686. DUK_DDD(DUK_DDDPRINT("setting in_directive_prologue"));
  48687. comp_ctx->curr_func.in_directive_prologue = 1;
  48688. }
  48689. /*
  48690. * Cleanups (all statement parsing flows through here).
  48691. *
  48692. * Pop label site and reset labels. Reset 'next temp' to value at
  48693. * entry to reuse temps.
  48694. */
  48695. if (label_id >= 0) {
  48696. duk__emit_extraop_bc(comp_ctx,
  48697. DUK_EXTRAOP_ENDLABEL,
  48698. (duk_regconst_t) label_id);
  48699. }
  48700. DUK__SETTEMP(comp_ctx, temp_at_entry);
  48701. duk__reset_labels_to_length(comp_ctx, labels_len_at_entry);
  48702. /* XXX: return indication of "terminalness" (e.g. a 'throw' is terminal) */
  48703. DUK__RECURSION_DECREASE(comp_ctx, thr);
  48704. }
  48705. #undef DUK__HAS_VAL
  48706. #undef DUK__HAS_TERM
  48707. #undef DUK__ALLOW_AUTO_SEMI_ALWAYS
  48708. /*
  48709. * Parse a statement list.
  48710. *
  48711. * Handles automatic semicolon insertion and implicit return value.
  48712. *
  48713. * Upon entry, 'curr_tok' should contain the first token of the first
  48714. * statement (parsed in the "allow regexp literal" mode). Upon exit,
  48715. * 'curr_tok' contains the token following the statement list terminator
  48716. * (EOF or closing brace).
  48717. */
  48718. DUK_LOCAL void duk__parse_stmts(duk_compiler_ctx *comp_ctx, duk_bool_t allow_source_elem, duk_bool_t expect_eof) {
  48719. duk_hthread *thr = comp_ctx->thr;
  48720. duk_context *ctx = (duk_context *) thr;
  48721. duk_ivalue res_alloc;
  48722. duk_ivalue *res = &res_alloc;
  48723. /* Setup state. Initial ivalue is 'undefined'. */
  48724. duk_require_stack(ctx, DUK__PARSE_STATEMENTS_SLOTS);
  48725. /* XXX: 'res' setup can be moved to function body level; in fact, two 'res'
  48726. * intermediate values suffice for parsing of each function. Nesting is needed
  48727. * for nested functions (which may occur inside expressions).
  48728. */
  48729. DUK_MEMZERO(&res_alloc, sizeof(res_alloc));
  48730. res->t = DUK_IVAL_PLAIN;
  48731. res->x1.t = DUK_ISPEC_VALUE;
  48732. res->x1.valstack_idx = duk_get_top(ctx);
  48733. res->x2.valstack_idx = res->x1.valstack_idx + 1;
  48734. duk_push_undefined(ctx);
  48735. duk_push_undefined(ctx);
  48736. /* Parse statements until a closing token (EOF or '}') is found. */
  48737. for (;;) {
  48738. /* Check whether statement list ends. */
  48739. if (expect_eof) {
  48740. if (comp_ctx->curr_token.t == DUK_TOK_EOF) {
  48741. break;
  48742. }
  48743. } else {
  48744. if (comp_ctx->curr_token.t == DUK_TOK_RCURLY) {
  48745. break;
  48746. }
  48747. }
  48748. /* Check statement type based on the first token type.
  48749. *
  48750. * Note: expression parsing helpers expect 'curr_tok' to
  48751. * contain the first token of the expression upon entry.
  48752. */
  48753. DUK_DDD(DUK_DDDPRINT("TOKEN %ld (non-whitespace, non-comment)", (long) comp_ctx->curr_token.t));
  48754. duk__parse_stmt(comp_ctx, res, allow_source_elem);
  48755. }
  48756. duk__advance(comp_ctx);
  48757. /* Tear down state. */
  48758. duk_pop_2(ctx);
  48759. }
  48760. /*
  48761. * Declaration binding instantiation conceptually happens when calling a
  48762. * function; for us it essentially means that function prologue. The
  48763. * conceptual process is described in E5 Section 10.5.
  48764. *
  48765. * We need to keep track of all encountered identifiers to (1) create an
  48766. * identifier-to-register map ("varmap"); and (2) detect duplicate
  48767. * declarations. Identifiers which are not bound to registers still need
  48768. * to be tracked for detecting duplicates. Currently such identifiers
  48769. * are put into the varmap with a 'null' value, which is later cleaned up.
  48770. *
  48771. * To support functions with a large number of variable and function
  48772. * declarations, registers are not allocated beyond a certain limit;
  48773. * after that limit, variables and functions need slow path access.
  48774. * Arguments are currently always register bound, which imposes a hard
  48775. * (and relatively small) argument count limit.
  48776. *
  48777. * Some bindings in E5 are not configurable (= deletable) and almost all
  48778. * are mutable (writable). Exceptions are:
  48779. *
  48780. * - The 'arguments' binding, established only if no shadowing argument
  48781. * or function declaration exists. We handle 'arguments' creation
  48782. * and binding through an explicit slow path environment record.
  48783. *
  48784. * - The "name" binding for a named function expression. This is also
  48785. * handled through an explicit slow path environment record.
  48786. */
  48787. /* XXX: add support for variables to not be register bound always, to
  48788. * handle cases with a very large number of variables?
  48789. */
  48790. DUK_LOCAL void duk__init_varmap_and_prologue_for_pass2(duk_compiler_ctx *comp_ctx, duk_reg_t *out_stmt_value_reg) {
  48791. duk_hthread *thr = comp_ctx->thr;
  48792. duk_context *ctx = (duk_context *) thr;
  48793. duk_hstring *h_name;
  48794. duk_bool_t configurable_bindings;
  48795. duk_uarridx_t num_args;
  48796. duk_uarridx_t num_decls;
  48797. duk_regconst_t rc_name;
  48798. duk_small_uint_t declvar_flags;
  48799. duk_uarridx_t i;
  48800. #ifdef DUK_USE_ASSERTIONS
  48801. duk_idx_t entry_top;
  48802. #endif
  48803. #ifdef DUK_USE_ASSERTIONS
  48804. entry_top = duk_get_top(ctx);
  48805. #endif
  48806. /*
  48807. * Preliminaries
  48808. */
  48809. configurable_bindings = comp_ctx->curr_func.is_eval;
  48810. DUK_DDD(DUK_DDDPRINT("configurable_bindings=%ld", (long) configurable_bindings));
  48811. /* varmap is already in comp_ctx->curr_func.varmap_idx */
  48812. /*
  48813. * Function formal arguments, always bound to registers
  48814. * (there's no support for shuffling them now).
  48815. */
  48816. num_args = (duk_uarridx_t) duk_get_length(ctx, comp_ctx->curr_func.argnames_idx);
  48817. DUK_DDD(DUK_DDDPRINT("num_args=%ld", (long) num_args));
  48818. /* XXX: check num_args */
  48819. for (i = 0; i < num_args; i++) {
  48820. duk_get_prop_index(ctx, comp_ctx->curr_func.argnames_idx, i);
  48821. h_name = duk_get_hstring(ctx, -1);
  48822. DUK_ASSERT(h_name != NULL);
  48823. if (comp_ctx->curr_func.is_strict) {
  48824. if (duk__hstring_is_eval_or_arguments(comp_ctx, h_name)) {
  48825. DUK_DDD(DUK_DDDPRINT("arg named 'eval' or 'arguments' in strict mode -> SyntaxError"));
  48826. goto error_argname;
  48827. }
  48828. duk_dup_top(ctx);
  48829. if (duk_has_prop(ctx, comp_ctx->curr_func.varmap_idx)) {
  48830. DUK_DDD(DUK_DDDPRINT("duplicate arg name in strict mode -> SyntaxError"));
  48831. goto error_argname;
  48832. }
  48833. /* Ensure argument name is not a reserved word in current
  48834. * (final) strictness. Formal argument parsing may not
  48835. * catch reserved names if strictness changes during
  48836. * parsing.
  48837. *
  48838. * We only need to do this in strict mode because non-strict
  48839. * keyword are always detected in formal argument parsing.
  48840. */
  48841. if (DUK_HSTRING_HAS_STRICT_RESERVED_WORD(h_name)) {
  48842. goto error_argname;
  48843. }
  48844. }
  48845. /* overwrite any previous binding of the same name; the effect is
  48846. * that last argument of a certain name wins.
  48847. */
  48848. /* only functions can have arguments */
  48849. DUK_ASSERT(comp_ctx->curr_func.is_function);
  48850. duk_push_uarridx(ctx, i); /* -> [ ... name index ] */
  48851. duk_put_prop(ctx, comp_ctx->curr_func.varmap_idx); /* -> [ ... ] */
  48852. /* no code needs to be emitted, the regs already have values */
  48853. }
  48854. /* use temp_next for tracking register allocations */
  48855. DUK__SETTEMP_CHECKMAX(comp_ctx, (duk_reg_t) num_args);
  48856. /*
  48857. * After arguments, allocate special registers (like shuffling temps)
  48858. */
  48859. if (out_stmt_value_reg) {
  48860. *out_stmt_value_reg = DUK__ALLOCTEMP(comp_ctx);
  48861. }
  48862. if (comp_ctx->curr_func.needs_shuffle) {
  48863. duk_reg_t shuffle_base = DUK__ALLOCTEMPS(comp_ctx, 3);
  48864. comp_ctx->curr_func.shuffle1 = shuffle_base;
  48865. comp_ctx->curr_func.shuffle2 = shuffle_base + 1;
  48866. comp_ctx->curr_func.shuffle3 = shuffle_base + 2;
  48867. DUK_D(DUK_DPRINT("shuffle registers needed by function, allocated: %ld %ld %ld",
  48868. (long) comp_ctx->curr_func.shuffle1,
  48869. (long) comp_ctx->curr_func.shuffle2,
  48870. (long) comp_ctx->curr_func.shuffle3));
  48871. }
  48872. if (comp_ctx->curr_func.temp_next > 0x100) {
  48873. DUK_D(DUK_DPRINT("not enough 8-bit regs: temp_next=%ld", (long) comp_ctx->curr_func.temp_next));
  48874. goto error_outofregs;
  48875. }
  48876. /*
  48877. * Function declarations
  48878. */
  48879. num_decls = (duk_uarridx_t) duk_get_length(ctx, comp_ctx->curr_func.decls_idx);
  48880. DUK_DDD(DUK_DDDPRINT("num_decls=%ld -> %!T",
  48881. (long) num_decls,
  48882. (duk_tval *) duk_get_tval(ctx, comp_ctx->curr_func.decls_idx)));
  48883. for (i = 0; i < num_decls; i += 2) {
  48884. duk_int_t decl_type;
  48885. duk_int_t fnum;
  48886. duk_get_prop_index(ctx, comp_ctx->curr_func.decls_idx, i + 1); /* decl type */
  48887. decl_type = duk_to_int(ctx, -1);
  48888. fnum = decl_type >> 8; /* XXX: macros */
  48889. decl_type = decl_type & 0xff;
  48890. duk_pop(ctx);
  48891. if (decl_type != DUK_DECL_TYPE_FUNC) {
  48892. continue;
  48893. }
  48894. duk_get_prop_index(ctx, comp_ctx->curr_func.decls_idx, i); /* decl name */
  48895. /* XXX: spilling */
  48896. if (comp_ctx->curr_func.is_function) {
  48897. duk_reg_t reg_bind;
  48898. duk_dup_top(ctx);
  48899. if (duk_has_prop(ctx, comp_ctx->curr_func.varmap_idx)) {
  48900. /* shadowed; update value */
  48901. duk_dup_top(ctx);
  48902. duk_get_prop(ctx, comp_ctx->curr_func.varmap_idx);
  48903. reg_bind = duk_to_int(ctx, -1); /* [ ... name reg_bind ] */
  48904. duk__emit_a_bc(comp_ctx,
  48905. DUK_OP_CLOSURE,
  48906. (duk_regconst_t) reg_bind,
  48907. (duk_regconst_t) fnum);
  48908. } else {
  48909. /* function: always register bound */
  48910. reg_bind = DUK__ALLOCTEMP(comp_ctx);
  48911. duk__emit_a_bc(comp_ctx,
  48912. DUK_OP_CLOSURE,
  48913. (duk_regconst_t) reg_bind,
  48914. (duk_regconst_t) fnum);
  48915. duk_push_int(ctx, (duk_int_t) reg_bind);
  48916. }
  48917. } else {
  48918. /* Function declaration for global/eval code is emitted even
  48919. * for duplicates, because of E5 Section 10.5, step 5.e of
  48920. * E5.1 (special behavior for variable bound to global object).
  48921. *
  48922. * DECLVAR will not re-declare a variable as such, but will
  48923. * update the binding value.
  48924. */
  48925. duk_reg_t reg_temp = DUK__ALLOCTEMP(comp_ctx);
  48926. duk_dup_top(ctx);
  48927. rc_name = duk__getconst(comp_ctx);
  48928. duk_push_null(ctx);
  48929. duk__emit_a_bc(comp_ctx,
  48930. DUK_OP_CLOSURE,
  48931. (duk_regconst_t) reg_temp,
  48932. (duk_regconst_t) fnum);
  48933. declvar_flags = DUK_PROPDESC_FLAG_WRITABLE |
  48934. DUK_PROPDESC_FLAG_ENUMERABLE |
  48935. DUK_BC_DECLVAR_FLAG_FUNC_DECL;
  48936. if (configurable_bindings) {
  48937. declvar_flags |= DUK_PROPDESC_FLAG_CONFIGURABLE;
  48938. }
  48939. duk__emit_a_b_c(comp_ctx,
  48940. DUK_OP_DECLVAR | DUK__EMIT_FLAG_NO_SHUFFLE_A,
  48941. (duk_regconst_t) declvar_flags /*flags*/,
  48942. rc_name /*name*/,
  48943. (duk_regconst_t) reg_temp /*value*/);
  48944. DUK__SETTEMP(comp_ctx, reg_temp); /* forget temp */
  48945. }
  48946. DUK_DDD(DUK_DDDPRINT("function declaration to varmap: %!T -> %!T",
  48947. (duk_tval *) duk_get_tval(ctx, -2),
  48948. (duk_tval *) duk_get_tval(ctx, -1)));
  48949. duk_put_prop(ctx, comp_ctx->curr_func.varmap_idx); /* [ ... name reg/null ] -> [ ... ] */
  48950. }
  48951. /*
  48952. * 'arguments' binding is special; if a shadowing argument or
  48953. * function declaration exists, an arguments object will
  48954. * definitely not be needed, regardless of whether the identifier
  48955. * 'arguments' is referenced inside the function body.
  48956. */
  48957. if (duk_has_prop_stridx(ctx, comp_ctx->curr_func.varmap_idx, DUK_STRIDX_LC_ARGUMENTS)) {
  48958. DUK_DDD(DUK_DDDPRINT("'arguments' is shadowed by argument or function declaration "
  48959. "-> arguments object creation can be skipped"));
  48960. comp_ctx->curr_func.is_arguments_shadowed = 1;
  48961. }
  48962. /*
  48963. * Variable declarations.
  48964. *
  48965. * Unlike function declarations, variable declaration values don't get
  48966. * assigned on entry. If a binding of the same name already exists, just
  48967. * ignore it silently.
  48968. */
  48969. for (i = 0; i < num_decls; i += 2) {
  48970. duk_int_t decl_type;
  48971. duk_get_prop_index(ctx, comp_ctx->curr_func.decls_idx, i + 1); /* decl type */
  48972. decl_type = duk_to_int(ctx, -1);
  48973. decl_type = decl_type & 0xff;
  48974. duk_pop(ctx);
  48975. if (decl_type != DUK_DECL_TYPE_VAR) {
  48976. continue;
  48977. }
  48978. duk_get_prop_index(ctx, comp_ctx->curr_func.decls_idx, i); /* decl name */
  48979. if (duk_has_prop(ctx, comp_ctx->curr_func.varmap_idx)) {
  48980. /* shadowed, ignore */
  48981. } else {
  48982. duk_get_prop_index(ctx, comp_ctx->curr_func.decls_idx, i); /* decl name */
  48983. h_name = duk_get_hstring(ctx, -1);
  48984. DUK_ASSERT(h_name != NULL);
  48985. if (h_name == DUK_HTHREAD_STRING_LC_ARGUMENTS(thr) &&
  48986. !comp_ctx->curr_func.is_arguments_shadowed) {
  48987. /* E5 Section steps 7-8 */
  48988. DUK_DDD(DUK_DDDPRINT("'arguments' not shadowed by a function declaration, "
  48989. "but appears as a variable declaration -> treat as "
  48990. "a no-op for variable declaration purposes"));
  48991. duk_pop(ctx);
  48992. continue;
  48993. }
  48994. /* XXX: spilling */
  48995. if (comp_ctx->curr_func.is_function) {
  48996. duk_reg_t reg_bind = DUK__ALLOCTEMP(comp_ctx);
  48997. /* no need to init reg, it will be undefined on entry */
  48998. duk_push_int(ctx, (duk_int_t) reg_bind);
  48999. } else {
  49000. duk_dup_top(ctx);
  49001. rc_name = duk__getconst(comp_ctx);
  49002. duk_push_null(ctx);
  49003. declvar_flags = DUK_PROPDESC_FLAG_WRITABLE |
  49004. DUK_PROPDESC_FLAG_ENUMERABLE |
  49005. DUK_BC_DECLVAR_FLAG_UNDEF_VALUE;
  49006. if (configurable_bindings) {
  49007. declvar_flags |= DUK_PROPDESC_FLAG_CONFIGURABLE;
  49008. }
  49009. duk__emit_a_b_c(comp_ctx,
  49010. DUK_OP_DECLVAR | DUK__EMIT_FLAG_NO_SHUFFLE_A,
  49011. (duk_regconst_t) declvar_flags /*flags*/,
  49012. rc_name /*name*/,
  49013. (duk_regconst_t) 0 /*value*/);
  49014. }
  49015. duk_put_prop(ctx, comp_ctx->curr_func.varmap_idx); /* [ ... name reg/null ] -> [ ... ] */
  49016. }
  49017. }
  49018. /*
  49019. * Wrap up
  49020. */
  49021. DUK_DDD(DUK_DDDPRINT("varmap: %!T, is_arguments_shadowed=%ld",
  49022. (duk_tval *) duk_get_tval(ctx, comp_ctx->curr_func.varmap_idx),
  49023. (long) comp_ctx->curr_func.is_arguments_shadowed));
  49024. DUK_ASSERT_TOP(ctx, entry_top);
  49025. return;
  49026. error_outofregs:
  49027. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, DUK_STR_REG_LIMIT);
  49028. DUK_UNREACHABLE();
  49029. return;
  49030. error_argname:
  49031. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_ARG_NAME);
  49032. DUK_UNREACHABLE();
  49033. return;
  49034. }
  49035. /*
  49036. * Parse a function-body-like expression (FunctionBody or Program
  49037. * in E5 grammar) using a two-pass parse. The productions appear
  49038. * in the following contexts:
  49039. *
  49040. * - function expression
  49041. * - function statement
  49042. * - function declaration
  49043. * - getter in object literal
  49044. * - setter in object literal
  49045. * - global code
  49046. * - eval code
  49047. * - Function constructor body
  49048. *
  49049. * This function only parses the statement list of the body; the argument
  49050. * list and possible function name must be initialized by the caller.
  49051. * For instance, for Function constructor, the argument names are originally
  49052. * on the value stack. The parsing of statements ends either at an EOF or
  49053. * a closing brace; this is controlled by an input flag.
  49054. *
  49055. * Note that there are many differences affecting parsing and even code
  49056. * generation:
  49057. *
  49058. * - Global and eval code have an implicit return value generated
  49059. * by the last statement; function code does not
  49060. *
  49061. * - Global code, eval code, and Function constructor body end in
  49062. * an EOF, other bodies in a closing brace ('}')
  49063. *
  49064. * Upon entry, 'curr_tok' is ignored and the function will pull in the
  49065. * first token on its own. Upon exit, 'curr_tok' is the terminating
  49066. * token (EOF or closing brace).
  49067. */
  49068. DUK_LOCAL void duk__parse_func_body(duk_compiler_ctx *comp_ctx, duk_bool_t expect_eof, duk_bool_t implicit_return_value, duk_small_int_t expect_token) {
  49069. duk_compiler_func *func;
  49070. duk_hthread *thr;
  49071. duk_context *ctx;
  49072. duk_reg_t reg_stmt_value = -1;
  49073. duk_lexer_point lex_pt;
  49074. duk_reg_t temp_first;
  49075. duk_small_int_t compile_round = 1;
  49076. DUK_ASSERT(comp_ctx != NULL);
  49077. thr = comp_ctx->thr;
  49078. ctx = (duk_context *) thr;
  49079. DUK_ASSERT(thr != NULL);
  49080. func = &comp_ctx->curr_func;
  49081. DUK_ASSERT(func != NULL);
  49082. DUK__RECURSION_INCREASE(comp_ctx, thr);
  49083. duk_require_stack(ctx, DUK__FUNCTION_BODY_REQUIRE_SLOTS);
  49084. /*
  49085. * Store lexer position for a later rewind
  49086. */
  49087. DUK_LEXER_GETPOINT(&comp_ctx->lex, &lex_pt);
  49088. /*
  49089. * Program code (global and eval code) has an implicit return value
  49090. * from the last statement value (e.g. eval("1; 2+3;") returns 3).
  49091. * This is not the case with functions. If implicit statement return
  49092. * value is requested, all statements are coerced to a register
  49093. * allocated here, and used in the implicit return statement below.
  49094. */
  49095. /* XXX: this is pointless here because pass 1 is throw-away */
  49096. if (implicit_return_value) {
  49097. reg_stmt_value = DUK__ALLOCTEMP(comp_ctx);
  49098. /* If an implicit return value is needed by caller, it must be
  49099. * initialized to 'undefined' because we don't know whether any
  49100. * non-empty (where "empty" is a continuation type, and different
  49101. * from an empty statement) statements will be executed.
  49102. *
  49103. * However, since 1st pass is a throwaway one, no need to emit
  49104. * it here.
  49105. */
  49106. #if 0
  49107. duk__emit_extraop_bc(comp_ctx,
  49108. DUK_EXTRAOP_LDUNDEF,
  49109. 0);
  49110. #endif
  49111. }
  49112. /*
  49113. * First pass.
  49114. *
  49115. * Gather variable/function declarations needed for second pass.
  49116. * Code generated is dummy and discarded.
  49117. */
  49118. func->in_directive_prologue = 1;
  49119. func->in_scanning = 1;
  49120. func->may_direct_eval = 0;
  49121. func->id_access_arguments = 0;
  49122. func->id_access_slow = 0;
  49123. func->reg_stmt_value = reg_stmt_value;
  49124. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  49125. func->min_line = DUK_INT_MAX;
  49126. func->max_line = 0;
  49127. #endif
  49128. /* duk__parse_stmts() expects curr_tok to be set; parse in "allow regexp literal" mode with current strictness */
  49129. if (expect_token >= 0) {
  49130. /* Eating a left curly; regexp mode is allowed by left curly
  49131. * based on duk__token_lbp[] automatically.
  49132. */
  49133. DUK_ASSERT(expect_token == DUK_TOK_LCURLY);
  49134. duk__update_lineinfo_currtoken(comp_ctx);
  49135. duk__advance_expect(comp_ctx, expect_token);
  49136. } else {
  49137. /* Need to set curr_token.t because lexing regexp mode depends on current
  49138. * token type. Zero value causes "allow regexp" mode.
  49139. */
  49140. comp_ctx->curr_token.t = 0;
  49141. duk__advance(comp_ctx);
  49142. }
  49143. DUK_DDD(DUK_DDDPRINT("begin 1st pass"));
  49144. duk__parse_stmts(comp_ctx,
  49145. 1, /* allow source elements */
  49146. expect_eof); /* expect EOF instead of } */
  49147. DUK_DDD(DUK_DDDPRINT("end 1st pass"));
  49148. /*
  49149. * Second (and possibly third) pass.
  49150. *
  49151. * Generate actual code. In most cases the need for shuffle
  49152. * registers is detected during pass 1, but in some corner cases
  49153. * we'll only detect it during pass 2 and a third pass is then
  49154. * needed (see GH-115).
  49155. */
  49156. for (;;) {
  49157. duk_bool_t needs_shuffle_before = comp_ctx->curr_func.needs_shuffle;
  49158. compile_round++;
  49159. /*
  49160. * Rewind lexer.
  49161. *
  49162. * duk__parse_stmts() expects curr_tok to be set; parse in "allow regexp
  49163. * literal" mode with current strictness.
  49164. *
  49165. * curr_token line number info should be initialized for pass 2 before
  49166. * generating prologue, to ensure prologue bytecode gets nice line numbers.
  49167. */
  49168. DUK_DDD(DUK_DDDPRINT("rewind lexer"));
  49169. DUK_LEXER_SETPOINT(&comp_ctx->lex, &lex_pt);
  49170. comp_ctx->curr_token.t = 0; /* this is needed for regexp mode */
  49171. comp_ctx->curr_token.start_line = 0; /* needed for line number tracking (becomes prev_token.start_line) */
  49172. duk__advance(comp_ctx);
  49173. /*
  49174. * Reset function state and perform register allocation, which creates
  49175. * 'varmap' for second pass. Function prologue for variable declarations,
  49176. * binding value initializations etc is emitted as a by-product.
  49177. *
  49178. * Strict mode restrictions for duplicate and invalid argument
  49179. * names are checked here now that we know whether the function
  49180. * is actually strict. See: test-dev-strict-mode-boundary.js.
  49181. *
  49182. * Inner functions are compiled during pass 1 and are not reset.
  49183. */
  49184. duk__reset_func_for_pass2(comp_ctx);
  49185. func->in_directive_prologue = 1;
  49186. func->in_scanning = 0;
  49187. /* must be able to emit code, alloc consts, etc. */
  49188. duk__init_varmap_and_prologue_for_pass2(comp_ctx,
  49189. (implicit_return_value ? &reg_stmt_value : NULL));
  49190. func->reg_stmt_value = reg_stmt_value;
  49191. temp_first = DUK__GETTEMP(comp_ctx);
  49192. func->temp_first = temp_first;
  49193. func->temp_next = temp_first;
  49194. func->stmt_next = 0;
  49195. func->label_next = 0;
  49196. /* XXX: init or assert catch depth etc -- all values */
  49197. func->id_access_arguments = 0;
  49198. func->id_access_slow = 0;
  49199. /*
  49200. * Check function name validity now that we know strictness.
  49201. * This only applies to function declarations and expressions,
  49202. * not setter/getter name.
  49203. *
  49204. * See: test-dev-strict-mode-boundary.js
  49205. */
  49206. if (func->is_function && !func->is_setget && func->h_name != NULL) {
  49207. if (func->is_strict) {
  49208. if (duk__hstring_is_eval_or_arguments(comp_ctx, func->h_name)) {
  49209. DUK_DDD(DUK_DDDPRINT("func name is 'eval' or 'arguments' in strict mode"));
  49210. goto error_funcname;
  49211. }
  49212. if (DUK_HSTRING_HAS_STRICT_RESERVED_WORD(func->h_name)) {
  49213. DUK_DDD(DUK_DDDPRINT("func name is a reserved word in strict mode"));
  49214. goto error_funcname;
  49215. }
  49216. } else {
  49217. if (DUK_HSTRING_HAS_RESERVED_WORD(func->h_name) &&
  49218. !DUK_HSTRING_HAS_STRICT_RESERVED_WORD(func->h_name)) {
  49219. DUK_DDD(DUK_DDDPRINT("func name is a reserved word in non-strict mode"));
  49220. goto error_funcname;
  49221. }
  49222. }
  49223. }
  49224. /*
  49225. * Second pass parsing.
  49226. */
  49227. if (implicit_return_value) {
  49228. /* Default implicit return value. */
  49229. duk__emit_extraop_bc(comp_ctx,
  49230. DUK_EXTRAOP_LDUNDEF,
  49231. 0);
  49232. }
  49233. DUK_DDD(DUK_DDDPRINT("begin 2nd pass"));
  49234. duk__parse_stmts(comp_ctx,
  49235. 1, /* allow source elements */
  49236. expect_eof); /* expect EOF instead of } */
  49237. DUK_DDD(DUK_DDDPRINT("end 2nd pass"));
  49238. duk__update_lineinfo_currtoken(comp_ctx);
  49239. if (needs_shuffle_before == comp_ctx->curr_func.needs_shuffle) {
  49240. /* Shuffle decision not changed. */
  49241. break;
  49242. }
  49243. if (compile_round >= 3) {
  49244. /* Should never happen but avoid infinite loop just in case. */
  49245. DUK_D(DUK_DPRINT("more than 3 compile passes needed, should never happen"));
  49246. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR);
  49247. }
  49248. DUK_D(DUK_DPRINT("need additional round to compile function, round now %d", (int) compile_round));
  49249. }
  49250. /*
  49251. * Emit a final RETURN.
  49252. *
  49253. * It would be nice to avoid emitting an unnecessary "return" opcode
  49254. * if the current PC is not reachable. However, this cannot be reliably
  49255. * detected; even if the previous instruction is an unconditional jump,
  49256. * there may be a previous jump which jumps to current PC (which is the
  49257. * case for iteration and conditional statements, for instance).
  49258. */
  49259. /* XXX: request a "last statement is terminal" from duk__parse_stmt() and duk__parse_stmts();
  49260. * we could avoid the last RETURN if we could ensure there is no way to get here
  49261. * (directly or via a jump)
  49262. */
  49263. DUK_ASSERT(comp_ctx->curr_func.catch_depth == 0); /* fast returns are always OK here */
  49264. if (reg_stmt_value >= 0) {
  49265. duk__emit_a_b(comp_ctx,
  49266. DUK_OP_RETURN | DUK__EMIT_FLAG_NO_SHUFFLE_A,
  49267. (duk_regconst_t) (DUK_BC_RETURN_FLAG_HAVE_RETVAL | DUK_BC_RETURN_FLAG_FAST) /*flags*/,
  49268. (duk_regconst_t) reg_stmt_value /*reg*/);
  49269. } else {
  49270. duk__emit_a_b(comp_ctx,
  49271. DUK_OP_RETURN | DUK__EMIT_FLAG_NO_SHUFFLE_A,
  49272. (duk_regconst_t) DUK_BC_RETURN_FLAG_FAST /*flags*/,
  49273. (duk_regconst_t) 0 /*reg(ignored)*/);
  49274. }
  49275. /*
  49276. * Peephole optimize JUMP chains.
  49277. */
  49278. duk__peephole_optimize_bytecode(comp_ctx);
  49279. /*
  49280. * comp_ctx->curr_func is now ready to be converted into an actual
  49281. * function template.
  49282. */
  49283. DUK__RECURSION_DECREASE(comp_ctx, thr);
  49284. return;
  49285. error_funcname:
  49286. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_FUNC_NAME);
  49287. }
  49288. /*
  49289. * Parse a function-like expression:
  49290. *
  49291. * - function expression
  49292. * - function declaration
  49293. * - function statement (non-standard)
  49294. * - setter/getter
  49295. *
  49296. * Adds the function to comp_ctx->curr_func function table and returns the
  49297. * function number.
  49298. *
  49299. * On entry, curr_token points to:
  49300. *
  49301. * - the token after 'function' for function expression/declaration/statement
  49302. * - the token after 'set' or 'get' for setter/getter
  49303. */
  49304. /* Parse formals. */
  49305. DUK_LOCAL void duk__parse_func_formals(duk_compiler_ctx *comp_ctx) {
  49306. duk_hthread *thr = comp_ctx->thr;
  49307. duk_context *ctx = (duk_context *) thr;
  49308. duk_bool_t first = 1;
  49309. duk_uarridx_t n;
  49310. for (;;) {
  49311. if (comp_ctx->curr_token.t == DUK_TOK_RPAREN) {
  49312. break;
  49313. }
  49314. if (first) {
  49315. /* no comma */
  49316. first = 0;
  49317. } else {
  49318. duk__advance_expect(comp_ctx, DUK_TOK_COMMA);
  49319. }
  49320. /* Note: when parsing a formal list in non-strict context, e.g.
  49321. * "implements" is parsed as an identifier. When the function is
  49322. * later detected to be strict, the argument list must be rechecked
  49323. * against a larger set of reserved words (that of strict mode).
  49324. * This is handled by duk__parse_func_body(). Here we recognize
  49325. * whatever tokens are considered reserved in current strictness
  49326. * (which is not always enough).
  49327. */
  49328. if (comp_ctx->curr_token.t != DUK_TOK_IDENTIFIER) {
  49329. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, "expected identifier");
  49330. }
  49331. DUK_ASSERT(comp_ctx->curr_token.t == DUK_TOK_IDENTIFIER);
  49332. DUK_ASSERT(comp_ctx->curr_token.str1 != NULL);
  49333. DUK_DDD(DUK_DDDPRINT("formal argument: %!O",
  49334. (duk_heaphdr *) comp_ctx->curr_token.str1));
  49335. /* XXX: append primitive */
  49336. duk_push_hstring(ctx, comp_ctx->curr_token.str1);
  49337. n = (duk_uarridx_t) duk_get_length(ctx, comp_ctx->curr_func.argnames_idx);
  49338. duk_put_prop_index(ctx, comp_ctx->curr_func.argnames_idx, n);
  49339. duk__advance(comp_ctx); /* eat identifier */
  49340. }
  49341. }
  49342. /* Parse a function-like expression, assuming that 'comp_ctx->curr_func' is
  49343. * correctly set up. Assumes that curr_token is just after 'function' (or
  49344. * 'set'/'get' etc).
  49345. */
  49346. DUK_LOCAL void duk__parse_func_like_raw(duk_compiler_ctx *comp_ctx, duk_bool_t is_decl, duk_bool_t is_setget) {
  49347. duk_hthread *thr = comp_ctx->thr;
  49348. duk_context *ctx = (duk_context *) thr;
  49349. DUK_ASSERT(comp_ctx->curr_func.num_formals == 0);
  49350. DUK_ASSERT(comp_ctx->curr_func.is_function == 1);
  49351. DUK_ASSERT(comp_ctx->curr_func.is_eval == 0);
  49352. DUK_ASSERT(comp_ctx->curr_func.is_global == 0);
  49353. DUK_ASSERT(comp_ctx->curr_func.is_setget == is_setget);
  49354. DUK_ASSERT(comp_ctx->curr_func.is_decl == is_decl);
  49355. duk__update_lineinfo_currtoken(comp_ctx);
  49356. /*
  49357. * Function name (if any)
  49358. *
  49359. * We don't check for prohibited names here, because we don't
  49360. * yet know whether the function will be strict. Function body
  49361. * parsing handles this retroactively.
  49362. *
  49363. * For function expressions and declarations function name must
  49364. * be an Identifer (excludes reserved words). For setter/getter
  49365. * it is a PropertyName which allows reserved words and also
  49366. * strings and numbers (e.g. "{ get 1() { ... } }").
  49367. */
  49368. if (is_setget) {
  49369. /* PropertyName -> IdentifierName | StringLiteral | NumericLiteral */
  49370. if (comp_ctx->curr_token.t_nores == DUK_TOK_IDENTIFIER ||
  49371. comp_ctx->curr_token.t == DUK_TOK_STRING) {
  49372. duk_push_hstring(ctx, comp_ctx->curr_token.str1); /* keep in valstack */
  49373. } else if (comp_ctx->curr_token.t == DUK_TOK_NUMBER) {
  49374. duk_push_number(ctx, comp_ctx->curr_token.num);
  49375. duk_to_string(ctx, -1);
  49376. } else {
  49377. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_GETSET_NAME);
  49378. }
  49379. comp_ctx->curr_func.h_name = duk_get_hstring(ctx, -1); /* borrowed reference */
  49380. DUK_ASSERT(comp_ctx->curr_func.h_name != NULL);
  49381. duk__advance(comp_ctx);
  49382. } else {
  49383. /* Function name is an Identifier (not IdentifierName), but we get
  49384. * the raw name (not recognizing keywords) here and perform the name
  49385. * checks only after pass 1.
  49386. */
  49387. if (comp_ctx->curr_token.t_nores == DUK_TOK_IDENTIFIER) {
  49388. duk_push_hstring(ctx, comp_ctx->curr_token.str1); /* keep in valstack */
  49389. comp_ctx->curr_func.h_name = duk_get_hstring(ctx, -1); /* borrowed reference */
  49390. DUK_ASSERT(comp_ctx->curr_func.h_name != NULL);
  49391. duk__advance(comp_ctx);
  49392. } else {
  49393. /* valstack will be unbalanced, which is OK */
  49394. DUK_ASSERT(!is_setget);
  49395. if (is_decl) {
  49396. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_FUNC_NAME_REQUIRED);
  49397. }
  49398. }
  49399. }
  49400. DUK_DDD(DUK_DDDPRINT("function name: %!O",
  49401. (duk_heaphdr *) comp_ctx->curr_func.h_name));
  49402. /*
  49403. * Formal argument list
  49404. *
  49405. * We don't check for prohibited names or for duplicate argument
  49406. * names here, becase we don't yet know whether the function will
  49407. * be strict. Function body parsing handles this retroactively.
  49408. */
  49409. duk__advance_expect(comp_ctx, DUK_TOK_LPAREN);
  49410. duk__parse_func_formals(comp_ctx);
  49411. DUK_ASSERT(comp_ctx->curr_token.t == DUK_TOK_RPAREN);
  49412. duk__advance(comp_ctx);
  49413. /*
  49414. * Parse function body
  49415. */
  49416. duk__parse_func_body(comp_ctx,
  49417. 0, /* expect_eof */
  49418. 0, /* implicit_return_value */
  49419. DUK_TOK_LCURLY); /* expect_token */
  49420. /*
  49421. * Convert duk_compiler_func to a function template and add it
  49422. * to the parent function table.
  49423. */
  49424. duk__convert_to_func_template(comp_ctx, is_setget /*force_no_namebind*/); /* -> [ ... func ] */
  49425. }
  49426. /* Parse an inner function, adding the function template to the current function's
  49427. * function table. Return a function number to be used by the outer function.
  49428. *
  49429. * Avoiding O(depth^2) inner function parsing is handled here. On the first pass,
  49430. * compile and register the function normally into the 'funcs' array, also recording
  49431. * a lexer point (offset/line) to the closing brace of the function. On the second
  49432. * pass, skip the function and return the same 'fnum' as on the first pass by using
  49433. * a running counter.
  49434. *
  49435. * An unfortunate side effect of this is that when parsing the inner function, almost
  49436. * nothing is known of the outer function, i.e. the inner function's scope. We don't
  49437. * need that information at the moment, but it would allow some optimizations if it
  49438. * were used.
  49439. */
  49440. DUK_LOCAL duk_int_t duk__parse_func_like_fnum(duk_compiler_ctx *comp_ctx, duk_bool_t is_decl, duk_bool_t is_setget) {
  49441. duk_hthread *thr = comp_ctx->thr;
  49442. duk_context *ctx = (duk_context *) thr;
  49443. duk_compiler_func old_func;
  49444. duk_idx_t entry_top;
  49445. duk_int_t fnum;
  49446. /*
  49447. * On second pass, skip the function.
  49448. */
  49449. if (!comp_ctx->curr_func.in_scanning) {
  49450. duk_lexer_point lex_pt;
  49451. fnum = comp_ctx->curr_func.fnum_next++;
  49452. duk_get_prop_index(ctx, comp_ctx->curr_func.funcs_idx, (duk_uarridx_t) (fnum * 3 + 1));
  49453. lex_pt.offset = duk_to_int(ctx, -1);
  49454. duk_pop(ctx);
  49455. duk_get_prop_index(ctx, comp_ctx->curr_func.funcs_idx, (duk_uarridx_t) (fnum * 3 + 2));
  49456. lex_pt.line = duk_to_int(ctx, -1);
  49457. duk_pop(ctx);
  49458. DUK_DDD(DUK_DDDPRINT("second pass of an inner func, skip the function, reparse closing brace; lex offset=%ld, line=%ld",
  49459. (long) lex_pt.offset, (long) lex_pt.line));
  49460. DUK_LEXER_SETPOINT(&comp_ctx->lex, &lex_pt);
  49461. comp_ctx->curr_token.t = 0; /* this is needed for regexp mode */
  49462. comp_ctx->curr_token.start_line = 0; /* needed for line number tracking (becomes prev_token.start_line) */
  49463. duk__advance(comp_ctx);
  49464. duk__advance_expect(comp_ctx, DUK_TOK_RCURLY);
  49465. return fnum;
  49466. }
  49467. /*
  49468. * On first pass, perform actual parsing. Remember valstack top on entry
  49469. * to restore it later, and switch to using a new function in comp_ctx.
  49470. */
  49471. entry_top = duk_get_top(ctx);
  49472. DUK_DDD(DUK_DDDPRINT("before func: entry_top=%ld, curr_tok.start_offset=%ld",
  49473. (long) entry_top, (long) comp_ctx->curr_token.start_offset));
  49474. DUK_MEMCPY(&old_func, &comp_ctx->curr_func, sizeof(duk_compiler_func));
  49475. DUK_MEMZERO(&comp_ctx->curr_func, sizeof(duk_compiler_func));
  49476. duk__init_func_valstack_slots(comp_ctx);
  49477. DUK_ASSERT(comp_ctx->curr_func.num_formals == 0);
  49478. /* inherit initial strictness from parent */
  49479. comp_ctx->curr_func.is_strict = old_func.is_strict;
  49480. DUK_ASSERT(comp_ctx->curr_func.is_notail == 0);
  49481. comp_ctx->curr_func.is_function = 1;
  49482. DUK_ASSERT(comp_ctx->curr_func.is_eval == 0);
  49483. DUK_ASSERT(comp_ctx->curr_func.is_global == 0);
  49484. comp_ctx->curr_func.is_setget = is_setget;
  49485. comp_ctx->curr_func.is_decl = is_decl;
  49486. /*
  49487. * Parse inner function
  49488. */
  49489. duk__parse_func_like_raw(comp_ctx, is_decl, is_setget); /* pushes function template */
  49490. /* prev_token.start_offset points to the closing brace here; when skipping
  49491. * we're going to reparse the closing brace to ensure semicolon insertion
  49492. * etc work as expected.
  49493. */
  49494. DUK_DDD(DUK_DDDPRINT("after func: prev_tok.start_offset=%ld, curr_tok.start_offset=%ld",
  49495. (long) comp_ctx->prev_token.start_offset, (long) comp_ctx->curr_token.start_offset));
  49496. DUK_ASSERT(comp_ctx->lex.input[comp_ctx->prev_token.start_offset] == (duk_uint8_t) DUK_ASC_RCURLY);
  49497. /* XXX: append primitive */
  49498. DUK_ASSERT(duk_get_length(ctx, old_func.funcs_idx) == (duk_size_t) (old_func.fnum_next * 3));
  49499. fnum = old_func.fnum_next++;
  49500. if (fnum > DUK__MAX_FUNCS) {
  49501. DUK_ERROR(comp_ctx->thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_FUNC_LIMIT);
  49502. }
  49503. /* array writes autoincrement length */
  49504. (void) duk_put_prop_index(ctx, old_func.funcs_idx, (duk_uarridx_t) (fnum * 3));
  49505. duk_push_size_t(ctx, comp_ctx->prev_token.start_offset);
  49506. (void) duk_put_prop_index(ctx, old_func.funcs_idx, (duk_uarridx_t) (fnum * 3 + 1));
  49507. duk_push_int(ctx, comp_ctx->prev_token.start_line);
  49508. (void) duk_put_prop_index(ctx, old_func.funcs_idx, (duk_uarridx_t) (fnum * 3 + 2));
  49509. /*
  49510. * Cleanup: restore original function, restore valstack state.
  49511. */
  49512. DUK_MEMCPY((void *) &comp_ctx->curr_func, (void *) &old_func, sizeof(duk_compiler_func));
  49513. duk_set_top(ctx, entry_top);
  49514. DUK_ASSERT_TOP(ctx, entry_top);
  49515. return fnum;
  49516. }
  49517. /*
  49518. * Compile input string into an executable function template without
  49519. * arguments.
  49520. *
  49521. * The string is parsed as the "Program" production of Ecmascript E5.
  49522. * Compilation context can be either global code or eval code (see E5
  49523. * Sections 14 and 15.1.2.1).
  49524. *
  49525. * Input stack: [ ... filename ]
  49526. * Output stack: [ ... func_template ]
  49527. */
  49528. /* XXX: source code property */
  49529. DUK_LOCAL duk_ret_t duk__js_compile_raw(duk_context *ctx) {
  49530. duk_hthread *thr = (duk_hthread *) ctx;
  49531. duk_hstring *h_filename;
  49532. duk__compiler_stkstate *comp_stk;
  49533. duk_compiler_ctx *comp_ctx;
  49534. duk_lexer_point *lex_pt;
  49535. duk_compiler_func *func;
  49536. duk_idx_t entry_top;
  49537. duk_bool_t is_strict;
  49538. duk_bool_t is_eval;
  49539. duk_bool_t is_funcexpr;
  49540. duk_small_uint_t flags;
  49541. DUK_ASSERT(thr != NULL);
  49542. /*
  49543. * Arguments check
  49544. */
  49545. entry_top = duk_get_top(ctx);
  49546. DUK_ASSERT(entry_top >= 2);
  49547. comp_stk = (duk__compiler_stkstate *) duk_require_pointer(ctx, -1);
  49548. comp_ctx = &comp_stk->comp_ctx_alloc;
  49549. lex_pt = &comp_stk->lex_pt_alloc;
  49550. DUK_ASSERT(comp_ctx != NULL);
  49551. DUK_ASSERT(lex_pt != NULL);
  49552. flags = comp_stk->flags;
  49553. is_eval = (flags & DUK_JS_COMPILE_FLAG_EVAL ? 1 : 0);
  49554. is_strict = (flags & DUK_JS_COMPILE_FLAG_STRICT ? 1 : 0);
  49555. is_funcexpr = (flags & DUK_JS_COMPILE_FLAG_FUNCEXPR ? 1 : 0);
  49556. h_filename = duk_get_hstring(ctx, -2); /* may be undefined */
  49557. /*
  49558. * Init compiler and lexer contexts
  49559. */
  49560. func = &comp_ctx->curr_func;
  49561. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  49562. comp_ctx->thr = NULL;
  49563. comp_ctx->h_filename = NULL;
  49564. comp_ctx->prev_token.str1 = NULL;
  49565. comp_ctx->prev_token.str2 = NULL;
  49566. comp_ctx->curr_token.str1 = NULL;
  49567. comp_ctx->curr_token.str2 = NULL;
  49568. #endif
  49569. duk_require_stack(ctx, DUK__COMPILE_ENTRY_SLOTS);
  49570. duk_push_dynamic_buffer(ctx, 0); /* entry_top + 0 */
  49571. duk_push_undefined(ctx); /* entry_top + 1 */
  49572. duk_push_undefined(ctx); /* entry_top + 2 */
  49573. duk_push_undefined(ctx); /* entry_top + 3 */
  49574. duk_push_undefined(ctx); /* entry_top + 4 */
  49575. comp_ctx->thr = thr;
  49576. comp_ctx->h_filename = h_filename;
  49577. comp_ctx->tok11_idx = entry_top + 1;
  49578. comp_ctx->tok12_idx = entry_top + 2;
  49579. comp_ctx->tok21_idx = entry_top + 3;
  49580. comp_ctx->tok22_idx = entry_top + 4;
  49581. comp_ctx->recursion_limit = DUK_COMPILER_RECURSION_LIMIT;
  49582. /* comp_ctx->lex has been pre-initialized by caller: it has been
  49583. * zeroed and input/input_length has been set.
  49584. */
  49585. comp_ctx->lex.thr = thr;
  49586. /* comp_ctx->lex.input and comp_ctx->lex.input_length filled by caller */
  49587. comp_ctx->lex.slot1_idx = comp_ctx->tok11_idx;
  49588. comp_ctx->lex.slot2_idx = comp_ctx->tok12_idx;
  49589. comp_ctx->lex.buf_idx = entry_top + 0;
  49590. comp_ctx->lex.buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, entry_top + 0);
  49591. DUK_ASSERT(comp_ctx->lex.buf != NULL);
  49592. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(comp_ctx->lex.buf));
  49593. comp_ctx->lex.token_limit = DUK_COMPILER_TOKEN_LIMIT;
  49594. lex_pt->offset = 0;
  49595. lex_pt->line = 1;
  49596. DUK_LEXER_SETPOINT(&comp_ctx->lex, lex_pt); /* fills window */
  49597. comp_ctx->curr_token.start_line = 0; /* needed for line number tracking (becomes prev_token.start_line) */
  49598. /*
  49599. * Initialize function state for a zero-argument function
  49600. */
  49601. duk__init_func_valstack_slots(comp_ctx);
  49602. DUK_ASSERT(func->num_formals == 0);
  49603. if (is_funcexpr) {
  49604. /* Name will be filled from function expression, not by caller.
  49605. * This case is used by Function constructor and duk_compile()
  49606. * API with the DUK_COMPILE_FUNCTION option.
  49607. */
  49608. DUK_ASSERT(func->h_name == NULL);
  49609. } else {
  49610. duk_push_hstring_stridx(ctx, (is_eval ? DUK_STRIDX_EVAL :
  49611. DUK_STRIDX_GLOBAL));
  49612. func->h_name = duk_get_hstring(ctx, -1);
  49613. }
  49614. /*
  49615. * Parse a function body or a function-like expression, depending
  49616. * on flags.
  49617. */
  49618. func->is_strict = is_strict;
  49619. func->is_setget = 0;
  49620. func->is_decl = 0;
  49621. if (is_funcexpr) {
  49622. func->is_function = 1;
  49623. func->is_eval = 0;
  49624. func->is_global = 0;
  49625. duk__advance(comp_ctx); /* init 'curr_token' */
  49626. duk__advance_expect(comp_ctx, DUK_TOK_FUNCTION);
  49627. (void) duk__parse_func_like_raw(comp_ctx,
  49628. 0, /* is_decl */
  49629. 0); /* is_setget */
  49630. } else {
  49631. func->is_function = 0;
  49632. func->is_eval = is_eval;
  49633. func->is_global = !is_eval;
  49634. duk__parse_func_body(comp_ctx,
  49635. 1, /* expect_eof */
  49636. 1, /* implicit_return_value */
  49637. -1); /* expect_token */
  49638. }
  49639. /*
  49640. * Convert duk_compiler_func to a function template
  49641. */
  49642. duk__convert_to_func_template(comp_ctx, 0 /*force_no_namebind*/);
  49643. /*
  49644. * Wrapping duk_safe_call() will mangle the stack, just return stack top
  49645. */
  49646. /* [ ... filename (temps) func ] */
  49647. return 1;
  49648. }
  49649. DUK_INTERNAL void duk_js_compile(duk_hthread *thr, const duk_uint8_t *src_buffer, duk_size_t src_length, duk_small_uint_t flags) {
  49650. duk_context *ctx = (duk_context *) thr;
  49651. duk__compiler_stkstate comp_stk;
  49652. duk_compiler_ctx *prev_ctx;
  49653. duk_ret_t safe_rc;
  49654. /* XXX: this illustrates that a C catchpoint implemented using duk_safe_call()
  49655. * is a bit heavy at the moment. The wrapper compiles to ~180 bytes on x64.
  49656. * Alternatives would be nice.
  49657. */
  49658. DUK_ASSERT(thr != NULL);
  49659. DUK_ASSERT(src_buffer != NULL);
  49660. /* preinitialize lexer state partially */
  49661. DUK_MEMZERO(&comp_stk, sizeof(comp_stk));
  49662. comp_stk.flags = flags;
  49663. DUK_LEXER_INITCTX(&comp_stk.comp_ctx_alloc.lex);
  49664. comp_stk.comp_ctx_alloc.lex.input = src_buffer;
  49665. comp_stk.comp_ctx_alloc.lex.input_length = src_length;
  49666. duk_push_pointer(ctx, (void *) &comp_stk);
  49667. /* [ ... filename &comp_stk ] */
  49668. prev_ctx = thr->compile_ctx;
  49669. thr->compile_ctx = &comp_stk.comp_ctx_alloc; /* for duk_error_augment.c */
  49670. safe_rc = duk_safe_call(ctx, duk__js_compile_raw, 2 /*nargs*/, 1 /*nret*/);
  49671. thr->compile_ctx = prev_ctx;
  49672. if (safe_rc != DUK_EXEC_SUCCESS) {
  49673. /* Append a "(line NNN)" to the "message" property of any
  49674. * error thrown during compilation. Usually compilation
  49675. * errors are SyntaxErrors but they can also be out-of-memory
  49676. * errors and the like.
  49677. *
  49678. * Source file/line are added to tracedata directly by
  49679. * duk_error_augment.c based on thr->compile_ctx.
  49680. */
  49681. /* [ ... error ] */
  49682. DUK_DDD(DUK_DDDPRINT("compile error, before adding line info: %!T",
  49683. (duk_tval *) duk_get_tval(ctx, -1)));
  49684. if (duk_is_object(ctx, -1)) {
  49685. /* XXX: Now that fileName and lineNumber are set, this is
  49686. * unnecessary. Remove in Duktape 1.3.0?
  49687. */
  49688. if (duk_get_prop_stridx(ctx, -1, DUK_STRIDX_MESSAGE)) {
  49689. duk_push_sprintf(ctx, " (line %ld)", (long) comp_stk.comp_ctx_alloc.curr_token.start_line);
  49690. duk_concat(ctx, 2);
  49691. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_MESSAGE);
  49692. } else {
  49693. duk_pop(ctx);
  49694. }
  49695. }
  49696. DUK_DDD(DUK_DDDPRINT("compile error, after adding line info: %!T",
  49697. (duk_tval *) duk_get_tval(ctx, -1)));
  49698. duk_throw(ctx);
  49699. }
  49700. /* [ ... template ] */
  49701. }
  49702. #line 1 "duk_js_executor.c"
  49703. /*
  49704. * Ecmascript bytecode executor.
  49705. */
  49706. /* include removed: duk_internal.h */
  49707. /*
  49708. * Local forward declarations
  49709. */
  49710. DUK_LOCAL_DECL void duk__reconfig_valstack(duk_hthread *thr, duk_size_t act_idx, duk_small_uint_t retval_count);
  49711. /*
  49712. * Arithmetic, binary, and logical helpers.
  49713. *
  49714. * Note: there is no opcode for logical AND or logical OR; this is on
  49715. * purpose, because the evalution order semantics for them make such
  49716. * opcodes pretty pointless (short circuiting means they are most
  49717. * comfortably implemented as jumps). However, a logical NOT opcode
  49718. * is useful.
  49719. *
  49720. * Note: careful with duk_tval pointers here: they are potentially
  49721. * invalidated by any DECREF and almost any API call.
  49722. */
  49723. DUK_LOCAL duk_double_t duk__compute_mod(duk_double_t d1, duk_double_t d2) {
  49724. /*
  49725. * Ecmascript modulus ('%') does not match IEEE 754 "remainder"
  49726. * operation (implemented by remainder() in C99) but does seem
  49727. * to match ANSI C fmod().
  49728. *
  49729. * Compare E5 Section 11.5.3 and "man fmod".
  49730. */
  49731. return (duk_double_t) DUK_FMOD((double) d1, (double) d2);
  49732. }
  49733. DUK_LOCAL void duk__vm_arith_add(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y, duk_small_uint_fast_t idx_z) {
  49734. /*
  49735. * Addition operator is different from other arithmetic
  49736. * operations in that it also provides string concatenation.
  49737. * Hence it is implemented separately.
  49738. *
  49739. * There is a fast path for number addition. Other cases go
  49740. * through potentially multiple coercions as described in the
  49741. * E5 specification. It may be possible to reduce the number
  49742. * of coercions, but this must be done carefully to preserve
  49743. * the exact semantics.
  49744. *
  49745. * E5 Section 11.6.1.
  49746. *
  49747. * Custom types also have special behavior implemented here.
  49748. */
  49749. duk_context *ctx = (duk_context *) thr;
  49750. duk_double_union du;
  49751. DUK_ASSERT(thr != NULL);
  49752. DUK_ASSERT(ctx != NULL);
  49753. DUK_ASSERT(tv_x != NULL); /* may be reg or const */
  49754. DUK_ASSERT(tv_y != NULL); /* may be reg or const */
  49755. DUK_ASSERT_DISABLE(idx_z >= 0); /* unsigned */
  49756. DUK_ASSERT((duk_uint_t) idx_z < (duk_uint_t) duk_get_top(ctx));
  49757. /*
  49758. * Fast paths
  49759. */
  49760. #if defined(DUK_USE_FASTINT)
  49761. if (DUK_TVAL_IS_FASTINT(tv_x) && DUK_TVAL_IS_FASTINT(tv_y)) {
  49762. duk_int64_t v1, v2, v3;
  49763. duk_int32_t v3_hi;
  49764. duk_tval tv_tmp;
  49765. duk_tval *tv_z;
  49766. /* Input values are signed 48-bit so we can detect overflow
  49767. * reliably from high bits or just a comparison.
  49768. */
  49769. v1 = DUK_TVAL_GET_FASTINT(tv_x);
  49770. v2 = DUK_TVAL_GET_FASTINT(tv_y);
  49771. v3 = v1 + v2;
  49772. v3_hi = (duk_int32_t) (v3 >> 32);
  49773. if (DUK_LIKELY(v3_hi >= -0x8000LL && v3_hi <= 0x7fffLL)) {
  49774. tv_z = thr->valstack_bottom + idx_z;
  49775. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  49776. DUK_TVAL_SET_FASTINT(tv_z, v3);
  49777. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  49778. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  49779. return;
  49780. } else {
  49781. /* overflow, fall through */
  49782. ;
  49783. }
  49784. }
  49785. #endif /* DUK_USE_FASTINT */
  49786. if (DUK_TVAL_IS_NUMBER(tv_x) && DUK_TVAL_IS_NUMBER(tv_y)) {
  49787. duk_tval tv_tmp;
  49788. duk_tval *tv_z;
  49789. du.d = DUK_TVAL_GET_NUMBER(tv_x) + DUK_TVAL_GET_NUMBER(tv_y);
  49790. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&du);
  49791. DUK_ASSERT(DUK_DBLUNION_IS_NORMALIZED(&du));
  49792. tv_z = thr->valstack_bottom + idx_z;
  49793. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  49794. DUK_TVAL_SET_NUMBER(tv_z, du.d);
  49795. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  49796. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  49797. return;
  49798. }
  49799. /*
  49800. * Slow path: potentially requires function calls for coercion
  49801. */
  49802. duk_push_tval(ctx, tv_x);
  49803. duk_push_tval(ctx, tv_y);
  49804. duk_to_primitive(ctx, -2, DUK_HINT_NONE); /* side effects -> don't use tv_x, tv_y after */
  49805. duk_to_primitive(ctx, -1, DUK_HINT_NONE);
  49806. /* As a first approximation, buffer values are coerced to strings
  49807. * for addition. This means that adding two buffers currently
  49808. * results in a string.
  49809. */
  49810. if (duk_check_type_mask(ctx, -2, DUK_TYPE_MASK_STRING | DUK_TYPE_MASK_BUFFER) ||
  49811. duk_check_type_mask(ctx, -1, DUK_TYPE_MASK_STRING | DUK_TYPE_MASK_BUFFER)) {
  49812. duk_to_string(ctx, -2);
  49813. duk_to_string(ctx, -1);
  49814. duk_concat(ctx, 2); /* [... s1 s2] -> [... s1+s2] */
  49815. duk_replace(ctx, (duk_idx_t) idx_z); /* side effects */
  49816. } else {
  49817. duk_double_t d1, d2;
  49818. d1 = duk_to_number(ctx, -2);
  49819. d2 = duk_to_number(ctx, -1);
  49820. DUK_ASSERT(duk_is_number(ctx, -2));
  49821. DUK_ASSERT(duk_is_number(ctx, -1));
  49822. DUK_ASSERT_DOUBLE_IS_NORMALIZED(d1);
  49823. DUK_ASSERT_DOUBLE_IS_NORMALIZED(d2);
  49824. du.d = d1 + d2;
  49825. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&du);
  49826. DUK_ASSERT(DUK_DBLUNION_IS_NORMALIZED(&du));
  49827. duk_pop_2(ctx);
  49828. duk_push_number(ctx, du.d);
  49829. duk_replace(ctx, (duk_idx_t) idx_z); /* side effects */
  49830. }
  49831. }
  49832. DUK_LOCAL void duk__vm_arith_binary_op(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y, duk_idx_t idx_z, duk_small_uint_fast_t opcode) {
  49833. /*
  49834. * Arithmetic operations other than '+' have number-only semantics
  49835. * and are implemented here. The separate switch-case here means a
  49836. * "double dispatch" of the arithmetic opcode, but saves code space.
  49837. *
  49838. * E5 Sections 11.5, 11.5.1, 11.5.2, 11.5.3, 11.6, 11.6.1, 11.6.2, 11.6.3.
  49839. */
  49840. duk_context *ctx = (duk_context *) thr;
  49841. duk_tval tv_tmp;
  49842. duk_tval *tv_z;
  49843. duk_double_t d1, d2;
  49844. duk_double_union du;
  49845. DUK_ASSERT(thr != NULL);
  49846. DUK_ASSERT(ctx != NULL);
  49847. DUK_ASSERT(tv_x != NULL); /* may be reg or const */
  49848. DUK_ASSERT(tv_y != NULL); /* may be reg or const */
  49849. DUK_ASSERT_DISABLE(idx_z >= 0); /* unsigned */
  49850. DUK_ASSERT((duk_uint_t) idx_z < (duk_uint_t) duk_get_top(ctx));
  49851. #if defined(DUK_USE_FASTINT)
  49852. if (DUK_TVAL_IS_FASTINT(tv_x) && DUK_TVAL_IS_FASTINT(tv_y)) {
  49853. duk_int64_t v1, v2, v3;
  49854. duk_int32_t v3_hi;
  49855. v1 = DUK_TVAL_GET_FASTINT(tv_x);
  49856. v2 = DUK_TVAL_GET_FASTINT(tv_y);
  49857. switch (opcode) {
  49858. case DUK_OP_SUB: {
  49859. v3 = v1 - v2;
  49860. break;
  49861. }
  49862. case DUK_OP_MUL: {
  49863. /* Must ensure result is 64-bit (no overflow); a
  49864. * simple and sufficient fast path is to allow only
  49865. * 32-bit inputs. Avoid zero inputs to avoid
  49866. * negative zero issues (-1 * 0 = -0, for instance).
  49867. */
  49868. if (v1 >= -0x80000000LL && v1 <= 0x7fffffffLL && v1 != 0 &&
  49869. v2 >= -0x80000000LL && v2 <= 0x7fffffffLL && v2 != 0) {
  49870. v3 = v1 * v2;
  49871. } else {
  49872. goto skip_fastint;
  49873. }
  49874. break;
  49875. }
  49876. case DUK_OP_DIV: {
  49877. /* Don't allow a zero divisor. Fast path check by
  49878. * "verifying" with multiplication. Also avoid zero
  49879. * dividend to avoid negative zero issues (0 / -1 = -0
  49880. * for instance).
  49881. */
  49882. if (v1 == 0 || v2 == 0) {
  49883. goto skip_fastint;
  49884. }
  49885. v3 = v1 / v2;
  49886. if (v3 * v2 != v1) {
  49887. goto skip_fastint;
  49888. }
  49889. break;
  49890. }
  49891. case DUK_OP_MOD: {
  49892. /* Don't allow a zero divisor. Restrict both v1 and
  49893. * v2 to positive values to avoid compiler specific
  49894. * behavior.
  49895. */
  49896. if (v1 < 1 || v2 < 1) {
  49897. goto skip_fastint;
  49898. }
  49899. v3 = v1 % v2;
  49900. DUK_ASSERT(v3 >= 0);
  49901. DUK_ASSERT(v3 < v2);
  49902. DUK_ASSERT(v1 - (v1 / v2) * v2 == v3);
  49903. break;
  49904. }
  49905. default: {
  49906. DUK_UNREACHABLE();
  49907. goto skip_fastint;
  49908. }
  49909. }
  49910. v3_hi = (duk_int32_t) (v3 >> 32);
  49911. if (DUK_LIKELY(v3_hi >= -0x8000LL && v3_hi <= 0x7fffLL)) {
  49912. tv_z = thr->valstack_bottom + idx_z;
  49913. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  49914. DUK_TVAL_SET_FASTINT(tv_z, v3);
  49915. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  49916. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  49917. return;
  49918. }
  49919. /* fall through if overflow etc */
  49920. }
  49921. skip_fastint:
  49922. #endif /* DUK_USE_FASTINT */
  49923. if (DUK_TVAL_IS_NUMBER(tv_x) && DUK_TVAL_IS_NUMBER(tv_y)) {
  49924. /* fast path */
  49925. d1 = DUK_TVAL_GET_NUMBER(tv_x);
  49926. d2 = DUK_TVAL_GET_NUMBER(tv_y);
  49927. } else {
  49928. duk_push_tval(ctx, tv_x);
  49929. duk_push_tval(ctx, tv_y);
  49930. d1 = duk_to_number(ctx, -2); /* side effects */
  49931. d2 = duk_to_number(ctx, -1);
  49932. DUK_ASSERT(duk_is_number(ctx, -2));
  49933. DUK_ASSERT(duk_is_number(ctx, -1));
  49934. DUK_ASSERT_DOUBLE_IS_NORMALIZED(d1);
  49935. DUK_ASSERT_DOUBLE_IS_NORMALIZED(d2);
  49936. duk_pop_2(ctx);
  49937. }
  49938. switch (opcode) {
  49939. case DUK_OP_SUB: {
  49940. du.d = d1 - d2;
  49941. break;
  49942. }
  49943. case DUK_OP_MUL: {
  49944. du.d = d1 * d2;
  49945. break;
  49946. }
  49947. case DUK_OP_DIV: {
  49948. du.d = d1 / d2;
  49949. break;
  49950. }
  49951. case DUK_OP_MOD: {
  49952. du.d = duk__compute_mod(d1, d2);
  49953. break;
  49954. }
  49955. default: {
  49956. DUK_UNREACHABLE();
  49957. du.d = DUK_DOUBLE_NAN; /* should not happen */
  49958. break;
  49959. }
  49960. }
  49961. /* important to use normalized NaN with 8-byte tagged types */
  49962. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&du);
  49963. DUK_ASSERT(DUK_DBLUNION_IS_NORMALIZED(&du));
  49964. tv_z = thr->valstack_bottom + idx_z;
  49965. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  49966. DUK_TVAL_SET_NUMBER(tv_z, du.d);
  49967. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  49968. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  49969. }
  49970. DUK_LOCAL void duk__vm_bitwise_binary_op(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y, duk_small_uint_fast_t idx_z, duk_small_uint_fast_t opcode) {
  49971. /*
  49972. * Binary bitwise operations use different coercions (ToInt32, ToUint32)
  49973. * depending on the operation. We coerce the arguments first using
  49974. * ToInt32(), and then cast to an 32-bit value if necessary. Note that
  49975. * such casts must be correct even if there is no native 32-bit type
  49976. * (e.g., duk_int32_t and duk_uint32_t are 64-bit).
  49977. *
  49978. * E5 Sections 11.10, 11.7.1, 11.7.2, 11.7.3
  49979. */
  49980. duk_context *ctx = (duk_context *) thr;
  49981. duk_tval tv_tmp;
  49982. duk_tval *tv_z;
  49983. duk_int32_t i1, i2, i3;
  49984. duk_uint32_t u1, u2, u3;
  49985. #if defined(DUK_USE_FASTINT)
  49986. duk_int64_t fi3;
  49987. #else
  49988. duk_double_t d3;
  49989. #endif
  49990. DUK_ASSERT(thr != NULL);
  49991. DUK_ASSERT(ctx != NULL);
  49992. DUK_ASSERT(tv_x != NULL); /* may be reg or const */
  49993. DUK_ASSERT(tv_y != NULL); /* may be reg or const */
  49994. DUK_ASSERT_DISABLE(idx_z >= 0); /* unsigned */
  49995. DUK_ASSERT((duk_uint_t) idx_z < (duk_uint_t) duk_get_top(ctx));
  49996. #if defined(DUK_USE_FASTINT)
  49997. if (DUK_TVAL_IS_FASTINT(tv_x) && DUK_TVAL_IS_FASTINT(tv_y)) {
  49998. i1 = (duk_int32_t) DUK_TVAL_GET_FASTINT_I32(tv_x);
  49999. i2 = (duk_int32_t) DUK_TVAL_GET_FASTINT_I32(tv_y);
  50000. }
  50001. else
  50002. #endif /* DUK_USE_FASTINT */
  50003. {
  50004. duk_push_tval(ctx, tv_x);
  50005. duk_push_tval(ctx, tv_y);
  50006. i1 = duk_to_int32(ctx, -2);
  50007. i2 = duk_to_int32(ctx, -1);
  50008. duk_pop_2(ctx);
  50009. }
  50010. switch (opcode) {
  50011. case DUK_OP_BAND: {
  50012. i3 = i1 & i2;
  50013. break;
  50014. }
  50015. case DUK_OP_BOR: {
  50016. i3 = i1 | i2;
  50017. break;
  50018. }
  50019. case DUK_OP_BXOR: {
  50020. i3 = i1 ^ i2;
  50021. break;
  50022. }
  50023. case DUK_OP_BASL: {
  50024. /* Signed shift, named "arithmetic" (asl) because the result
  50025. * is signed, e.g. 4294967295 << 1 -> -2. Note that result
  50026. * must be masked.
  50027. */
  50028. u2 = ((duk_uint32_t) i2) & 0xffffffffUL;
  50029. i3 = i1 << (u2 & 0x1f); /* E5 Section 11.7.1, steps 7 and 8 */
  50030. i3 = i3 & ((duk_int32_t) 0xffffffffUL); /* Note: left shift, should mask */
  50031. break;
  50032. }
  50033. case DUK_OP_BASR: {
  50034. /* signed shift */
  50035. u2 = ((duk_uint32_t) i2) & 0xffffffffUL;
  50036. i3 = i1 >> (u2 & 0x1f); /* E5 Section 11.7.2, steps 7 and 8 */
  50037. break;
  50038. }
  50039. case DUK_OP_BLSR: {
  50040. /* unsigned shift */
  50041. u1 = ((duk_uint32_t) i1) & 0xffffffffUL;
  50042. u2 = ((duk_uint32_t) i2) & 0xffffffffUL;
  50043. /* special result value handling */
  50044. u3 = u1 >> (u2 & 0x1f); /* E5 Section 11.7.2, steps 7 and 8 */
  50045. #if defined(DUK_USE_FASTINT)
  50046. fi3 = (duk_int64_t) u3;
  50047. goto fastint_result_set;
  50048. #else
  50049. d3 = (duk_double_t) u3;
  50050. goto result_set;
  50051. #endif
  50052. }
  50053. default: {
  50054. DUK_UNREACHABLE();
  50055. i3 = 0; /* should not happen */
  50056. break;
  50057. }
  50058. }
  50059. #if defined(DUK_USE_FASTINT)
  50060. /* Result is always fastint compatible. */
  50061. /* XXX: set 32-bit result (but must handle signed and unsigned) */
  50062. fi3 = (duk_int64_t) i3;
  50063. fastint_result_set:
  50064. tv_z = thr->valstack_bottom + idx_z;
  50065. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  50066. DUK_TVAL_SET_FASTINT(tv_z, fi3);
  50067. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  50068. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50069. #else
  50070. d3 = (duk_double_t) i3;
  50071. result_set:
  50072. DUK_ASSERT(!DUK_ISNAN(d3)); /* 'd3' is never NaN, so no need to normalize */
  50073. DUK_ASSERT_DOUBLE_IS_NORMALIZED(d3); /* always normalized */
  50074. tv_z = thr->valstack_bottom + idx_z;
  50075. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  50076. DUK_TVAL_SET_NUMBER(tv_z, d3);
  50077. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  50078. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50079. #endif
  50080. }
  50081. /* In-place unary operation. */
  50082. DUK_LOCAL void duk__vm_arith_unary_op(duk_hthread *thr, duk_tval *tv_x, duk_idx_t idx_x, duk_small_uint_fast_t opcode) {
  50083. /*
  50084. * Arithmetic operations other than '+' have number-only semantics
  50085. * and are implemented here. The separate switch-case here means a
  50086. * "double dispatch" of the arithmetic opcode, but saves code space.
  50087. *
  50088. * E5 Sections 11.5, 11.5.1, 11.5.2, 11.5.3, 11.6, 11.6.1, 11.6.2, 11.6.3.
  50089. */
  50090. duk_context *ctx = (duk_context *) thr;
  50091. duk_double_t d1;
  50092. duk_double_union du;
  50093. DUK_ASSERT(thr != NULL);
  50094. DUK_ASSERT(ctx != NULL);
  50095. DUK_ASSERT(opcode == DUK_EXTRAOP_UNM || opcode == DUK_EXTRAOP_UNP);
  50096. #if defined(DUK_USE_FASTINT)
  50097. if (DUK_TVAL_IS_FASTINT(tv_x)) {
  50098. duk_int64_t v1, v2;
  50099. v1 = DUK_TVAL_GET_FASTINT(tv_x);
  50100. if (opcode == DUK_EXTRAOP_UNM) {
  50101. /* The smallest fastint is no longer 48-bit when
  50102. * negated. Positive zero becames negative zero
  50103. * (cannot be represented) when negated.
  50104. */
  50105. if (DUK_LIKELY(v1 != DUK_FASTINT_MIN && v1 != 0)) {
  50106. v2 = -v1;
  50107. DUK_TVAL_SET_FASTINT(tv_x, v2); /* no refcount changes */
  50108. return;
  50109. }
  50110. } else {
  50111. /* ToNumber() for a fastint is a no-op. */
  50112. DUK_ASSERT(opcode == DUK_EXTRAOP_UNP);
  50113. return;
  50114. }
  50115. /* fall through if overflow etc */
  50116. }
  50117. #endif /* DUK_USE_FASTINT */
  50118. if (!DUK_TVAL_IS_NUMBER(tv_x)) {
  50119. duk_to_number(ctx, idx_x); /* side effects, perform in-place */
  50120. tv_x = duk_get_tval(ctx, idx_x);
  50121. DUK_ASSERT(tv_x != NULL);
  50122. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_x));
  50123. }
  50124. d1 = DUK_TVAL_GET_NUMBER(tv_x);
  50125. if (opcode == DUK_EXTRAOP_UNM) {
  50126. du.d = -d1;
  50127. } else {
  50128. /* ToNumber() for a double is a no-op. */
  50129. DUK_ASSERT(opcode == DUK_EXTRAOP_UNP);
  50130. du.d = d1;
  50131. }
  50132. DUK_DBLUNION_NORMALIZE_NAN_CHECK(&du); /* mandatory if du.d is a NaN */
  50133. DUK_ASSERT(DUK_DBLUNION_IS_NORMALIZED(&du));
  50134. #if defined(DUK_USE_FASTINT)
  50135. /* Unary plus is used to force a fastint check, so must include
  50136. * downgrade check.
  50137. */
  50138. DUK_TVAL_SET_NUMBER_CHKFAST(tv_x, du.d); /* no refcount changes */
  50139. #else
  50140. DUK_TVAL_SET_NUMBER(tv_x, du.d); /* no refcount changes */
  50141. #endif
  50142. }
  50143. DUK_LOCAL void duk__vm_bitwise_not(duk_hthread *thr, duk_tval *tv_x, duk_small_uint_fast_t idx_z) {
  50144. /*
  50145. * E5 Section 11.4.8
  50146. */
  50147. duk_context *ctx = (duk_context *) thr;
  50148. duk_tval tv_tmp;
  50149. duk_tval *tv_z;
  50150. duk_int32_t i1, i2;
  50151. #if !defined(DUK_USE_FASTINT)
  50152. duk_double_t d2;
  50153. #endif
  50154. DUK_ASSERT(thr != NULL);
  50155. DUK_ASSERT(ctx != NULL);
  50156. DUK_ASSERT(tv_x != NULL); /* may be reg or const */
  50157. DUK_ASSERT_DISABLE(idx_z >= 0);
  50158. DUK_ASSERT((duk_uint_t) idx_z < (duk_uint_t) duk_get_top(ctx));
  50159. #if defined(DUK_USE_FASTINT)
  50160. if (DUK_TVAL_IS_FASTINT(tv_x)) {
  50161. i1 = (duk_int32_t) DUK_TVAL_GET_FASTINT_I32(tv_x);
  50162. }
  50163. else
  50164. #endif /* DUK_USE_FASTINT */
  50165. {
  50166. duk_push_tval(ctx, tv_x);
  50167. i1 = duk_to_int32(ctx, -1);
  50168. duk_pop(ctx);
  50169. }
  50170. i2 = ~i1;
  50171. #if defined(DUK_USE_FASTINT)
  50172. /* Result is always fastint compatible. */
  50173. tv_z = thr->valstack_bottom + idx_z;
  50174. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  50175. DUK_TVAL_SET_FASTINT_I32(tv_z, i2);
  50176. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  50177. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50178. #else
  50179. d2 = (duk_double_t) i2;
  50180. DUK_ASSERT(!DUK_ISNAN(d2)); /* 'val' is never NaN, so no need to normalize */
  50181. DUK_ASSERT_DOUBLE_IS_NORMALIZED(d2); /* always normalized */
  50182. tv_z = thr->valstack_bottom + idx_z;
  50183. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  50184. DUK_TVAL_SET_NUMBER(tv_z, d2);
  50185. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv_z)); /* no need to incref */
  50186. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50187. #endif
  50188. }
  50189. DUK_LOCAL void duk__vm_logical_not(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_z) {
  50190. /*
  50191. * E5 Section 11.4.9
  50192. */
  50193. duk_tval tv_tmp;
  50194. duk_bool_t res;
  50195. DUK_ASSERT(thr != NULL);
  50196. DUK_ASSERT(tv_x != NULL); /* may be reg or const */
  50197. DUK_ASSERT(tv_z != NULL); /* reg */
  50198. DUK_UNREF(thr); /* w/o refcounts */
  50199. /* ToBoolean() does not require any operations with side effects so
  50200. * we can do it efficiently. For footprint it would be better to use
  50201. * duk_js_toboolean() and then push+replace to the result slot.
  50202. */
  50203. res = duk_js_toboolean(tv_x); /* does not modify tv_x */
  50204. DUK_ASSERT(res == 0 || res == 1);
  50205. res ^= 1;
  50206. DUK_TVAL_SET_TVAL(&tv_tmp, tv_z);
  50207. DUK_TVAL_SET_BOOLEAN(tv_z, res); /* no need to incref */
  50208. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50209. }
  50210. /*
  50211. * Longjmp handler for the bytecode executor (and a bunch of static
  50212. * helpers for it).
  50213. *
  50214. * Any type of longjmp() can be caught here, including intra-function
  50215. * longjmp()s like 'break', 'continue', (slow) 'return', 'yield', etc.
  50216. *
  50217. * Error policy: should not ordinarily throw errors. Errors thrown
  50218. * will bubble outwards.
  50219. *
  50220. * Returns:
  50221. * 0 restart execution
  50222. * 1 bytecode executor finished
  50223. * 2 rethrow longjmp
  50224. */
  50225. /* XXX: duk_api operations for cross-thread reg manipulation? */
  50226. /* XXX: post-condition: value stack must be correct; for ecmascript functions, clamped to 'nregs' */
  50227. #define DUK__LONGJMP_RESTART 0 /* state updated, restart bytecode execution */
  50228. #define DUK__LONGJMP_FINISHED 1 /* exit bytecode executor with return value */
  50229. #define DUK__LONGJMP_RETHROW 2 /* exit bytecode executor by rethrowing an error to caller */
  50230. /* only called when act_idx points to an Ecmascript function */
  50231. DUK_LOCAL void duk__reconfig_valstack(duk_hthread *thr, duk_size_t act_idx, duk_small_uint_t retval_count) {
  50232. duk_hcompiledfunction *h_func;
  50233. DUK_ASSERT(thr != NULL);
  50234. DUK_ASSERT_DISABLE(act_idx >= 0); /* unsigned */
  50235. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + act_idx) != NULL);
  50236. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + act_idx)));
  50237. DUK_ASSERT_DISABLE(thr->callstack[act_idx].idx_retval >= 0); /* unsigned */
  50238. thr->valstack_bottom = thr->valstack + thr->callstack[act_idx].idx_bottom;
  50239. /* clamp so that retval is at the top (retval_count == 1) or register just before
  50240. * intended retval is at the top (retval_count == 0, happens e.g. with 'finally').
  50241. */
  50242. duk_set_top((duk_context *) thr,
  50243. (duk_idx_t) (thr->callstack[act_idx].idx_retval -
  50244. thr->callstack[act_idx].idx_bottom +
  50245. retval_count));
  50246. /*
  50247. * When returning to an Ecmascript function, extend the valstack
  50248. * top to 'nregs' always.
  50249. */
  50250. h_func = (duk_hcompiledfunction *) DUK_ACT_GET_FUNC(thr->callstack + act_idx);
  50251. (void) duk_valstack_resize_raw((duk_context *) thr,
  50252. (thr->valstack_bottom - thr->valstack) + /* bottom of current func */
  50253. h_func->nregs + /* reg count */
  50254. DUK_VALSTACK_INTERNAL_EXTRA, /* + spare */
  50255. DUK_VSRESIZE_FLAG_SHRINK | /* flags */
  50256. 0 /* no compact */ |
  50257. DUK_VSRESIZE_FLAG_THROW);
  50258. duk_set_top((duk_context *) thr, h_func->nregs);
  50259. }
  50260. DUK_LOCAL void duk__handle_catch_or_finally(duk_hthread *thr, duk_size_t cat_idx, duk_bool_t is_finally) {
  50261. duk_context *ctx = (duk_context *) thr;
  50262. duk_tval tv_tmp;
  50263. duk_tval *tv1;
  50264. DUK_DDD(DUK_DDDPRINT("handling catch/finally, cat_idx=%ld, is_finally=%ld",
  50265. (long) cat_idx, (long) is_finally));
  50266. /*
  50267. * Set caught value and longjmp type to catcher regs.
  50268. */
  50269. DUK_DDD(DUK_DDDPRINT("writing catch registers: idx_base=%ld -> %!T, idx_base+1=%ld -> %!T",
  50270. (long) thr->catchstack[cat_idx].idx_base,
  50271. (duk_tval *) &thr->heap->lj.value1,
  50272. (long) (thr->catchstack[cat_idx].idx_base + 1),
  50273. (duk_tval *) &thr->heap->lj.value2));
  50274. tv1 = thr->valstack + thr->catchstack[cat_idx].idx_base;
  50275. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  50276. DUK_TVAL_SET_TVAL(tv1, &thr->heap->lj.value1);
  50277. DUK_TVAL_INCREF(thr, tv1);
  50278. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50279. tv1 = thr->valstack + thr->catchstack[cat_idx].idx_base + 1;
  50280. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  50281. DUK_TVAL_SET_NUMBER(tv1, (duk_double_t) thr->heap->lj.type); /* XXX: set int */
  50282. DUK_ASSERT(!DUK_TVAL_IS_HEAP_ALLOCATED(tv1)); /* no need to incref */
  50283. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50284. /*
  50285. * Unwind catchstack and callstack.
  50286. *
  50287. * The 'cat_idx' catcher is always kept, even when executing finally.
  50288. */
  50289. duk_hthread_catchstack_unwind(thr, cat_idx + 1);
  50290. duk_hthread_callstack_unwind(thr, thr->catchstack[cat_idx].callstack_index + 1);
  50291. /*
  50292. * Reconfigure valstack to 'nregs' (this is always the case for
  50293. * Ecmascript functions).
  50294. */
  50295. DUK_ASSERT(thr->callstack_top >= 1);
  50296. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1) != NULL);
  50297. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1)));
  50298. thr->valstack_bottom = thr->valstack + (thr->callstack + thr->callstack_top - 1)->idx_bottom;
  50299. duk_set_top((duk_context *) thr, ((duk_hcompiledfunction *) DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1))->nregs);
  50300. /*
  50301. * Reset PC: resume execution from catch or finally jump slot.
  50302. */
  50303. (thr->callstack + thr->callstack_top - 1)->pc =
  50304. thr->catchstack[cat_idx].pc_base + (is_finally ? 1 : 0);
  50305. /*
  50306. * If entering a 'catch' block which requires an automatic
  50307. * catch variable binding, create the lexical environment.
  50308. *
  50309. * The binding is mutable (= writable) but not deletable.
  50310. * Step 4 for the catch production in E5 Section 12.14;
  50311. * no value is given for CreateMutableBinding 'D' argument,
  50312. * which implies the binding is not deletable.
  50313. */
  50314. if (!is_finally && DUK_CAT_HAS_CATCH_BINDING_ENABLED(&thr->catchstack[cat_idx])) {
  50315. duk_activation *act;
  50316. duk_hobject *new_env;
  50317. duk_hobject *act_lex_env;
  50318. DUK_DDD(DUK_DDDPRINT("catcher has an automatic catch binding"));
  50319. /* Note: 'act' is dangerous here because it may get invalidate at many
  50320. * points, so we re-lookup it multiple times.
  50321. */
  50322. DUK_ASSERT(thr->callstack_top >= 1);
  50323. act = thr->callstack + thr->callstack_top - 1;
  50324. if (act->lex_env == NULL) {
  50325. DUK_ASSERT(act->var_env == NULL);
  50326. DUK_DDD(DUK_DDDPRINT("delayed environment initialization"));
  50327. /* this may have side effects, so re-lookup act */
  50328. duk_js_init_activation_environment_records_delayed(thr, act);
  50329. act = thr->callstack + thr->callstack_top - 1;
  50330. }
  50331. DUK_ASSERT(act->lex_env != NULL);
  50332. DUK_ASSERT(act->var_env != NULL);
  50333. DUK_ASSERT(DUK_ACT_GET_FUNC(act) != NULL);
  50334. DUK_UNREF(act); /* unreferenced without assertions */
  50335. act = thr->callstack + thr->callstack_top - 1;
  50336. act_lex_env = act->lex_env;
  50337. act = NULL; /* invalidated */
  50338. (void) duk_push_object_helper_proto(ctx,
  50339. DUK_HOBJECT_FLAG_EXTENSIBLE |
  50340. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_DECENV),
  50341. act_lex_env);
  50342. new_env = duk_require_hobject(ctx, -1);
  50343. DUK_ASSERT(new_env != NULL);
  50344. DUK_DDD(DUK_DDDPRINT("new_env allocated: %!iO", (duk_heaphdr *) new_env));
  50345. /* Note: currently the catch binding is handled without a register
  50346. * binding because we don't support dynamic register bindings (they
  50347. * must be fixed for an entire function). So, there is no need to
  50348. * record regbases etc.
  50349. */
  50350. DUK_ASSERT(thr->catchstack[cat_idx].h_varname != NULL);
  50351. duk_push_hstring(ctx, thr->catchstack[cat_idx].h_varname);
  50352. duk_push_tval(ctx, &thr->heap->lj.value1);
  50353. duk_xdef_prop(ctx, -3, DUK_PROPDESC_FLAGS_W); /* writable, not configurable */
  50354. act = thr->callstack + thr->callstack_top - 1;
  50355. act->lex_env = new_env;
  50356. DUK_HOBJECT_INCREF(thr, new_env); /* reachable through activation */
  50357. DUK_CAT_SET_LEXENV_ACTIVE(&thr->catchstack[cat_idx]);
  50358. duk_pop(ctx);
  50359. DUK_DDD(DUK_DDDPRINT("new_env finished: %!iO", (duk_heaphdr *) new_env));
  50360. }
  50361. if (is_finally) {
  50362. DUK_CAT_CLEAR_FINALLY_ENABLED(&thr->catchstack[cat_idx]);
  50363. } else {
  50364. DUK_CAT_CLEAR_CATCH_ENABLED(&thr->catchstack[cat_idx]);
  50365. }
  50366. }
  50367. DUK_LOCAL void duk__handle_label(duk_hthread *thr, duk_size_t cat_idx) {
  50368. duk_activation *act;
  50369. /* no callstack changes, no value stack changes */
  50370. DUK_ASSERT(thr != NULL);
  50371. DUK_ASSERT(thr->callstack_top >= 1);
  50372. act = thr->callstack + thr->callstack_top - 1;
  50373. DUK_ASSERT(DUK_ACT_GET_FUNC(act) != NULL);
  50374. DUK_ASSERT(DUK_HOBJECT_HAS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(act)));
  50375. /* +0 = break, +1 = continue */
  50376. act->pc = thr->catchstack[cat_idx].pc_base + (thr->heap->lj.type == DUK_LJ_TYPE_CONTINUE ? 1 : 0);
  50377. act = NULL; /* invalidated */
  50378. duk_hthread_catchstack_unwind(thr, cat_idx + 1); /* keep label catcher */
  50379. /* no need to unwind callstack */
  50380. /* valstack should not need changes */
  50381. #if defined(DUK_USE_ASSERTIONS)
  50382. act = thr->callstack + thr->callstack_top - 1;
  50383. DUK_ASSERT((duk_size_t) (thr->valstack_top - thr->valstack_bottom) ==
  50384. (duk_size_t) ((duk_hcompiledfunction *) DUK_ACT_GET_FUNC(act))->nregs);
  50385. #endif
  50386. }
  50387. /* Note: called for DUK_LJ_TYPE_YIELD and for DUK_LJ_TYPE_RETURN, when a
  50388. * return terminates a thread and yields to the resumer.
  50389. */
  50390. DUK_LOCAL void duk__handle_yield(duk_hthread *thr, duk_hthread *resumer, duk_size_t act_idx) {
  50391. duk_tval tv_tmp;
  50392. duk_tval *tv1;
  50393. /* this may also be called for DUK_LJ_TYPE_RETURN; this is OK as long as
  50394. * lj.value1 is correct.
  50395. */
  50396. DUK_ASSERT(DUK_ACT_GET_FUNC(resumer->callstack + act_idx) != NULL);
  50397. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(resumer->callstack + act_idx))); /* resume caller must be an ecmascript func */
  50398. DUK_DDD(DUK_DDDPRINT("resume idx_retval is %ld", (long) resumer->callstack[act_idx].idx_retval));
  50399. tv1 = resumer->valstack + resumer->callstack[act_idx].idx_retval; /* return value from Duktape.Thread.resume() */
  50400. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  50401. DUK_TVAL_SET_TVAL(tv1, &thr->heap->lj.value1);
  50402. DUK_TVAL_INCREF(thr, tv1);
  50403. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50404. duk_hthread_callstack_unwind(resumer, act_idx + 1); /* unwind to 'resume' caller */
  50405. /* no need to unwind catchstack */
  50406. duk__reconfig_valstack(resumer, act_idx, 1); /* 1 = have retval */
  50407. /* caller must change active thread, and set thr->resumer to NULL */
  50408. }
  50409. DUK_LOCAL
  50410. duk_small_uint_t duk__handle_longjmp(duk_hthread *thr,
  50411. duk_hthread *entry_thread,
  50412. duk_size_t entry_callstack_top) {
  50413. duk_tval tv_tmp;
  50414. duk_size_t entry_callstack_index;
  50415. duk_small_uint_t retval = DUK__LONGJMP_RESTART;
  50416. DUK_ASSERT(thr != NULL);
  50417. DUK_ASSERT(entry_thread != NULL);
  50418. DUK_ASSERT(entry_callstack_top > 0); /* guarantees entry_callstack_top - 1 >= 0 */
  50419. entry_callstack_index = entry_callstack_top - 1;
  50420. /* 'thr' is the current thread, as no-one resumes except us and we
  50421. * switch 'thr' in that case.
  50422. */
  50423. /*
  50424. * (Re)try handling the longjmp.
  50425. *
  50426. * A longjmp handler may convert the longjmp to a different type and
  50427. * "virtually" rethrow by goto'ing to 'check_longjmp'. Before the goto,
  50428. * the following must be updated:
  50429. * - the heap 'lj' state
  50430. * - 'thr' must reflect the "throwing" thread
  50431. */
  50432. check_longjmp:
  50433. DUK_DD(DUK_DDPRINT("handling longjmp: type=%ld, value1=%!T, value2=%!T, iserror=%ld",
  50434. (long) thr->heap->lj.type,
  50435. (duk_tval *) &thr->heap->lj.value1,
  50436. (duk_tval *) &thr->heap->lj.value2,
  50437. (long) thr->heap->lj.iserror));
  50438. switch (thr->heap->lj.type) {
  50439. case DUK_LJ_TYPE_RESUME: {
  50440. /*
  50441. * Note: lj.value1 is 'value', lj.value2 is 'resumee'.
  50442. * This differs from YIELD.
  50443. */
  50444. duk_tval *tv;
  50445. duk_tval *tv2;
  50446. duk_size_t act_idx;
  50447. duk_hthread *resumee;
  50448. /* duk_bi_duk_object_yield() and duk_bi_duk_object_resume() ensure all of these are met */
  50449. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_RUNNING); /* unchanged by Duktape.Thread.resume() */
  50450. DUK_ASSERT(thr->callstack_top >= 2); /* Ecmascript activation + Duktape.Thread.resume() activation */
  50451. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1) != NULL &&
  50452. DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1)) &&
  50453. ((duk_hnativefunction *) DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1))->func == duk_bi_thread_resume);
  50454. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2) != NULL &&
  50455. DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2))); /* an Ecmascript function */
  50456. DUK_ASSERT_DISABLE((thr->callstack + thr->callstack_top - 2)->idx_retval >= 0); /* unsigned */
  50457. tv = &thr->heap->lj.value2; /* resumee */
  50458. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  50459. DUK_ASSERT(DUK_TVAL_GET_OBJECT(tv) != NULL);
  50460. DUK_ASSERT(DUK_HOBJECT_IS_THREAD(DUK_TVAL_GET_OBJECT(tv)));
  50461. resumee = (duk_hthread *) DUK_TVAL_GET_OBJECT(tv);
  50462. DUK_ASSERT(resumee != NULL);
  50463. DUK_ASSERT(resumee->resumer == NULL);
  50464. DUK_ASSERT(resumee->state == DUK_HTHREAD_STATE_INACTIVE ||
  50465. resumee->state == DUK_HTHREAD_STATE_YIELDED); /* checked by Duktape.Thread.resume() */
  50466. DUK_ASSERT(resumee->state != DUK_HTHREAD_STATE_YIELDED ||
  50467. resumee->callstack_top >= 2); /* YIELDED: Ecmascript activation + Duktape.Thread.yield() activation */
  50468. DUK_ASSERT(resumee->state != DUK_HTHREAD_STATE_YIELDED ||
  50469. (DUK_ACT_GET_FUNC(resumee->callstack + resumee->callstack_top - 1) != NULL &&
  50470. DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(resumee->callstack + resumee->callstack_top - 1)) &&
  50471. ((duk_hnativefunction *) DUK_ACT_GET_FUNC(resumee->callstack + resumee->callstack_top - 1))->func == duk_bi_thread_yield));
  50472. DUK_ASSERT(resumee->state != DUK_HTHREAD_STATE_YIELDED ||
  50473. (DUK_ACT_GET_FUNC(resumee->callstack + resumee->callstack_top - 2) != NULL &&
  50474. DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(resumee->callstack + resumee->callstack_top - 2)))); /* an Ecmascript function */
  50475. DUK_ASSERT_DISABLE(resumee->state != DUK_HTHREAD_STATE_YIELDED ||
  50476. (resumee->callstack + resumee->callstack_top - 2)->idx_retval >= 0); /* idx_retval unsigned */
  50477. DUK_ASSERT(resumee->state != DUK_HTHREAD_STATE_INACTIVE ||
  50478. resumee->callstack_top == 0); /* INACTIVE: no activation, single function value on valstack */
  50479. DUK_ASSERT(resumee->state != DUK_HTHREAD_STATE_INACTIVE ||
  50480. (resumee->valstack_top == resumee->valstack + 1 &&
  50481. DUK_TVAL_IS_OBJECT(resumee->valstack_top - 1) &&
  50482. DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_TVAL_GET_OBJECT(resumee->valstack_top - 1))));
  50483. if (thr->heap->lj.iserror) {
  50484. /*
  50485. * Throw the error in the resumed thread's context; the
  50486. * error value is pushed onto the resumee valstack.
  50487. *
  50488. * Note: the callstack of the target may empty in this case
  50489. * too (i.e. the target thread has never been resumed). The
  50490. * value stack will contain the initial function in that case,
  50491. * which we simply ignore.
  50492. */
  50493. resumee->resumer = thr;
  50494. resumee->state = DUK_HTHREAD_STATE_RUNNING;
  50495. thr->state = DUK_HTHREAD_STATE_RESUMED;
  50496. DUK_HEAP_SWITCH_THREAD(thr->heap, resumee);
  50497. thr = resumee;
  50498. thr->heap->lj.type = DUK_LJ_TYPE_THROW;
  50499. /* thr->heap->lj.value1 is already the value to throw */
  50500. /* thr->heap->lj.value2 is 'thread', will be wiped out at the end */
  50501. DUK_ASSERT(thr->heap->lj.iserror); /* already set */
  50502. DUK_DD(DUK_DDPRINT("-> resume with an error, converted to a throw in the resumee, propagate"));
  50503. goto check_longjmp;
  50504. } else if (resumee->state == DUK_HTHREAD_STATE_YIELDED) {
  50505. act_idx = resumee->callstack_top - 2; /* Ecmascript function */
  50506. DUK_ASSERT_DISABLE(resumee->callstack[act_idx].idx_retval >= 0); /* unsigned */
  50507. tv = resumee->valstack + resumee->callstack[act_idx].idx_retval; /* return value from Duktape.Thread.yield() */
  50508. DUK_ASSERT(tv >= resumee->valstack && tv < resumee->valstack_top);
  50509. tv2 = &thr->heap->lj.value1;
  50510. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  50511. DUK_TVAL_SET_TVAL(tv, tv2);
  50512. DUK_TVAL_INCREF(thr, tv);
  50513. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50514. duk_hthread_callstack_unwind(resumee, act_idx + 1); /* unwind to 'yield' caller */
  50515. /* no need to unwind catchstack */
  50516. duk__reconfig_valstack(resumee, act_idx, 1); /* 1 = have retval */
  50517. resumee->resumer = thr;
  50518. resumee->state = DUK_HTHREAD_STATE_RUNNING;
  50519. thr->state = DUK_HTHREAD_STATE_RESUMED;
  50520. DUK_HEAP_SWITCH_THREAD(thr->heap, resumee);
  50521. #if 0
  50522. thr = resumee; /* not needed, as we exit right away */
  50523. #endif
  50524. DUK_DD(DUK_DDPRINT("-> resume with a value, restart execution in resumee"));
  50525. retval = DUK__LONGJMP_RESTART;
  50526. goto wipe_and_return;
  50527. } else {
  50528. duk_small_uint_t call_flags;
  50529. duk_bool_t setup_rc;
  50530. /* resumee: [... initial_func] (currently actually: [initial_func]) */
  50531. duk_push_undefined((duk_context *) resumee);
  50532. tv = &thr->heap->lj.value1;
  50533. duk_push_tval((duk_context *) resumee, tv);
  50534. /* resumee: [... initial_func undefined(= this) resume_value ] */
  50535. call_flags = DUK_CALL_FLAG_IS_RESUME; /* is resume, not a tailcall */
  50536. setup_rc = duk_handle_ecma_call_setup(resumee,
  50537. 1, /* num_stack_args */
  50538. call_flags); /* call_flags */
  50539. if (setup_rc == 0) {
  50540. /* Shouldn't happen but check anyway. */
  50541. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR);
  50542. }
  50543. resumee->resumer = thr;
  50544. resumee->state = DUK_HTHREAD_STATE_RUNNING;
  50545. thr->state = DUK_HTHREAD_STATE_RESUMED;
  50546. DUK_HEAP_SWITCH_THREAD(thr->heap, resumee);
  50547. #if 0
  50548. thr = resumee; /* not needed, as we exit right away */
  50549. #endif
  50550. DUK_DD(DUK_DDPRINT("-> resume with a value, restart execution in resumee"));
  50551. retval = DUK__LONGJMP_RESTART;
  50552. goto wipe_and_return;
  50553. }
  50554. DUK_UNREACHABLE();
  50555. break; /* never here */
  50556. }
  50557. case DUK_LJ_TYPE_YIELD: {
  50558. /*
  50559. * Currently only allowed only if yielding thread has only
  50560. * Ecmascript activations (except for the Duktape.Thread.yield()
  50561. * call at the callstack top) and none of them constructor
  50562. * calls.
  50563. *
  50564. * This excludes the 'entry' thread which will always have
  50565. * a preventcount > 0.
  50566. */
  50567. duk_hthread *resumer;
  50568. /* duk_bi_duk_object_yield() and duk_bi_duk_object_resume() ensure all of these are met */
  50569. DUK_ASSERT(thr != entry_thread); /* Duktape.Thread.yield() should prevent */
  50570. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_RUNNING); /* unchanged from Duktape.Thread.yield() */
  50571. DUK_ASSERT(thr->callstack_top >= 2); /* Ecmascript activation + Duktape.Thread.yield() activation */
  50572. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1) != NULL &&
  50573. DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1)) &&
  50574. ((duk_hnativefunction *) DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1))->func == duk_bi_thread_yield);
  50575. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2) != NULL &&
  50576. DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2))); /* an Ecmascript function */
  50577. DUK_ASSERT_DISABLE((thr->callstack + thr->callstack_top - 2)->idx_retval >= 0); /* unsigned */
  50578. resumer = thr->resumer;
  50579. DUK_ASSERT(resumer != NULL);
  50580. DUK_ASSERT(resumer->state == DUK_HTHREAD_STATE_RESUMED); /* written by a previous RESUME handling */
  50581. DUK_ASSERT(resumer->callstack_top >= 2); /* Ecmascript activation + Duktape.Thread.resume() activation */
  50582. DUK_ASSERT(DUK_ACT_GET_FUNC(resumer->callstack + resumer->callstack_top - 1) != NULL &&
  50583. DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(resumer->callstack + resumer->callstack_top - 1)) &&
  50584. ((duk_hnativefunction *) DUK_ACT_GET_FUNC(resumer->callstack + resumer->callstack_top - 1))->func == duk_bi_thread_resume);
  50585. DUK_ASSERT(DUK_ACT_GET_FUNC(resumer->callstack + resumer->callstack_top - 2) != NULL &&
  50586. DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(resumer->callstack + resumer->callstack_top - 2))); /* an Ecmascript function */
  50587. DUK_ASSERT_DISABLE((resumer->callstack + resumer->callstack_top - 2)->idx_retval >= 0); /* unsigned */
  50588. if (thr->heap->lj.iserror) {
  50589. thr->state = DUK_HTHREAD_STATE_YIELDED;
  50590. thr->resumer = NULL;
  50591. resumer->state = DUK_HTHREAD_STATE_RUNNING;
  50592. DUK_HEAP_SWITCH_THREAD(thr->heap, resumer);
  50593. thr = resumer;
  50594. thr->heap->lj.type = DUK_LJ_TYPE_THROW;
  50595. /* lj.value1 is already set */
  50596. DUK_ASSERT(thr->heap->lj.iserror); /* already set */
  50597. DUK_DD(DUK_DDPRINT("-> yield an error, converted to a throw in the resumer, propagate"));
  50598. goto check_longjmp;
  50599. } else {
  50600. duk__handle_yield(thr, resumer, resumer->callstack_top - 2);
  50601. thr->state = DUK_HTHREAD_STATE_YIELDED;
  50602. thr->resumer = NULL;
  50603. resumer->state = DUK_HTHREAD_STATE_RUNNING;
  50604. DUK_HEAP_SWITCH_THREAD(thr->heap, resumer);
  50605. #if 0
  50606. thr = resumer; /* not needed, as we exit right away */
  50607. #endif
  50608. DUK_DD(DUK_DDPRINT("-> yield a value, restart execution in resumer"));
  50609. retval = DUK__LONGJMP_RESTART;
  50610. goto wipe_and_return;
  50611. }
  50612. DUK_UNREACHABLE();
  50613. break; /* never here */
  50614. }
  50615. case DUK_LJ_TYPE_RETURN: {
  50616. /*
  50617. * Four possible outcomes:
  50618. * * A 'finally' in the same function catches the 'return'.
  50619. * (or)
  50620. * * The return happens at the entry level of the bytecode
  50621. * executor, so return from the executor (in C stack).
  50622. * (or)
  50623. * * There is a calling (Ecmascript) activation in the call
  50624. * stack => return to it.
  50625. * (or)
  50626. * * There is no calling activation, and the thread is
  50627. * terminated. There is always a resumer in this case,
  50628. * which gets the return value similarly to a 'yield'
  50629. * (except that the current thread can no longer be
  50630. * resumed).
  50631. */
  50632. duk_tval *tv1;
  50633. duk_hthread *resumer;
  50634. duk_catcher *cat;
  50635. duk_size_t orig_callstack_index;
  50636. DUK_ASSERT(thr != NULL);
  50637. DUK_ASSERT(thr->callstack_top >= 1);
  50638. DUK_ASSERT(thr->catchstack != NULL);
  50639. /* XXX: does not work if thr->catchstack is NULL */
  50640. /* XXX: does not work if thr->catchstack is allocated but lowest pointer */
  50641. cat = thr->catchstack + thr->catchstack_top - 1; /* may be < thr->catchstack initially */
  50642. DUK_ASSERT(thr->callstack_top > 0); /* ensures callstack_top - 1 >= 0 */
  50643. orig_callstack_index = thr->callstack_top - 1;
  50644. while (cat >= thr->catchstack) {
  50645. if (cat->callstack_index != orig_callstack_index) {
  50646. break;
  50647. }
  50648. if (DUK_CAT_GET_TYPE(cat) == DUK_CAT_TYPE_TCF &&
  50649. DUK_CAT_HAS_FINALLY_ENABLED(cat)) {
  50650. /* 'finally' catches */
  50651. duk__handle_catch_or_finally(thr,
  50652. cat - thr->catchstack,
  50653. 1); /* is_finally */
  50654. DUK_DD(DUK_DDPRINT("-> return caught by a finally (in the same function), restart execution"));
  50655. retval = DUK__LONGJMP_RESTART;
  50656. goto wipe_and_return;
  50657. }
  50658. cat--;
  50659. }
  50660. /* if out of catchstack, cat = thr->catchstack - 1 */
  50661. DUK_DD(DUK_DDPRINT("no catcher in catch stack, return to calling activation / yield"));
  50662. /* return to calling activation (if any) */
  50663. if (thr == entry_thread &&
  50664. thr->callstack_top == entry_callstack_top) {
  50665. /* return to the bytecode executor caller */
  50666. duk_push_tval((duk_context *) thr, &thr->heap->lj.value1);
  50667. /* [ ... retval ] */
  50668. DUK_DD(DUK_DDPRINT("-> return propagated up to entry level, exit bytecode executor"));
  50669. retval = DUK__LONGJMP_FINISHED;
  50670. goto wipe_and_return;
  50671. }
  50672. if (thr->callstack_top >= 2) {
  50673. /* there is a caller; it MUST be an Ecmascript caller (otherwise it would
  50674. * match entry level check)
  50675. */
  50676. DUK_DDD(DUK_DDDPRINT("slow return to Ecmascript caller, idx_retval=%ld, lj_value1=%!T",
  50677. (long) (thr->callstack + thr->callstack_top - 2)->idx_retval,
  50678. (duk_tval *) &thr->heap->lj.value1));
  50679. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2))); /* must be ecmascript */
  50680. tv1 = thr->valstack + (thr->callstack + thr->callstack_top - 2)->idx_retval;
  50681. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  50682. DUK_TVAL_SET_TVAL(tv1, &thr->heap->lj.value1);
  50683. DUK_TVAL_INCREF(thr, tv1);
  50684. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50685. DUK_DDD(DUK_DDDPRINT("return value at idx_retval=%ld is %!T",
  50686. (long) (thr->callstack + thr->callstack_top - 2)->idx_retval,
  50687. (duk_tval *) (thr->valstack + (thr->callstack + thr->callstack_top - 2)->idx_retval)));
  50688. duk_hthread_catchstack_unwind(thr, (cat - thr->catchstack) + 1); /* leave 'cat' as top catcher (also works if catchstack exhausted) */
  50689. duk_hthread_callstack_unwind(thr, thr->callstack_top - 1);
  50690. duk__reconfig_valstack(thr, thr->callstack_top - 1, 1); /* new top, i.e. callee */
  50691. DUK_DD(DUK_DDPRINT("-> return not caught, restart execution in caller"));
  50692. retval = DUK__LONGJMP_RESTART;
  50693. goto wipe_and_return;
  50694. }
  50695. DUK_DD(DUK_DDPRINT("no calling activation, thread finishes (similar to yield)"));
  50696. DUK_ASSERT(thr->resumer != NULL);
  50697. DUK_ASSERT(thr->resumer->callstack_top >= 2); /* Ecmascript activation + Duktape.Thread.resume() activation */
  50698. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 1) != NULL &&
  50699. DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 1)) &&
  50700. ((duk_hnativefunction *) DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 1))->func == duk_bi_thread_resume); /* Duktape.Thread.resume() */
  50701. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 2) != NULL &&
  50702. DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 2))); /* an Ecmascript function */
  50703. DUK_ASSERT_DISABLE((thr->resumer->callstack + thr->resumer->callstack_top - 2)->idx_retval >= 0); /* unsigned */
  50704. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_RUNNING);
  50705. DUK_ASSERT(thr->resumer->state == DUK_HTHREAD_STATE_RESUMED);
  50706. resumer = thr->resumer;
  50707. duk__handle_yield(thr, resumer, resumer->callstack_top - 2);
  50708. duk_hthread_terminate(thr); /* updates thread state, minimizes its allocations */
  50709. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_TERMINATED);
  50710. thr->resumer = NULL;
  50711. resumer->state = DUK_HTHREAD_STATE_RUNNING;
  50712. DUK_HEAP_SWITCH_THREAD(thr->heap, resumer);
  50713. #if 0
  50714. thr = resumer; /* not needed */
  50715. #endif
  50716. DUK_DD(DUK_DDPRINT("-> return not caught, thread terminated; handle like yield, restart execution in resumer"));
  50717. retval = DUK__LONGJMP_RESTART;
  50718. goto wipe_and_return;
  50719. }
  50720. case DUK_LJ_TYPE_BREAK:
  50721. case DUK_LJ_TYPE_CONTINUE: {
  50722. /*
  50723. * Find a matching label catcher or 'finally' catcher in
  50724. * the same function.
  50725. *
  50726. * A label catcher must always exist and will match unless
  50727. * a 'finally' captures the break/continue first. It is the
  50728. * compiler's responsibility to ensure that labels are used
  50729. * correctly.
  50730. */
  50731. duk_catcher *cat;
  50732. duk_size_t orig_callstack_index;
  50733. duk_uint_t lj_label;
  50734. cat = thr->catchstack + thr->catchstack_top - 1;
  50735. orig_callstack_index = cat->callstack_index;
  50736. DUK_ASSERT(DUK_TVAL_IS_NUMBER(&thr->heap->lj.value1));
  50737. lj_label = (duk_uint_t) DUK_TVAL_GET_NUMBER(&thr->heap->lj.value1);
  50738. DUK_DDD(DUK_DDDPRINT("handling break/continue with label=%ld, callstack index=%ld",
  50739. (long) lj_label, (long) cat->callstack_index));
  50740. while (cat >= thr->catchstack) {
  50741. if (cat->callstack_index != orig_callstack_index) {
  50742. break;
  50743. }
  50744. DUK_DDD(DUK_DDDPRINT("considering catcher %ld: type=%ld label=%ld",
  50745. (long) (cat - thr->catchstack),
  50746. (long) DUK_CAT_GET_TYPE(cat),
  50747. (long) DUK_CAT_GET_LABEL(cat)));
  50748. if (DUK_CAT_GET_TYPE(cat) == DUK_CAT_TYPE_TCF &&
  50749. DUK_CAT_HAS_FINALLY_ENABLED(cat)) {
  50750. /* finally catches */
  50751. duk__handle_catch_or_finally(thr,
  50752. cat - thr->catchstack,
  50753. 1); /* is_finally */
  50754. DUK_DD(DUK_DDPRINT("-> break/continue caught by a finally (in the same function), restart execution"));
  50755. retval = DUK__LONGJMP_RESTART;
  50756. goto wipe_and_return;
  50757. }
  50758. if (DUK_CAT_GET_TYPE(cat) == DUK_CAT_TYPE_LABEL &&
  50759. (duk_uint_t) DUK_CAT_GET_LABEL(cat) == lj_label) {
  50760. /* found label */
  50761. duk__handle_label(thr,
  50762. cat - thr->catchstack);
  50763. DUK_DD(DUK_DDPRINT("-> break/continue caught by a label catcher (in the same function), restart execution"));
  50764. retval = DUK__LONGJMP_RESTART;
  50765. goto wipe_and_return;
  50766. }
  50767. cat--;
  50768. }
  50769. /* should never happen, but be robust */
  50770. DUK_D(DUK_DPRINT("break/continue not caught by anything in the current function (should never happen)"));
  50771. goto convert_to_internal_error;
  50772. }
  50773. case DUK_LJ_TYPE_THROW: {
  50774. /*
  50775. * Three possible outcomes:
  50776. * * A try or finally catcher is found => resume there.
  50777. * (or)
  50778. * * The error propagates to the bytecode executor entry
  50779. * level (and we're in the entry thread) => rethrow
  50780. * with a new longjmp(), after restoring the previous
  50781. * catchpoint.
  50782. * * The error is not caught in the current thread, so
  50783. * the thread finishes with an error. This works like
  50784. * a yielded error, except that the thread is finished
  50785. * and can no longer be resumed. (There is always a
  50786. * resumer in this case.)
  50787. *
  50788. * Note: until we hit the entry level, there can only be
  50789. * Ecmascript activations.
  50790. */
  50791. duk_catcher *cat;
  50792. duk_hthread *resumer;
  50793. cat = thr->catchstack + thr->catchstack_top - 1;
  50794. while (cat >= thr->catchstack) {
  50795. if (thr == entry_thread &&
  50796. cat->callstack_index < entry_callstack_index) {
  50797. /* entry level reached */
  50798. break;
  50799. }
  50800. if (DUK_CAT_HAS_CATCH_ENABLED(cat)) {
  50801. /* try catches */
  50802. DUK_ASSERT(DUK_CAT_GET_TYPE(cat) == DUK_CAT_TYPE_TCF);
  50803. duk__handle_catch_or_finally(thr,
  50804. cat - thr->catchstack,
  50805. 0); /* is_finally */
  50806. DUK_DD(DUK_DDPRINT("-> throw caught by a 'catch' clause, restart execution"));
  50807. retval = DUK__LONGJMP_RESTART;
  50808. goto wipe_and_return;
  50809. }
  50810. if (DUK_CAT_HAS_FINALLY_ENABLED(cat)) {
  50811. DUK_ASSERT(DUK_CAT_GET_TYPE(cat) == DUK_CAT_TYPE_TCF);
  50812. DUK_ASSERT(!DUK_CAT_HAS_CATCH_ENABLED(cat));
  50813. duk__handle_catch_or_finally(thr,
  50814. cat - thr->catchstack,
  50815. 1); /* is_finally */
  50816. DUK_DD(DUK_DDPRINT("-> throw caught by a 'finally' clause, restart execution"));
  50817. retval = DUK__LONGJMP_RESTART;
  50818. goto wipe_and_return;
  50819. }
  50820. cat--;
  50821. }
  50822. if (thr == entry_thread) {
  50823. /* not caught by anything before entry level; rethrow and let the
  50824. * final catcher unwind everything
  50825. */
  50826. #if 0
  50827. duk_hthread_catchstack_unwind(thr, (cat - thr->catchstack) + 1); /* leave 'cat' as top catcher (also works if catchstack exhausted) */
  50828. duk_hthread_callstack_unwind(thr, entry_callstack_index + 1);
  50829. #endif
  50830. DUK_D(DUK_DPRINT("-> throw propagated up to entry level, rethrow and exit bytecode executor"));
  50831. retval = DUK__LONGJMP_RETHROW;
  50832. goto just_return;
  50833. /* Note: MUST NOT wipe_and_return here, as heap->lj must remain intact */
  50834. }
  50835. DUK_DD(DUK_DDPRINT("not caught by current thread, yield error to resumer"));
  50836. /* not caught by current thread, thread terminates (yield error to resumer);
  50837. * note that this may cause a cascade if the resumer terminates with an uncaught
  50838. * exception etc (this is OK, but needs careful testing)
  50839. */
  50840. DUK_ASSERT(thr->resumer != NULL);
  50841. DUK_ASSERT(thr->resumer->callstack_top >= 2); /* Ecmascript activation + Duktape.Thread.resume() activation */
  50842. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 1) != NULL &&
  50843. DUK_HOBJECT_IS_NATIVEFUNCTION(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 1)) &&
  50844. ((duk_hnativefunction *) DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 1))->func == duk_bi_thread_resume); /* Duktape.Thread.resume() */
  50845. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 2) != NULL &&
  50846. DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->resumer->callstack + thr->resumer->callstack_top - 2))); /* an Ecmascript function */
  50847. resumer = thr->resumer;
  50848. /* reset longjmp */
  50849. DUK_ASSERT(thr->heap->lj.type == DUK_LJ_TYPE_THROW); /* already set */
  50850. /* lj.value1 already set */
  50851. duk_hthread_terminate(thr); /* updates thread state, minimizes its allocations */
  50852. DUK_ASSERT(thr->state == DUK_HTHREAD_STATE_TERMINATED);
  50853. thr->resumer = NULL;
  50854. resumer->state = DUK_HTHREAD_STATE_RUNNING;
  50855. DUK_HEAP_SWITCH_THREAD(thr->heap, resumer);
  50856. thr = resumer;
  50857. goto check_longjmp;
  50858. }
  50859. case DUK_LJ_TYPE_NORMAL: {
  50860. DUK_D(DUK_DPRINT("caught DUK_LJ_TYPE_NORMAL, should never happen, treat as internal error"));
  50861. goto convert_to_internal_error;
  50862. }
  50863. default: {
  50864. /* should never happen, but be robust */
  50865. DUK_D(DUK_DPRINT("caught unknown longjmp type %ld, treat as internal error", (long) thr->heap->lj.type));
  50866. goto convert_to_internal_error;
  50867. }
  50868. } /* end switch */
  50869. DUK_UNREACHABLE();
  50870. wipe_and_return:
  50871. /* this is not strictly necessary, but helps debugging */
  50872. thr->heap->lj.type = DUK_LJ_TYPE_UNKNOWN;
  50873. thr->heap->lj.iserror = 0;
  50874. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value1);
  50875. DUK_TVAL_SET_UNDEFINED_UNUSED(&thr->heap->lj.value1);
  50876. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50877. DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value2);
  50878. DUK_TVAL_SET_UNDEFINED_UNUSED(&thr->heap->lj.value2);
  50879. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50880. just_return:
  50881. return retval;
  50882. convert_to_internal_error:
  50883. /* This could also be thrown internally (set the error, goto check_longjmp),
  50884. * but it's better for internal errors to bubble outwards.
  50885. */
  50886. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR_EXEC_LONGJMP);
  50887. DUK_UNREACHABLE();
  50888. return retval;
  50889. }
  50890. /* XXX: Disabled for 1.0 release. This needs to handle unwinding for label
  50891. * sites (which are created for explicit labels but also for control statements
  50892. * like for-loops). At that point it's quite close to the "slow return" handler
  50893. * except for longjmp(). Perhaps all returns could initially be handled as fast
  50894. * returns and only converted to longjmp()s when basic handling won't do?
  50895. */
  50896. #if 0
  50897. /* Try a fast return. Return false if fails, so that a slow return can be done
  50898. * instead.
  50899. */
  50900. DUK_LOCAL
  50901. duk_bool_t duk__handle_fast_return(duk_hthread *thr,
  50902. duk_tval *tv_retval,
  50903. duk_hthread *entry_thread,
  50904. duk_size_t entry_callstack_top) {
  50905. duk_tval tv_tmp;
  50906. duk_tval *tv1;
  50907. /* retval == NULL indicates 'undefined' return value */
  50908. if (thr == entry_thread && thr->callstack_top == entry_callstack_top) {
  50909. DUK_DDD(DUK_DDDPRINT("reject fast return: return would exit bytecode executor to caller"));
  50910. return 0;
  50911. }
  50912. if (thr->callstack_top <= 1) {
  50913. DUK_DDD(DUK_DDDPRINT("reject fast return: there is no caller in this callstack (thread yield)"));
  50914. return 0;
  50915. }
  50916. /* There is a caller, and it must be an Ecmascript caller (otherwise
  50917. * it would have matched the entry level check).
  50918. */
  50919. DUK_ASSERT(thr->callstack_top >= 2);
  50920. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 2))); /* must be ecmascript */
  50921. tv1 = thr->valstack + (thr->callstack + thr->callstack_top - 2)->idx_retval;
  50922. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  50923. if (tv_retval) {
  50924. DUK_TVAL_SET_TVAL(tv1, tv_retval);
  50925. DUK_TVAL_INCREF(thr, tv1);
  50926. } else {
  50927. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv1);
  50928. /* no need to incref */
  50929. }
  50930. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  50931. /* No catchstack to unwind. */
  50932. #if 0
  50933. duk_hthread_catchstack_unwind(thr, (cat - thr->catchstack) + 1); /* leave 'cat' as top catcher (also works if catchstack exhausted) */
  50934. #endif
  50935. duk_hthread_callstack_unwind(thr, thr->callstack_top - 1);
  50936. duk__reconfig_valstack(thr, thr->callstack_top - 1, 1); /* new top, i.e. callee */
  50937. DUK_DDD(DUK_DDDPRINT("fast return accepted"));
  50938. return 1;
  50939. }
  50940. #endif
  50941. /*
  50942. * Executor interrupt handling
  50943. *
  50944. * The handler is called whenever the interrupt countdown reaches zero
  50945. * (or below). The handler must perform whatever checks are activated,
  50946. * e.g. check for cumulative step count to impose an execution step
  50947. * limit or check for breakpoints or other debugger interaction.
  50948. *
  50949. * When the actions are done, the handler must reinit the interrupt
  50950. * init and counter values. The 'init' value must indicate how many
  50951. * bytecode instructions are executed before the next interrupt. The
  50952. * counter must interface with the bytecode executor loop. Concretely,
  50953. * the new init value is normally one higher than the new counter value.
  50954. * For instance, to execute exactly one bytecode instruction the init
  50955. * value is set to 1 and the counter to 0. If an error is thrown by the
  50956. * interrupt handler, the counters are set to the same value (e.g. both
  50957. * to 0 to cause an interrupt when the next bytecode instruction is about
  50958. * to be executed after error handling).
  50959. *
  50960. * Maintaining the init/counter value properly is important for accurate
  50961. * behavior. For instance, executor step limit needs a cumulative step
  50962. * count which is simply computed as a sum of 'init' values. This must
  50963. * work accurately even when single stepping.
  50964. */
  50965. #ifdef DUK_USE_INTERRUPT_COUNTER
  50966. #define DUK__INT_NOACTION 0 /* no specific action, resume normal execution */
  50967. #define DUK__INT_RESTART 1 /* must "goto restart_execution", e.g. breakpoints changed */
  50968. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  50969. DUK_LOCAL void duk__interrupt_handle_debugger(duk_hthread *thr, duk_bool_t *out_immediate, duk_small_uint_t *out_interrupt_retval) {
  50970. duk_context *ctx;
  50971. duk_activation *act;
  50972. duk_breakpoint *bp;
  50973. duk_breakpoint **bp_active;
  50974. duk_uint_fast32_t line = 0;
  50975. duk_bool_t send_status;
  50976. duk_bool_t process_messages;
  50977. duk_bool_t processed_messages = 0;
  50978. ctx = (duk_context *) thr;
  50979. act = thr->callstack + thr->callstack_top - 1;
  50980. /* It might seem that replacing 'thr->heap' with just 'heap' below
  50981. * might be a good idea, but it increases code size slightly
  50982. * (probably due to unnecessary spilling) at least on x64.
  50983. */
  50984. /*
  50985. * Breakpoint and step state checks
  50986. */
  50987. if (act->flags & DUK_ACT_FLAG_BREAKPOINT_ACTIVE ||
  50988. (thr->heap->dbg_step_thread == thr &&
  50989. thr->heap->dbg_step_csindex == thr->callstack_top - 1)) {
  50990. line = duk_debug_curr_line(thr);
  50991. if (act->prev_line != line) {
  50992. DUK_DDD(DUK_DDDPRINT("PC=%ld line=%ld; line transition: %ld -> %ld",
  50993. (long) act->pc, (long) line, (long) act->prev_line, (long) line));
  50994. /* Stepped? Step out is handled by callstack unwind. */
  50995. if ((thr->heap->dbg_step_type == DUK_STEP_TYPE_INTO ||
  50996. thr->heap->dbg_step_type == DUK_STEP_TYPE_OVER) &&
  50997. (thr->heap->dbg_step_thread == thr) &&
  50998. (thr->heap->dbg_step_csindex == thr->callstack_top - 1) &&
  50999. (line != thr->heap->dbg_step_startline)) {
  51000. DUK_D(DUK_DPRINT("STEP STATE TRIGGERED PAUSE at line %ld",
  51001. (long) line));
  51002. DUK_HEAP_SET_PAUSED(thr->heap);
  51003. }
  51004. /* Check for breakpoints only on line transition.
  51005. * Breakpoint is triggered when we enter or cross
  51006. * the target line, and the previous line was within
  51007. * the same function.
  51008. */
  51009. bp_active = thr->heap->dbg_breakpoints_active;
  51010. for (;;) {
  51011. bp = *bp_active++;
  51012. if (bp == NULL) {
  51013. break;
  51014. }
  51015. DUK_ASSERT(bp->filename != NULL);
  51016. if (act->prev_line < bp->line && line >= bp->line) {
  51017. DUK_D(DUK_DPRINT("BREAKPOINT TRIGGERED at %!O:%ld",
  51018. (duk_heaphdr *) bp->filename, (long) bp->line));
  51019. DUK_HEAP_SET_PAUSED(thr->heap);
  51020. }
  51021. }
  51022. } else {
  51023. DUK_DDD(DUK_DDDPRINT("PC=%ld line=%ld", (long) act->pc, (long) line));
  51024. }
  51025. act->prev_line = line;
  51026. }
  51027. /*
  51028. * Rate limit check for sending status update or peeking into
  51029. * the debug transport. Both can be expensive operations that
  51030. * we don't want to do on every opcode.
  51031. *
  51032. * Making sure the interval remains reasonable on a wide variety
  51033. * of targets and bytecode is difficult without a timestamp, so
  51034. * we use a Date-provided timestamp for the rate limit check.
  51035. * But since it's also expensive to get a timestamp, a bytecode
  51036. * counter is used to rate limit getting timestamps.
  51037. */
  51038. if (thr->heap->dbg_state_dirty || thr->heap->dbg_paused) {
  51039. send_status = 1;
  51040. } else {
  51041. send_status = 0;
  51042. }
  51043. if (thr->heap->dbg_paused) {
  51044. process_messages = 1;
  51045. } else {
  51046. process_messages = 0;
  51047. }
  51048. thr->heap->dbg_exec_counter += thr->heap->interrupt_init;
  51049. if (thr->heap->dbg_exec_counter - thr->heap->dbg_last_counter >= DUK_HEAP_DBG_RATELIMIT_OPCODES) {
  51050. /* Overflow of the execution counter is fine and doesn't break
  51051. * anything here.
  51052. */
  51053. duk_double_t now, diff_last;
  51054. thr->heap->dbg_last_counter = thr->heap->dbg_exec_counter;
  51055. now = duk_bi_date_get_now(ctx);
  51056. diff_last = now - thr->heap->dbg_last_time;
  51057. if (diff_last < 0.0 || diff_last >= (duk_double_t) DUK_HEAP_DBG_RATELIMIT_MILLISECS) {
  51058. /* Negative value checked so that a "time jump" works
  51059. * reasonably.
  51060. *
  51061. * Same interval is now used for status sending and
  51062. * peeking.
  51063. */
  51064. thr->heap->dbg_last_time = now;
  51065. send_status = 1;
  51066. process_messages = 1;
  51067. }
  51068. }
  51069. /*
  51070. * Send status
  51071. */
  51072. act = NULL; /* may be changed */
  51073. if (send_status) {
  51074. duk_debug_send_status(thr);
  51075. thr->heap->dbg_state_dirty = 0;
  51076. }
  51077. /*
  51078. * Process messages. If we're paused, we'll block for new messages.
  51079. * if we're not paused, we'll process anything we can peek but won't
  51080. * block for more.
  51081. */
  51082. if (process_messages) {
  51083. processed_messages = duk_debug_process_messages(thr, 0 /*no_block*/);
  51084. }
  51085. /* XXX: any case here where we need to re-send status? */
  51086. /* Continue checked execution if there are breakpoints or we're stepping.
  51087. * Also use checked execution if paused flag is active - it shouldn't be
  51088. * because the debug message loop shouldn't terminate if it was. Step out
  51089. * is handled by callstack unwind and doesn't need checked execution.
  51090. * Note that debugger may have detached due to error or explicit request
  51091. * above, so we must recheck attach status.
  51092. */
  51093. if (DUK_HEAP_IS_DEBUGGER_ATTACHED(thr->heap)) {
  51094. act = thr->callstack + thr->callstack_top - 1; /* relookup, may have changed */
  51095. if (act->flags & DUK_ACT_FLAG_BREAKPOINT_ACTIVE ||
  51096. ((thr->heap->dbg_step_type == DUK_STEP_TYPE_INTO ||
  51097. thr->heap->dbg_step_type == DUK_STEP_TYPE_OVER) &&
  51098. thr->heap->dbg_step_thread == thr &&
  51099. thr->heap->dbg_step_csindex == thr->callstack_top - 1) ||
  51100. thr->heap->dbg_paused) {
  51101. *out_immediate = 1;
  51102. }
  51103. /* If we processed any debug messages breakpoints may have
  51104. * changed; restart execution to re-check active breakpoints.
  51105. */
  51106. if (processed_messages) {
  51107. DUK_D(DUK_DPRINT("processed debug messages, restart execution to recheck possibly changed breakpoints"));
  51108. *out_interrupt_retval = DUK__INT_RESTART;
  51109. }
  51110. } else {
  51111. DUK_D(DUK_DPRINT("debugger became detached, resume normal execution"));
  51112. }
  51113. }
  51114. #endif /* DUK_USE_DEBUGGER_SUPPORT */
  51115. DUK_LOCAL duk_small_uint_t duk__executor_interrupt(duk_hthread *thr) {
  51116. duk_int_t ctr;
  51117. duk_activation *act;
  51118. duk_hcompiledfunction *fun;
  51119. duk_bool_t immediate = 0;
  51120. duk_small_uint_t retval;
  51121. DUK_ASSERT(thr != NULL);
  51122. DUK_ASSERT(thr->callstack != NULL);
  51123. DUK_ASSERT(thr->callstack_top > 0);
  51124. retval = DUK__INT_NOACTION;
  51125. ctr = DUK_HEAP_INTCTR_DEFAULT;
  51126. /*
  51127. * Avoid nested calls. Concretely this happens during debugging, e.g.
  51128. * when we eval() an expression.
  51129. */
  51130. if (DUK_HEAP_HAS_INTERRUPT_RUNNING(thr->heap)) {
  51131. DUK_DD(DUK_DDPRINT("nested executor interrupt, ignoring"));
  51132. /* Set a high interrupt counter; the original executor
  51133. * interrupt invocation will rewrite before exiting.
  51134. */
  51135. thr->heap->interrupt_init = ctr;
  51136. thr->heap->interrupt_counter = ctr - 1;
  51137. thr->interrupt_counter = ctr - 1;
  51138. return DUK__INT_NOACTION;
  51139. }
  51140. DUK_HEAP_SET_INTERRUPT_RUNNING(thr->heap);
  51141. act = thr->callstack + thr->callstack_top - 1;
  51142. fun = (duk_hcompiledfunction *) DUK_ACT_GET_FUNC(act);
  51143. DUK_ASSERT(DUK_HOBJECT_HAS_COMPILEDFUNCTION((duk_hobject *) fun));
  51144. DUK_UNREF(fun);
  51145. #if defined(DUK_USE_EXEC_TIMEOUT_CHECK)
  51146. /*
  51147. * Execution timeout check
  51148. */
  51149. if (DUK_USE_EXEC_TIMEOUT_CHECK(thr->heap->heap_udata)) {
  51150. /* Keep throwing an error whenever we get here. The unusual values
  51151. * are set this way because no instruction is ever executed, we just
  51152. * throw an error until all try/catch/finally and other catchpoints
  51153. * have been exhausted. Duktape/C code gets control at each protected
  51154. * call but whenever it enters back into Duktape the RangeError gets
  51155. * raised. User exec timeout check must consistently indicate a timeout
  51156. * until we've fully bubbled out of Duktape.
  51157. */
  51158. DUK_D(DUK_DPRINT("execution timeout, throwing a RangeError"));
  51159. thr->heap->interrupt_init = 0;
  51160. thr->heap->interrupt_counter = 0;
  51161. thr->interrupt_counter = 0;
  51162. DUK_ERROR(thr, DUK_ERR_RANGE_ERROR, "execution timeout");
  51163. }
  51164. #endif /* DUK_USE_EXEC_TIMEOUT_CHECK */
  51165. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  51166. if (DUK_HEAP_IS_DEBUGGER_ATTACHED(thr->heap)) {
  51167. duk__interrupt_handle_debugger(thr, &immediate, &retval);
  51168. act = thr->callstack + thr->callstack_top - 1; /* relookup if changed */
  51169. }
  51170. #endif /* DUK_USE_DEBUGGER_SUPPORT */
  51171. /*
  51172. * Update the interrupt counter
  51173. */
  51174. if (immediate) {
  51175. /* Cause an interrupt after executing one instruction. */
  51176. ctr = 1;
  51177. }
  51178. DUK_DDD(DUK_DDDPRINT("executor interrupt finished, cstop=%ld, pc=%ld, nextctr=%ld",
  51179. (long) thr->callstack_top, (long) act->pc, (long) ctr));
  51180. /* The counter value is one less than the init value: init value should
  51181. * indicate how many instructions are executed before interrupt. To
  51182. * execute 1 instruction, counter must be 0.
  51183. */
  51184. thr->heap->interrupt_init = ctr;
  51185. thr->heap->interrupt_counter = ctr - 1;
  51186. thr->interrupt_counter = ctr - 1;
  51187. DUK_HEAP_CLEAR_INTERRUPT_RUNNING(thr->heap);
  51188. return retval;
  51189. }
  51190. #endif /* DUK_USE_INTERRUPT_COUNTER */
  51191. /*
  51192. * Debugger handling for executor restart
  51193. *
  51194. * Check for breakpoints, stepping, etc, and figure out if we should execute
  51195. * in checked or normal mode. Note that we can't do this when an activation
  51196. * is created, because breakpoint status (and stepping status) may change
  51197. * later, so we must recheck every time we're executing an activation.
  51198. */
  51199. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  51200. DUK_LOCAL void duk__executor_handle_debugger(duk_hthread *thr, duk_activation *act, duk_hcompiledfunction *fun) {
  51201. duk_heap *heap;
  51202. duk_tval *tv_tmp;
  51203. duk_hstring *filename;
  51204. duk_small_uint_t bp_idx;
  51205. duk_breakpoint **bp_active;
  51206. DUK_ASSERT(thr != NULL);
  51207. DUK_ASSERT(act != NULL);
  51208. DUK_ASSERT(fun != NULL);
  51209. heap = thr->heap;
  51210. bp_active = heap->dbg_breakpoints_active;
  51211. act->flags &= ~DUK_ACT_FLAG_BREAKPOINT_ACTIVE;
  51212. tv_tmp = duk_hobject_find_existing_entry_tval_ptr(thr->heap, (duk_hobject *) fun, DUK_HTHREAD_STRING_FILE_NAME(thr));
  51213. if (tv_tmp && DUK_TVAL_IS_STRING(tv_tmp)) {
  51214. filename = DUK_TVAL_GET_STRING(tv_tmp);
  51215. /* Figure out all active breakpoints. A breakpoint is
  51216. * considered active if the current function's fileName
  51217. * matches the breakpoint's fileName, AND there is no
  51218. * inner function that has matching line numbers
  51219. * (otherwise a breakpoint would be triggered both
  51220. * inside and outside of the inner function which would
  51221. * be confusing). Example:
  51222. *
  51223. * function foo() {
  51224. * print('foo');
  51225. * function bar() { <-. breakpoints in these
  51226. * print('bar'); | lines should not affect
  51227. * } <-' foo() execution
  51228. * bar();
  51229. * }
  51230. *
  51231. * We need a few things that are only available when
  51232. * debugger support is enabled: (1) a line range for
  51233. * each function, and (2) access to the function
  51234. * template to access the inner functions (and their
  51235. * line ranges).
  51236. *
  51237. * It's important to have a narrow match for active
  51238. * breakpoints so that we don't enter checked execution
  51239. * when that's not necessary. For instance, if we're
  51240. * running inside a certain function and there's
  51241. * breakpoint outside in (after the call site), we
  51242. * don't want to slow down execution of the function.
  51243. */
  51244. for (bp_idx = 0; bp_idx < heap->dbg_breakpoint_count; bp_idx++) {
  51245. duk_breakpoint *bp = heap->dbg_breakpoints + bp_idx;
  51246. duk_hobject **funcs, **funcs_end;
  51247. duk_hcompiledfunction *inner_fun;
  51248. duk_bool_t bp_match;
  51249. if (bp->filename == filename &&
  51250. bp->line >= fun->start_line && bp->line <= fun->end_line) {
  51251. bp_match = 1;
  51252. DUK_DD(DUK_DDPRINT("breakpoint filename and line match: "
  51253. "%s:%ld vs. %s (line %ld vs. %ld-%ld)",
  51254. DUK_HSTRING_GET_DATA(bp->filename),
  51255. (long) bp->line,
  51256. DUK_HSTRING_GET_DATA(filename),
  51257. (long) bp->line,
  51258. (long) fun->start_line,
  51259. (long) fun->end_line));
  51260. funcs = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(thr->heap, fun);
  51261. funcs_end = DUK_HCOMPILEDFUNCTION_GET_FUNCS_END(thr->heap, fun);
  51262. while (funcs != funcs_end) {
  51263. inner_fun = (duk_hcompiledfunction *) *funcs;
  51264. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION((duk_hobject *) inner_fun));
  51265. if (bp->line >= inner_fun->start_line && bp->line <= inner_fun->end_line) {
  51266. DUK_DD(DUK_DDPRINT("inner function masks ('captures') breakpoint"));
  51267. bp_match = 0;
  51268. break;
  51269. }
  51270. funcs++;
  51271. }
  51272. if (bp_match) {
  51273. /* No need to check for size of bp_active list,
  51274. * it's always larger than maximum number of
  51275. * breakpoints.
  51276. */
  51277. act->flags |= DUK_ACT_FLAG_BREAKPOINT_ACTIVE;
  51278. *bp_active = heap->dbg_breakpoints + bp_idx;
  51279. bp_active++;
  51280. }
  51281. }
  51282. }
  51283. }
  51284. *bp_active = NULL; /* terminate */
  51285. DUK_DD(DUK_DDPRINT("ACTIVE BREAKPOINTS: %ld", (long) (bp_active - thr->heap->dbg_breakpoints_active)));
  51286. /* Force pause if we were doing "step into" in another activation. */
  51287. if (thr->heap->dbg_step_thread != NULL &&
  51288. thr->heap->dbg_step_type == DUK_STEP_TYPE_INTO &&
  51289. (thr->heap->dbg_step_thread != thr ||
  51290. thr->heap->dbg_step_csindex != thr->callstack_top - 1)) {
  51291. DUK_D(DUK_DPRINT("STEP INTO ACTIVE, FORCE PAUSED"));
  51292. DUK_HEAP_SET_PAUSED(thr->heap);
  51293. }
  51294. /* Force interrupt right away if we're paused or in "checked mode".
  51295. * Step out is handled by callstack unwind.
  51296. */
  51297. if (act->flags & (DUK_ACT_FLAG_BREAKPOINT_ACTIVE) ||
  51298. thr->heap->dbg_paused ||
  51299. (thr->heap->dbg_step_type != DUK_STEP_TYPE_OUT &&
  51300. thr->heap->dbg_step_csindex == thr->callstack_top - 1)) {
  51301. thr->interrupt_counter = 0;
  51302. }
  51303. }
  51304. #endif /* DUK_USE_DEBUGGER_SUPPORT */
  51305. /*
  51306. * Ecmascript bytecode executor.
  51307. *
  51308. * Resume execution for the current thread from its current activation.
  51309. * Returns when execution would return from the entry level activation,
  51310. * leaving a single return value on top of the stack. Function calls
  51311. * and thread resumptions are handled internally. If an error occurs,
  51312. * a longjmp() with type DUK_LJ_TYPE_THROW is called on the entry level
  51313. * setjmp() jmpbuf.
  51314. *
  51315. * Ecmascript function calls and coroutine resumptions are handled
  51316. * internally without recursive C calls. Other function calls are
  51317. * handled using duk_handle_call(), increasing C recursion depth.
  51318. *
  51319. * There are many other tricky control flow situations, such as:
  51320. *
  51321. * - Break and continue (fast and slow)
  51322. * - Return (fast and slow)
  51323. * - Error throwing
  51324. * - Thread resume and yield
  51325. *
  51326. * For more detailed notes, see doc/execution.rst.
  51327. *
  51328. * Also see doc/code-issues.rst for discussion of setjmp(), longjmp(),
  51329. * and volatile.
  51330. */
  51331. #define DUK__STRICT() (DUK_HOBJECT_HAS_STRICT(&(fun)->obj))
  51332. #define DUK__REG(x) (thr->valstack_bottom[(x)])
  51333. #define DUK__REGP(x) (&thr->valstack_bottom[(x)])
  51334. #define DUK__CONST(x) (DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(thr->heap, fun)[(x)])
  51335. #define DUK__CONSTP(x) (&DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(thr->heap, fun)[(x)])
  51336. #define DUK__REGCONST(x) ((x) < DUK_BC_REGLIMIT ? DUK__REG((x)) : DUK__CONST((x) - DUK_BC_REGLIMIT))
  51337. #define DUK__REGCONSTP(x) ((x) < DUK_BC_REGLIMIT ? DUK__REGP((x)) : DUK__CONSTP((x) - DUK_BC_REGLIMIT))
  51338. #ifdef DUK_USE_VERBOSE_EXECUTOR_ERRORS
  51339. #define DUK__INTERNAL_ERROR(msg) do { \
  51340. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, (msg)); \
  51341. } while (0)
  51342. #else
  51343. #define DUK__INTERNAL_ERROR(msg) do { \
  51344. goto internal_error; \
  51345. } while (0)
  51346. #endif
  51347. DUK_INTERNAL void duk_js_execute_bytecode(duk_hthread *exec_thr) {
  51348. /* Entry level info. Although these are assigned to before setjmp()
  51349. * a 'volatile' seems to be needed. Note placement of "volatile" for
  51350. * pointers. See doc/code-issues.rst for more discussion.
  51351. */
  51352. duk_hthread * volatile entry_thread; /* volatile copy of exec_thr */
  51353. volatile duk_size_t entry_callstack_top;
  51354. volatile duk_int_t entry_call_recursion_depth;
  51355. duk_jmpbuf * volatile entry_jmpbuf_ptr;
  51356. /* "hot" variables for interpretation -- not volatile, value not guaranteed in setjmp error handling */
  51357. duk_hthread *thr; /* stable */
  51358. duk_activation *act; /* semi-stable (ok as long as callstack not resized) */
  51359. duk_hcompiledfunction *fun; /* stable */
  51360. duk_instr_t *bcode; /* stable */
  51361. /* 'consts' is computed on-the-fly */
  51362. /* 'funcs' is quite rarely used, so no local for it */
  51363. /* "hot" temps for interpretation -- not volatile, value not guaranteed in setjmp error handling */
  51364. duk_uint_fast32_t ins; /* XXX: check performance impact on x64 between fast/non-fast variant */
  51365. /* jmpbuf */
  51366. duk_jmpbuf jmpbuf;
  51367. #ifdef DUK_USE_INTERRUPT_COUNTER
  51368. duk_int_t int_ctr;
  51369. #endif
  51370. #ifdef DUK_USE_ASSERTIONS
  51371. duk_size_t valstack_top_base; /* valstack top, should match before interpreting each op (no leftovers) */
  51372. #endif
  51373. /* XXX: document assumptions on setjmp and volatile variables
  51374. * (see duk_handle_call()).
  51375. */
  51376. /*
  51377. * Preliminaries
  51378. */
  51379. DUK_ASSERT(exec_thr != NULL);
  51380. DUK_ASSERT(exec_thr->heap != NULL);
  51381. DUK_ASSERT(exec_thr->heap->curr_thread != NULL);
  51382. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR((duk_heaphdr *) exec_thr);
  51383. DUK_ASSERT(exec_thr->callstack_top >= 1); /* at least one activation, ours */
  51384. DUK_ASSERT(DUK_ACT_GET_FUNC(exec_thr->callstack + exec_thr->callstack_top - 1) != NULL);
  51385. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(exec_thr->callstack + exec_thr->callstack_top - 1)));
  51386. entry_thread = exec_thr; /* volatile copy */
  51387. thr = (duk_hthread *) entry_thread;
  51388. entry_callstack_top = thr->callstack_top;
  51389. entry_call_recursion_depth = thr->heap->call_recursion_depth;
  51390. entry_jmpbuf_ptr = thr->heap->lj.jmpbuf_ptr;
  51391. /*
  51392. * Setjmp catchpoint setup.
  51393. *
  51394. * Note: we currently assume that the setjmp() catchpoint is
  51395. * not re-entrant (longjmp() cannot be called more than once
  51396. * for a single setjmp()).
  51397. */
  51398. reset_setjmp_catchpoint:
  51399. DUK_ASSERT(thr != NULL);
  51400. thr->heap->lj.jmpbuf_ptr = &jmpbuf;
  51401. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL);
  51402. if (DUK_SETJMP(thr->heap->lj.jmpbuf_ptr->jb)) {
  51403. /*
  51404. * Note: any local variables accessed here must have their value
  51405. * assigned *before* the setjmp() call, OR they must be declared
  51406. * volatile. Otherwise their value is not guaranteed to be correct.
  51407. *
  51408. * 'thr' might seem to be a risky variable because it is changed
  51409. * for yield and resume. However, yield and resume are handled
  51410. * using longjmp()s.
  51411. */
  51412. duk_small_uint_t lj_ret;
  51413. DUK_DDD(DUK_DDDPRINT("longjmp caught by bytecode executor"));
  51414. /* Relookup 'thr': it's not volatile so its value is not
  51415. * guaranteed. The heap->curr_thread value should always be
  51416. * valid here because longjmp callers don't switch threads,
  51417. * only the longjmp handler does that (even for RESUME and
  51418. * YIELD).
  51419. */
  51420. DUK_ASSERT(entry_thread != NULL);
  51421. thr = entry_thread->heap->curr_thread;
  51422. /* XXX: signalling the need to shrink check (only if unwound) */
  51423. /* Must be restored here to handle e.g. yields properly. */
  51424. thr->heap->call_recursion_depth = entry_call_recursion_depth;
  51425. /* Switch to caller's setjmp() catcher so that if an error occurs
  51426. * during error handling, it is always propagated outwards instead
  51427. * of causing an infinite loop in our own handler.
  51428. */
  51429. DUK_DDD(DUK_DDDPRINT("restore jmpbuf_ptr: %p -> %p",
  51430. (void *) ((thr && thr->heap) ? thr->heap->lj.jmpbuf_ptr : NULL),
  51431. (void *) entry_jmpbuf_ptr));
  51432. thr->heap->lj.jmpbuf_ptr = (duk_jmpbuf *) entry_jmpbuf_ptr;
  51433. lj_ret = duk__handle_longjmp(thr, (duk_hthread *) entry_thread, (duk_size_t) entry_callstack_top);
  51434. if (lj_ret == DUK__LONGJMP_RESTART) {
  51435. /*
  51436. * Restart bytecode execution, possibly with a changed thread.
  51437. */
  51438. thr = thr->heap->curr_thread;
  51439. goto reset_setjmp_catchpoint;
  51440. } else if (lj_ret == DUK__LONGJMP_RETHROW) {
  51441. /*
  51442. * Rethrow error to calling state.
  51443. */
  51444. /* thread may have changed (e.g. YIELD converted to THROW) */
  51445. thr = thr->heap->curr_thread;
  51446. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr == entry_jmpbuf_ptr);
  51447. duk_err_longjmp(thr);
  51448. DUK_UNREACHABLE();
  51449. } else {
  51450. /*
  51451. * Return from bytecode executor with a return value.
  51452. */
  51453. DUK_ASSERT(lj_ret == DUK__LONGJMP_FINISHED);
  51454. /* XXX: return assertions for valstack, callstack, catchstack */
  51455. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr == entry_jmpbuf_ptr);
  51456. return;
  51457. }
  51458. DUK_UNREACHABLE();
  51459. }
  51460. /*
  51461. * Restart execution by reloading thread state.
  51462. *
  51463. * Note that 'thr' and any thread configuration may have changed,
  51464. * so all local variables are suspect.
  51465. *
  51466. * The number of local variables should be kept to a minimum: if
  51467. * the variables are spilled, they will need to be loaded from
  51468. * memory anyway.
  51469. */
  51470. restart_execution:
  51471. /* Lookup current thread; use the volatile 'entry_thread' for this to
  51472. * avoid clobber warnings. (Any valid, reachable 'thr' value would be
  51473. * fine for this, so using 'entry_thread' is just to silence warnings.)
  51474. */
  51475. thr = entry_thread->heap->curr_thread;
  51476. DUK_ASSERT(thr != NULL);
  51477. DUK_ASSERT(thr->callstack_top >= 1);
  51478. DUK_ASSERT(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1) != NULL);
  51479. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_ACT_GET_FUNC(thr->callstack + thr->callstack_top - 1)));
  51480. #ifdef DUK_USE_INTERRUPT_COUNTER
  51481. thr->interrupt_counter = thr->heap->interrupt_counter;
  51482. #endif
  51483. /* assume that thr->valstack_bottom has been set-up before getting here */
  51484. act = thr->callstack + thr->callstack_top - 1;
  51485. fun = (duk_hcompiledfunction *) DUK_ACT_GET_FUNC(act);
  51486. DUK_ASSERT(fun != NULL);
  51487. DUK_ASSERT(thr->valstack_top - thr->valstack_bottom == fun->nregs);
  51488. bcode = DUK_HCOMPILEDFUNCTION_GET_CODE_BASE(thr->heap, fun);
  51489. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  51490. if (DUK_HEAP_IS_DEBUGGER_ATTACHED(thr->heap) && !thr->heap->dbg_processing) {
  51491. thr->heap->dbg_processing = 1;
  51492. duk__executor_handle_debugger(thr, act, fun);
  51493. thr->heap->dbg_processing = 0;
  51494. }
  51495. #endif /* DUK_USE_DEBUGGER_SUPPORT */
  51496. /* XXX: shrink check flag? */
  51497. /*
  51498. * Bytecode interpreter.
  51499. *
  51500. * The interpreter must be very careful with memory pointers, as
  51501. * many pointers are not guaranteed to be 'stable' and may be
  51502. * reallocated and relocated on-the-fly quite easily (e.g. by a
  51503. * memory allocation or a property access).
  51504. *
  51505. * The following are assumed to have stable pointers:
  51506. * - the current thread
  51507. * - the current function
  51508. * - the bytecode, constant table, inner function table of the
  51509. * current function (as they are a part of the function allocation)
  51510. *
  51511. * The following are assumed to have semi-stable pointers:
  51512. * - the current activation entry: stable as long as callstack
  51513. * is not changed (reallocated by growing or shrinking), or
  51514. * by any garbage collection invocation (through finalizers)
  51515. * - Note in particular that ANY DECREF can invalidate the
  51516. * activation pointer
  51517. *
  51518. * The following are not assumed to have stable pointers at all:
  51519. * - the value stack (registers) of the current thread
  51520. * - the catch stack of the current thread
  51521. *
  51522. * See execution.txt for discussion.
  51523. */
  51524. DUK_ASSERT(thr != NULL);
  51525. DUK_ASSERT(act != NULL);
  51526. DUK_ASSERT(fun != NULL);
  51527. DUK_ASSERT(bcode != NULL);
  51528. DUK_DD(DUK_DDPRINT("restarting execution, thr %p, act %p (idx %ld), fun %p, bcode %p, "
  51529. "consts %p, funcs %p, lev %ld, regbot %ld, regtop %ld, catchstack_top=%ld, "
  51530. "preventcount=%ld",
  51531. (void *) thr,
  51532. (void *) act,
  51533. (long) (thr->callstack_top - 1),
  51534. (void *) fun,
  51535. (void *) bcode,
  51536. (void *) DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(thr->heap, fun),
  51537. (void *) DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(thr->heap, fun),
  51538. (long) (thr->callstack_top - 1),
  51539. (long) (thr->valstack_bottom - thr->valstack),
  51540. (long) (thr->valstack_top - thr->valstack),
  51541. (long) thr->catchstack_top,
  51542. (long) thr->callstack_preventcount));
  51543. #ifdef DUK_USE_ASSERTIONS
  51544. valstack_top_base = (duk_size_t) (thr->valstack_top - thr->valstack);
  51545. #endif
  51546. for (;;) {
  51547. DUK_ASSERT(thr->callstack_top >= 1);
  51548. DUK_ASSERT(thr->valstack_top - thr->valstack_bottom == fun->nregs);
  51549. DUK_ASSERT((duk_size_t) (thr->valstack_top - thr->valstack) == valstack_top_base);
  51550. /* Executor interrupt counter check, used to implement breakpoints,
  51551. * debugging interface, execution timeouts, etc. The counter is heap
  51552. * specific but is maintained in the current thread to make the check
  51553. * as fast as possible. The counter is copied back to the heap struct
  51554. * whenever a thread switch occurs by the DUK_HEAP_SWITCH_THREAD() macro.
  51555. */
  51556. #ifdef DUK_USE_INTERRUPT_COUNTER
  51557. int_ctr = thr->interrupt_counter;
  51558. if (DUK_LIKELY(int_ctr > 0)) {
  51559. thr->interrupt_counter = int_ctr - 1;
  51560. } else {
  51561. /* Trigger at zero or below */
  51562. duk_small_uint_t exec_int_ret;
  51563. exec_int_ret = duk__executor_interrupt(thr);
  51564. if (exec_int_ret == DUK__INT_RESTART) {
  51565. goto restart_execution;
  51566. }
  51567. }
  51568. #endif
  51569. /* Because ANY DECREF potentially invalidates 'act' now (through
  51570. * finalization), we need to re-lookup 'act' in almost every case.
  51571. *
  51572. * XXX: future work for performance optimization:
  51573. * This is not nice; it would be nice if the program counter was a
  51574. * behind a stable pointer. For instance, put a raw bytecode pointer
  51575. * into duk_hthread struct (not into the callstack); since bytecode
  51576. * has a stable pointer this would work nicely. Whenever a call is
  51577. * made, the bytecode pointer could be backed up as an integer index
  51578. * to the calling activation. Perhaps add a macro for setting up a
  51579. * new activation (same as for setting up / switching threads)?
  51580. */
  51581. act = thr->callstack + thr->callstack_top - 1;
  51582. DUK_ASSERT(bcode + act->pc >= DUK_HCOMPILEDFUNCTION_GET_CODE_BASE(thr->heap, fun));
  51583. DUK_ASSERT(bcode + act->pc < DUK_HCOMPILEDFUNCTION_GET_CODE_END(thr->heap, fun));
  51584. DUK_DDD(DUK_DDDPRINT("executing bytecode: pc=%ld ins=0x%08lx, op=%ld, valstack_top=%ld/%ld, nregs=%ld --> %!I",
  51585. (long) act->pc,
  51586. (unsigned long) bcode[act->pc],
  51587. (long) DUK_DEC_OP(bcode[act->pc]),
  51588. (long) (thr->valstack_top - thr->valstack),
  51589. (long) (thr->valstack_end - thr->valstack),
  51590. (long) (fun ? fun->nregs : -1),
  51591. (duk_instr_t) bcode[act->pc]));
  51592. #if defined(DUK_USE_ASSERTIONS)
  51593. /* Quite heavy assert: check that valstack is in correctly
  51594. * initialized state. Improper shuffle instructions can
  51595. * write beyond valstack_end so this check catches them in
  51596. * the act.
  51597. */
  51598. {
  51599. duk_tval *tv;
  51600. tv = thr->valstack_top;
  51601. while (tv != thr->valstack_end) {
  51602. DUK_ASSERT(DUK_TVAL_IS_UNDEFINED_UNUSED(tv));
  51603. tv++;
  51604. }
  51605. }
  51606. #endif
  51607. ins = bcode[act->pc++];
  51608. /* Typing: use duk_small_(u)int_fast_t when decoding small
  51609. * opcode fields (op, A, B, C) and duk_(u)int_fast_t when
  51610. * decoding larger fields (e.g. BC which is 18 bits). Use
  51611. * unsigned variant by default, signed when the value is used
  51612. * in signed arithmetic. Using variable names such as 'a', 'b',
  51613. * 'c', 'bc', etc makes it easier to spot typing mismatches.
  51614. */
  51615. /* XXX: the best typing needs to be validated by perf measurement:
  51616. * e.g. using a small type which is the cast to a larger duk_idx_t
  51617. * may be slower than declaring the variable as a duk_idx_t in the
  51618. * first place.
  51619. */
  51620. /* XXX: use macros for the repetitive tval/refcount handling. */
  51621. switch ((int) DUK_DEC_OP(ins)) {
  51622. /* XXX: switch cast? */
  51623. case DUK_OP_LDREG: {
  51624. duk_small_uint_fast_t a;
  51625. duk_uint_fast_t bc;
  51626. duk_tval tv_tmp;
  51627. duk_tval *tv1, *tv2;
  51628. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51629. bc = DUK_DEC_BC(ins); tv2 = DUK__REGP(bc);
  51630. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  51631. DUK_TVAL_SET_TVAL(tv1, tv2);
  51632. DUK_TVAL_INCREF(thr, tv1);
  51633. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  51634. break;
  51635. }
  51636. case DUK_OP_STREG: {
  51637. duk_small_uint_fast_t a;
  51638. duk_uint_fast_t bc;
  51639. duk_tval tv_tmp;
  51640. duk_tval *tv1, *tv2;
  51641. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51642. bc = DUK_DEC_BC(ins); tv2 = DUK__REGP(bc);
  51643. DUK_TVAL_SET_TVAL(&tv_tmp, tv2);
  51644. DUK_TVAL_SET_TVAL(tv2, tv1);
  51645. DUK_TVAL_INCREF(thr, tv2);
  51646. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  51647. break;
  51648. }
  51649. case DUK_OP_LDCONST: {
  51650. duk_small_uint_fast_t a;
  51651. duk_uint_fast_t bc;
  51652. duk_tval tv_tmp;
  51653. duk_tval *tv1, *tv2;
  51654. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51655. bc = DUK_DEC_BC(ins); tv2 = DUK__CONSTP(bc);
  51656. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  51657. DUK_TVAL_SET_TVAL(tv1, tv2);
  51658. DUK_TVAL_INCREF(thr, tv2); /* may be e.g. string */
  51659. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  51660. break;
  51661. }
  51662. case DUK_OP_LDINT: {
  51663. duk_small_uint_fast_t a;
  51664. duk_int_fast_t bc;
  51665. duk_tval tv_tmp;
  51666. duk_tval *tv1;
  51667. #if defined(DUK_USE_FASTINT)
  51668. duk_int32_t val;
  51669. #else
  51670. duk_double_t val;
  51671. #endif
  51672. #if defined(DUK_USE_FASTINT)
  51673. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51674. bc = DUK_DEC_BC(ins); val = (duk_int32_t) (bc - DUK_BC_LDINT_BIAS);
  51675. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  51676. DUK_TVAL_SET_FASTINT_I32(tv1, val);
  51677. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  51678. #else
  51679. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51680. bc = DUK_DEC_BC(ins); val = (duk_double_t) (bc - DUK_BC_LDINT_BIAS);
  51681. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  51682. DUK_TVAL_SET_NUMBER(tv1, val);
  51683. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  51684. #endif
  51685. break;
  51686. }
  51687. case DUK_OP_LDINTX: {
  51688. duk_small_uint_fast_t a;
  51689. duk_tval *tv1;
  51690. duk_double_t val;
  51691. /* LDINTX is not necessarily in FASTINT range, so
  51692. * no fast path for now.
  51693. *
  51694. * XXX: perhaps restrict LDINTX to fastint range, wider
  51695. * range very rarely needed.
  51696. */
  51697. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51698. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv1));
  51699. val = DUK_TVAL_GET_NUMBER(tv1) * ((duk_double_t) (1L << DUK_BC_LDINTX_SHIFT)) +
  51700. (duk_double_t) DUK_DEC_BC(ins);
  51701. #if defined(DUK_USE_FASTINT)
  51702. DUK_TVAL_SET_NUMBER_CHKFAST(tv1, val);
  51703. #else
  51704. DUK_TVAL_SET_NUMBER(tv1, val);
  51705. #endif
  51706. break;
  51707. }
  51708. case DUK_OP_MPUTOBJ:
  51709. case DUK_OP_MPUTOBJI: {
  51710. duk_context *ctx = (duk_context *) thr;
  51711. duk_small_uint_fast_t a;
  51712. duk_tval *tv1;
  51713. duk_hobject *obj;
  51714. duk_uint_fast_t idx;
  51715. duk_small_uint_fast_t count;
  51716. /* A -> register of target object
  51717. * B -> first register of key/value pair list
  51718. * C -> number of key/value pairs
  51719. */
  51720. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51721. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv1));
  51722. obj = DUK_TVAL_GET_OBJECT(tv1);
  51723. idx = (duk_uint_fast_t) DUK_DEC_B(ins);
  51724. if (DUK_DEC_OP(ins) == DUK_OP_MPUTOBJI) {
  51725. duk_tval *tv_ind = DUK__REGP(idx);
  51726. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  51727. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  51728. }
  51729. count = (duk_small_uint_fast_t) DUK_DEC_C(ins);
  51730. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  51731. if (DUK_UNLIKELY(idx + count * 2 > (duk_uint_fast_t) duk_get_top(ctx))) {
  51732. /* XXX: use duk_is_valid_index() instead? */
  51733. /* XXX: improve check; check against nregs, not against top */
  51734. DUK__INTERNAL_ERROR("MPUTOBJ out of bounds");
  51735. }
  51736. #endif
  51737. duk_push_hobject(ctx, obj);
  51738. while (count > 0) {
  51739. /* XXX: faster initialization (direct access or better primitives) */
  51740. duk_push_tval(ctx, DUK__REGP(idx));
  51741. DUK_ASSERT(duk_is_string(ctx, -1));
  51742. duk_push_tval(ctx, DUK__REGP(idx + 1)); /* -> [... obj key value] */
  51743. duk_xdef_prop_wec(ctx, -3); /* -> [... obj] */
  51744. count--;
  51745. idx += 2;
  51746. }
  51747. duk_pop(ctx); /* [... obj] -> [...] */
  51748. break;
  51749. }
  51750. case DUK_OP_MPUTARR:
  51751. case DUK_OP_MPUTARRI: {
  51752. duk_context *ctx = (duk_context *) thr;
  51753. duk_small_uint_fast_t a;
  51754. duk_tval *tv1;
  51755. duk_hobject *obj;
  51756. duk_uint_fast_t idx;
  51757. duk_small_uint_fast_t count;
  51758. duk_uint32_t arr_idx;
  51759. /* A -> register of target object
  51760. * B -> first register of value data (start_index, value1, value2, ..., valueN)
  51761. * C -> number of key/value pairs (N)
  51762. */
  51763. a = DUK_DEC_A(ins); tv1 = DUK__REGP(a);
  51764. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv1));
  51765. obj = DUK_TVAL_GET_OBJECT(tv1);
  51766. DUK_ASSERT(obj != NULL);
  51767. idx = (duk_uint_fast_t) DUK_DEC_B(ins);
  51768. if (DUK_DEC_OP(ins) == DUK_OP_MPUTARRI) {
  51769. duk_tval *tv_ind = DUK__REGP(idx);
  51770. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  51771. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  51772. }
  51773. count = (duk_small_uint_fast_t) DUK_DEC_C(ins);
  51774. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  51775. if (idx + count + 1 > (duk_uint_fast_t) duk_get_top(ctx)) {
  51776. /* XXX: use duk_is_valid_index() instead? */
  51777. /* XXX: improve check; check against nregs, not against top */
  51778. DUK__INTERNAL_ERROR("MPUTARR out of bounds");
  51779. }
  51780. #endif
  51781. tv1 = DUK__REGP(idx);
  51782. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv1));
  51783. arr_idx = (duk_uint32_t) DUK_TVAL_GET_NUMBER(tv1);
  51784. idx++;
  51785. duk_push_hobject(ctx, obj);
  51786. while (count > 0) {
  51787. /* duk_xdef_prop() will define an own property without any array
  51788. * special behaviors. We'll need to set the array length explicitly
  51789. * in the end. For arrays with elisions, the compiler will emit an
  51790. * explicit SETALEN which will update the length.
  51791. */
  51792. /* XXX: because we're dealing with 'own' properties of a fresh array,
  51793. * the array initializer should just ensure that the array has a large
  51794. * enough array part and write the values directly into array part,
  51795. * and finally set 'length' manually in the end (as already happens now).
  51796. */
  51797. duk_push_tval(ctx, DUK__REGP(idx)); /* -> [... obj value] */
  51798. duk_xdef_prop_index_wec(ctx, -2, arr_idx); /* -> [... obj] */
  51799. /* XXX: could use at least one fewer loop counters */
  51800. count--;
  51801. idx++;
  51802. arr_idx++;
  51803. }
  51804. /* XXX: E5.1 Section 11.1.4 coerces the final length through
  51805. * ToUint32() which is odd but happens now as a side effect of
  51806. * 'arr_idx' type.
  51807. */
  51808. duk_hobject_set_length(thr, obj, (duk_uint32_t) arr_idx);
  51809. duk_pop(ctx); /* [... obj] -> [...] */
  51810. break;
  51811. }
  51812. case DUK_OP_NEW:
  51813. case DUK_OP_NEWI: {
  51814. duk_context *ctx = (duk_context *) thr;
  51815. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  51816. duk_uint_fast_t idx;
  51817. duk_small_uint_fast_t i;
  51818. /* A -> unused (reserved for flags, for consistency with DUK_OP_CALL)
  51819. * B -> target register and start reg: constructor, arg1, ..., argN
  51820. * (for DUK_OP_NEWI, 'b' is indirect)
  51821. * C -> num args (N)
  51822. */
  51823. /* Note: duk_new() will call the constuctor using duk_handle_call().
  51824. * A constructor call prevents a yield from inside the constructor,
  51825. * even if the constructor is an Ecmascript function.
  51826. */
  51827. /* XXX: unnecessary copying of values? Just set 'top' to
  51828. * b + c, and let the return handling fix up the stack frame?
  51829. */
  51830. idx = (duk_uint_fast_t) DUK_DEC_B(ins);
  51831. if (DUK_DEC_OP(ins) == DUK_OP_NEWI) {
  51832. duk_tval *tv_ind = DUK__REGP(idx);
  51833. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  51834. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  51835. }
  51836. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  51837. if (idx + c + 1 > (duk_uint_fast_t) duk_get_top(ctx)) {
  51838. /* XXX: use duk_is_valid_index() instead? */
  51839. /* XXX: improve check; check against nregs, not against top */
  51840. DUK__INTERNAL_ERROR("NEW out of bounds");
  51841. }
  51842. #endif
  51843. duk_require_stack(ctx, (duk_idx_t) c);
  51844. duk_push_tval(ctx, DUK__REGP(idx));
  51845. for (i = 0; i < c; i++) {
  51846. duk_push_tval(ctx, DUK__REGP(idx + i + 1));
  51847. }
  51848. duk_new(ctx, (duk_idx_t) c); /* [... constructor arg1 ... argN] -> [retval] */
  51849. DUK_DDD(DUK_DDDPRINT("NEW -> %!iT", (duk_tval *) duk_get_tval(ctx, -1)));
  51850. duk_replace(ctx, (duk_idx_t) idx);
  51851. break;
  51852. }
  51853. case DUK_OP_REGEXP: {
  51854. #ifdef DUK_USE_REGEXP_SUPPORT
  51855. duk_context *ctx = (duk_context *) thr;
  51856. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  51857. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  51858. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  51859. /* A -> target register
  51860. * B -> bytecode (also contains flags)
  51861. * C -> escaped source
  51862. */
  51863. duk_push_tval(ctx, DUK__REGCONSTP(c));
  51864. duk_push_tval(ctx, DUK__REGCONSTP(b)); /* -> [ ... escaped_source bytecode ] */
  51865. duk_regexp_create_instance(thr); /* -> [ ... regexp_instance ] */
  51866. DUK_DDD(DUK_DDDPRINT("regexp instance: %!iT", (duk_tval *) duk_get_tval(ctx, -1)));
  51867. duk_replace(ctx, (duk_idx_t) a);
  51868. #else
  51869. /* The compiler should never emit DUK_OP_REGEXP if there is no
  51870. * regexp support.
  51871. */
  51872. DUK__INTERNAL_ERROR("no regexp support");
  51873. #endif
  51874. break;
  51875. }
  51876. case DUK_OP_CSREG:
  51877. case DUK_OP_CSREGI: {
  51878. /*
  51879. * Assuming a register binds to a variable declared within this
  51880. * function (a declarative binding), the 'this' for the call
  51881. * setup is always 'undefined'. E5 Section 10.2.1.1.6.
  51882. */
  51883. duk_context *ctx = (duk_context *) thr;
  51884. duk_small_uint_fast_t b = DUK_DEC_B(ins); /* restricted to regs */
  51885. duk_uint_fast_t idx;
  51886. /* A -> target register (A, A+1) for call setup
  51887. * (for DUK_OP_CSREGI, 'a' is indirect)
  51888. * B -> register containing target function (not type checked here)
  51889. */
  51890. /* XXX: direct manipulation, or duk_replace_tval() */
  51891. /* Note: target registers a and a+1 may overlap with DUK__REGP(b).
  51892. * Careful here.
  51893. */
  51894. idx = (duk_uint_fast_t) DUK_DEC_A(ins);
  51895. if (DUK_DEC_OP(ins) == DUK_OP_CSREGI) {
  51896. duk_tval *tv_ind = DUK__REGP(idx);
  51897. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  51898. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  51899. }
  51900. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  51901. if (idx + 2 > (duk_uint_fast_t) duk_get_top(ctx)) {
  51902. /* XXX: use duk_is_valid_index() instead? */
  51903. /* XXX: improve check; check against nregs, not against top */
  51904. DUK__INTERNAL_ERROR("CSREG out of bounds");
  51905. }
  51906. #endif
  51907. duk_push_tval(ctx, DUK__REGP(b));
  51908. duk_replace(ctx, (duk_idx_t) idx);
  51909. duk_push_undefined(ctx);
  51910. duk_replace(ctx, (duk_idx_t) (idx + 1));
  51911. break;
  51912. }
  51913. case DUK_OP_GETVAR: {
  51914. duk_context *ctx = (duk_context *) thr;
  51915. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  51916. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  51917. duk_tval *tv1;
  51918. duk_hstring *name;
  51919. tv1 = DUK__CONSTP(bc);
  51920. DUK_ASSERT(DUK_TVAL_IS_STRING(tv1));
  51921. name = DUK_TVAL_GET_STRING(tv1);
  51922. DUK_ASSERT(name != NULL);
  51923. DUK_DDD(DUK_DDDPRINT("GETVAR: '%!O'", (duk_heaphdr *) name));
  51924. (void) duk_js_getvar_activation(thr, act, name, 1 /*throw*/); /* -> [... val this] */
  51925. duk_pop(ctx); /* 'this' binding is not needed here */
  51926. duk_replace(ctx, (duk_idx_t) a);
  51927. break;
  51928. }
  51929. case DUK_OP_PUTVAR: {
  51930. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  51931. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  51932. duk_tval *tv1;
  51933. duk_hstring *name;
  51934. tv1 = DUK__CONSTP(bc);
  51935. DUK_ASSERT(DUK_TVAL_IS_STRING(tv1));
  51936. name = DUK_TVAL_GET_STRING(tv1);
  51937. DUK_ASSERT(name != NULL);
  51938. /* XXX: putvar takes a duk_tval pointer, which is awkward and
  51939. * should be reworked.
  51940. */
  51941. tv1 = DUK__REGP(a); /* val */
  51942. duk_js_putvar_activation(thr, act, name, tv1, DUK__STRICT());
  51943. break;
  51944. }
  51945. case DUK_OP_DECLVAR: {
  51946. duk_context *ctx = (duk_context *) thr;
  51947. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  51948. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  51949. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  51950. duk_tval *tv1;
  51951. duk_hstring *name;
  51952. duk_small_uint_t prop_flags;
  51953. duk_bool_t is_func_decl;
  51954. duk_bool_t is_undef_value;
  51955. tv1 = DUK__REGCONSTP(b);
  51956. DUK_ASSERT(DUK_TVAL_IS_STRING(tv1));
  51957. name = DUK_TVAL_GET_STRING(tv1);
  51958. DUK_ASSERT(name != NULL);
  51959. is_undef_value = ((a & DUK_BC_DECLVAR_FLAG_UNDEF_VALUE) != 0);
  51960. is_func_decl = ((a & DUK_BC_DECLVAR_FLAG_FUNC_DECL) != 0);
  51961. /* XXX: declvar takes an duk_tval pointer, which is awkward and
  51962. * should be reworked.
  51963. */
  51964. /* Compiler is responsible for selecting property flags (configurability,
  51965. * writability, etc).
  51966. */
  51967. prop_flags = a & DUK_PROPDESC_FLAGS_MASK;
  51968. if (is_undef_value) {
  51969. duk_push_undefined(ctx);
  51970. } else {
  51971. duk_push_tval(ctx, DUK__REGCONSTP(c));
  51972. }
  51973. tv1 = duk_get_tval(ctx, -1);
  51974. if (duk_js_declvar_activation(thr, act, name, tv1, prop_flags, is_func_decl)) {
  51975. /* already declared, must update binding value */
  51976. tv1 = duk_get_tval(ctx, -1);
  51977. duk_js_putvar_activation(thr, act, name, tv1, DUK__STRICT());
  51978. }
  51979. duk_pop(ctx);
  51980. break;
  51981. }
  51982. case DUK_OP_DELVAR: {
  51983. duk_context *ctx = (duk_context *) thr;
  51984. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  51985. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  51986. duk_tval *tv1;
  51987. duk_hstring *name;
  51988. duk_bool_t rc;
  51989. tv1 = DUK__REGCONSTP(b);
  51990. DUK_ASSERT(DUK_TVAL_IS_STRING(tv1));
  51991. name = DUK_TVAL_GET_STRING(tv1);
  51992. DUK_ASSERT(name != NULL);
  51993. DUK_DDD(DUK_DDDPRINT("DELVAR '%!O'", (duk_heaphdr *) name));
  51994. rc = duk_js_delvar_activation(thr, act, name);
  51995. duk_push_boolean(ctx, rc);
  51996. duk_replace(ctx, (duk_idx_t) a);
  51997. break;
  51998. }
  51999. case DUK_OP_CSVAR:
  52000. case DUK_OP_CSVARI: {
  52001. /* 'this' value:
  52002. * E5 Section 6.b.i
  52003. *
  52004. * The only (standard) case where the 'this' binding is non-null is when
  52005. * (1) the variable is found in an object environment record, and
  52006. * (2) that object environment record is a 'with' block.
  52007. *
  52008. */
  52009. duk_context *ctx = (duk_context *) thr;
  52010. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52011. duk_uint_fast_t idx;
  52012. duk_tval *tv1;
  52013. duk_hstring *name;
  52014. tv1 = DUK__REGCONSTP(b);
  52015. DUK_ASSERT(DUK_TVAL_IS_STRING(tv1));
  52016. name = DUK_TVAL_GET_STRING(tv1);
  52017. DUK_ASSERT(name != NULL);
  52018. (void) duk_js_getvar_activation(thr, act, name, 1 /*throw*/); /* -> [... val this] */
  52019. /* Note: target registers a and a+1 may overlap with DUK__REGCONSTP(b)
  52020. * and DUK__REGCONSTP(c). Careful here.
  52021. */
  52022. idx = (duk_uint_fast_t) DUK_DEC_A(ins);
  52023. if (DUK_DEC_OP(ins) == DUK_OP_CSVARI) {
  52024. duk_tval *tv_ind = DUK__REGP(idx);
  52025. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  52026. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  52027. }
  52028. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  52029. if (idx + 2 > (duk_uint_fast_t) duk_get_top(ctx)) {
  52030. /* XXX: use duk_is_valid_index() instead? */
  52031. /* XXX: improve check; check against nregs, not against top */
  52032. DUK__INTERNAL_ERROR("CSVAR out of bounds");
  52033. }
  52034. #endif
  52035. duk_replace(ctx, (duk_idx_t) (idx + 1)); /* 'this' binding */
  52036. duk_replace(ctx, (duk_idx_t) idx); /* variable value (function, we hope, not checked here) */
  52037. break;
  52038. }
  52039. case DUK_OP_CLOSURE: {
  52040. duk_context *ctx = (duk_context *) thr;
  52041. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52042. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52043. duk_hobject *fun_temp;
  52044. /* A -> target reg
  52045. * BC -> inner function index
  52046. */
  52047. DUK_DDD(DUK_DDDPRINT("CLOSURE to target register %ld, fnum %ld (count %ld)",
  52048. (long) a, (long) bc, (long) DUK_HCOMPILEDFUNCTION_GET_FUNCS_COUNT(thr->heap, fun)));
  52049. DUK_ASSERT_DISABLE(bc >= 0); /* unsigned */
  52050. DUK_ASSERT((duk_uint_t) bc < (duk_uint_t) DUK_HCOMPILEDFUNCTION_GET_FUNCS_COUNT(thr->heap, fun));
  52051. fun_temp = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(thr->heap, fun)[bc];
  52052. DUK_ASSERT(fun_temp != NULL);
  52053. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(fun_temp));
  52054. DUK_DDD(DUK_DDDPRINT("CLOSURE: function template is: %p -> %!O",
  52055. (void *) fun_temp, (duk_heaphdr *) fun_temp));
  52056. if (act->lex_env == NULL) {
  52057. DUK_ASSERT(act->var_env == NULL);
  52058. duk_js_init_activation_environment_records_delayed(thr, act);
  52059. }
  52060. DUK_ASSERT(act->lex_env != NULL);
  52061. DUK_ASSERT(act->var_env != NULL);
  52062. /* functions always have a NEWENV flag, i.e. they get a
  52063. * new variable declaration environment, so only lex_env
  52064. * matters here.
  52065. */
  52066. duk_js_push_closure(thr,
  52067. (duk_hcompiledfunction *) fun_temp,
  52068. act->var_env,
  52069. act->lex_env);
  52070. duk_replace(ctx, (duk_idx_t) a);
  52071. break;
  52072. }
  52073. case DUK_OP_GETPROP: {
  52074. duk_context *ctx = (duk_context *) thr;
  52075. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52076. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52077. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52078. duk_tval *tv_obj;
  52079. duk_tval *tv_key;
  52080. duk_bool_t rc;
  52081. /* A -> target reg
  52082. * B -> object reg/const (may be const e.g. in "'foo'[1]")
  52083. * C -> key reg/const
  52084. */
  52085. tv_obj = DUK__REGCONSTP(b);
  52086. tv_key = DUK__REGCONSTP(c);
  52087. DUK_DDD(DUK_DDDPRINT("GETPROP: a=%ld obj=%!T, key=%!T",
  52088. (long) a,
  52089. (duk_tval *) DUK__REGCONSTP(b),
  52090. (duk_tval *) DUK__REGCONSTP(c)));
  52091. rc = duk_hobject_getprop(thr, tv_obj, tv_key); /* -> [val] */
  52092. DUK_UNREF(rc); /* ignore */
  52093. DUK_DDD(DUK_DDDPRINT("GETPROP --> %!T",
  52094. (duk_tval *) duk_get_tval(ctx, -1)));
  52095. tv_obj = NULL; /* invalidated */
  52096. tv_key = NULL; /* invalidated */
  52097. duk_replace(ctx, (duk_idx_t) a); /* val */
  52098. break;
  52099. }
  52100. case DUK_OP_PUTPROP: {
  52101. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52102. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52103. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52104. duk_tval *tv_obj;
  52105. duk_tval *tv_key;
  52106. duk_tval *tv_val;
  52107. duk_bool_t rc;
  52108. /* A -> object reg
  52109. * B -> key reg/const
  52110. * C -> value reg/const
  52111. *
  52112. * Note: intentional difference to register arrangement
  52113. * of e.g. GETPROP; 'A' must contain a register-only value.
  52114. */
  52115. tv_obj = DUK__REGP(a);
  52116. tv_key = DUK__REGCONSTP(b);
  52117. tv_val = DUK__REGCONSTP(c);
  52118. DUK_DDD(DUK_DDDPRINT("PUTPROP: obj=%!T, key=%!T, val=%!T",
  52119. (duk_tval *) DUK__REGP(a),
  52120. (duk_tval *) DUK__REGCONSTP(b),
  52121. (duk_tval *) DUK__REGCONSTP(c)));
  52122. rc = duk_hobject_putprop(thr, tv_obj, tv_key, tv_val, DUK__STRICT());
  52123. DUK_UNREF(rc); /* ignore */
  52124. DUK_DDD(DUK_DDDPRINT("PUTPROP --> obj=%!T, key=%!T, val=%!T",
  52125. (duk_tval *) DUK__REGP(a),
  52126. (duk_tval *) DUK__REGCONSTP(b),
  52127. (duk_tval *) DUK__REGCONSTP(c)));
  52128. tv_obj = NULL; /* invalidated */
  52129. tv_key = NULL; /* invalidated */
  52130. tv_val = NULL; /* invalidated */
  52131. break;
  52132. }
  52133. case DUK_OP_DELPROP: {
  52134. duk_context *ctx = (duk_context *) thr;
  52135. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52136. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52137. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52138. duk_tval *tv_obj;
  52139. duk_tval *tv_key;
  52140. duk_bool_t rc;
  52141. /* A -> result reg
  52142. * B -> object reg
  52143. * C -> key reg/const
  52144. */
  52145. tv_obj = DUK__REGP(b);
  52146. tv_key = DUK__REGCONSTP(c);
  52147. rc = duk_hobject_delprop(thr, tv_obj, tv_key, DUK__STRICT());
  52148. tv_obj = NULL; /* invalidated */
  52149. tv_key = NULL; /* invalidated */
  52150. duk_push_boolean(ctx, rc);
  52151. duk_replace(ctx, (duk_idx_t) a); /* result */
  52152. break;
  52153. }
  52154. case DUK_OP_CSPROP:
  52155. case DUK_OP_CSPROPI: {
  52156. duk_context *ctx = (duk_context *) thr;
  52157. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52158. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52159. duk_uint_fast_t idx;
  52160. duk_tval *tv_obj;
  52161. duk_tval *tv_key;
  52162. duk_bool_t rc;
  52163. /* E5 Section 11.2.3, step 6.a.i */
  52164. /* E5 Section 10.4.3 */
  52165. /* XXX: allow object to be a const, e.g. in 'foo'.toString()?
  52166. * On the other hand, DUK_REGCONSTP() is slower and generates
  52167. * more code.
  52168. */
  52169. tv_obj = DUK__REGP(b);
  52170. tv_key = DUK__REGCONSTP(c);
  52171. rc = duk_hobject_getprop(thr, tv_obj, tv_key); /* -> [val] */
  52172. DUK_UNREF(rc); /* unused */
  52173. tv_obj = NULL; /* invalidated */
  52174. tv_key = NULL; /* invalidated */
  52175. /* Note: target registers a and a+1 may overlap with DUK__REGP(b)
  52176. * and DUK__REGCONSTP(c). Careful here.
  52177. */
  52178. idx = (duk_uint_fast_t) DUK_DEC_A(ins);
  52179. if (DUK_DEC_OP(ins) == DUK_OP_CSPROPI) {
  52180. duk_tval *tv_ind = DUK__REGP(idx);
  52181. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  52182. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  52183. }
  52184. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  52185. if (idx + 2 > (duk_uint_fast_t) duk_get_top(ctx)) {
  52186. /* XXX: use duk_is_valid_index() instead? */
  52187. /* XXX: improve check; check against nregs, not against top */
  52188. DUK__INTERNAL_ERROR("CSPROP out of bounds");
  52189. }
  52190. #endif
  52191. duk_push_tval(ctx, DUK__REGP(b)); /* [ ... val obj ] */
  52192. duk_replace(ctx, (duk_idx_t) (idx + 1)); /* 'this' binding */
  52193. duk_replace(ctx, (duk_idx_t) idx); /* val */
  52194. break;
  52195. }
  52196. case DUK_OP_ADD:
  52197. case DUK_OP_SUB:
  52198. case DUK_OP_MUL:
  52199. case DUK_OP_DIV:
  52200. case DUK_OP_MOD: {
  52201. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52202. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52203. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52204. duk_small_uint_fast_t op = DUK_DEC_OP(ins);
  52205. if (op == DUK_OP_ADD) {
  52206. /*
  52207. * Handling DUK_OP_ADD this way is more compact (experimentally)
  52208. * than a separate case with separate argument decoding.
  52209. */
  52210. duk__vm_arith_add(thr, DUK__REGCONSTP(b), DUK__REGCONSTP(c), a);
  52211. } else {
  52212. duk__vm_arith_binary_op(thr, DUK__REGCONSTP(b), DUK__REGCONSTP(c), a, op);
  52213. }
  52214. break;
  52215. }
  52216. case DUK_OP_BAND:
  52217. case DUK_OP_BOR:
  52218. case DUK_OP_BXOR:
  52219. case DUK_OP_BASL:
  52220. case DUK_OP_BLSR:
  52221. case DUK_OP_BASR: {
  52222. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52223. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52224. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52225. duk_small_uint_fast_t op = DUK_DEC_OP(ins);
  52226. duk__vm_bitwise_binary_op(thr, DUK__REGCONSTP(b), DUK__REGCONSTP(c), a, op);
  52227. break;
  52228. }
  52229. case DUK_OP_EQ:
  52230. case DUK_OP_NEQ: {
  52231. duk_context *ctx = (duk_context *) thr;
  52232. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52233. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52234. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52235. duk_bool_t tmp;
  52236. /* E5 Sections 11.9.1, 11.9.3 */
  52237. tmp = duk_js_equals(thr, DUK__REGCONSTP(b), DUK__REGCONSTP(c));
  52238. if (DUK_DEC_OP(ins) == DUK_OP_NEQ) {
  52239. tmp = !tmp;
  52240. }
  52241. duk_push_boolean(ctx, tmp);
  52242. duk_replace(ctx, (duk_idx_t) a);
  52243. break;
  52244. }
  52245. case DUK_OP_SEQ:
  52246. case DUK_OP_SNEQ: {
  52247. duk_context *ctx = (duk_context *) thr;
  52248. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52249. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52250. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52251. duk_bool_t tmp;
  52252. /* E5 Sections 11.9.1, 11.9.3 */
  52253. tmp = duk_js_strict_equals(DUK__REGCONSTP(b), DUK__REGCONSTP(c));
  52254. if (DUK_DEC_OP(ins) == DUK_OP_SNEQ) {
  52255. tmp = !tmp;
  52256. }
  52257. duk_push_boolean(ctx, tmp);
  52258. duk_replace(ctx, (duk_idx_t) a);
  52259. break;
  52260. }
  52261. /* Note: combining comparison ops must be done carefully because
  52262. * of uncomparable values (NaN): it's not necessarily true that
  52263. * (x >= y) === !(x < y). Also, evaluation order matters, and
  52264. * although it would only seem to affect the compiler this is
  52265. * actually not the case, because there are also run-time coercions
  52266. * of the arguments (with potential side effects).
  52267. *
  52268. * XXX: can be combined; check code size.
  52269. */
  52270. case DUK_OP_GT: {
  52271. duk_context *ctx = (duk_context *) thr;
  52272. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52273. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52274. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52275. duk_bool_t tmp;
  52276. /* x > y --> y < x */
  52277. tmp = duk_js_compare_helper(thr,
  52278. DUK__REGCONSTP(c), /* y */
  52279. DUK__REGCONSTP(b), /* x */
  52280. 0); /* flags */
  52281. duk_push_boolean(ctx, tmp);
  52282. duk_replace(ctx, (duk_idx_t) a);
  52283. break;
  52284. }
  52285. case DUK_OP_GE: {
  52286. duk_context *ctx = (duk_context *) thr;
  52287. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52288. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52289. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52290. duk_bool_t tmp;
  52291. /* x >= y --> not (x < y) */
  52292. tmp = duk_js_compare_helper(thr,
  52293. DUK__REGCONSTP(b), /* x */
  52294. DUK__REGCONSTP(c), /* y */
  52295. DUK_COMPARE_FLAG_EVAL_LEFT_FIRST |
  52296. DUK_COMPARE_FLAG_NEGATE); /* flags */
  52297. duk_push_boolean(ctx, tmp);
  52298. duk_replace(ctx, (duk_idx_t) a);
  52299. break;
  52300. }
  52301. case DUK_OP_LT: {
  52302. duk_context *ctx = (duk_context *) thr;
  52303. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52304. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52305. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52306. duk_bool_t tmp;
  52307. /* x < y */
  52308. tmp = duk_js_compare_helper(thr,
  52309. DUK__REGCONSTP(b), /* x */
  52310. DUK__REGCONSTP(c), /* y */
  52311. DUK_COMPARE_FLAG_EVAL_LEFT_FIRST); /* flags */
  52312. duk_push_boolean(ctx, tmp);
  52313. duk_replace(ctx, (duk_idx_t) a);
  52314. break;
  52315. }
  52316. case DUK_OP_LE: {
  52317. duk_context *ctx = (duk_context *) thr;
  52318. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52319. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52320. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52321. duk_bool_t tmp;
  52322. /* x <= y --> not (x > y) --> not (y < x) */
  52323. tmp = duk_js_compare_helper(thr,
  52324. DUK__REGCONSTP(c), /* y */
  52325. DUK__REGCONSTP(b), /* x */
  52326. DUK_COMPARE_FLAG_NEGATE); /* flags */
  52327. duk_push_boolean(ctx, tmp);
  52328. duk_replace(ctx, (duk_idx_t) a);
  52329. break;
  52330. }
  52331. case DUK_OP_IF: {
  52332. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52333. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52334. duk_bool_t tmp;
  52335. tmp = duk_js_toboolean(DUK__REGCONSTP(b));
  52336. if (tmp == (duk_bool_t) a) {
  52337. /* if boolean matches A, skip next inst */
  52338. act->pc++;
  52339. } else {
  52340. ;
  52341. }
  52342. break;
  52343. }
  52344. case DUK_OP_JUMP: {
  52345. duk_int_fast_t abc = DUK_DEC_ABC(ins);
  52346. act->pc += abc - DUK_BC_JUMP_BIAS;
  52347. break;
  52348. }
  52349. case DUK_OP_RETURN: {
  52350. duk_context *ctx = (duk_context *) thr;
  52351. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52352. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52353. /* duk_small_uint_fast_t c = DUK_DEC_C(ins); */
  52354. duk_tval *tv_val;
  52355. /* A -> flags
  52356. * B -> return value reg/const
  52357. * C -> currently unused
  52358. */
  52359. /* A fast return avoids full longjmp handling for a set of
  52360. * scenarios which hopefully represents the common cases.
  52361. * The compiler is responsible for emitting fast returns
  52362. * only when they are safe. Currently this means that there
  52363. * is nothing on the catch stack (not even label catchers).
  52364. * The speed advantage of fast returns (avoiding longjmp) is
  52365. * not very high, around 10-15%.
  52366. */
  52367. #if 0 /* XXX: Disabled for 1.0 release */
  52368. if (a & DUK_BC_RETURN_FLAG_FAST) {
  52369. DUK_DDD(DUK_DDDPRINT("FASTRETURN attempt a=%ld b=%ld", (long) a, (long) b));
  52370. if (duk__handle_fast_return(thr,
  52371. (a & DUK_BC_RETURN_FLAG_HAVE_RETVAL) ? DUK__REGCONSTP(b) : NULL,
  52372. entry_thread,
  52373. entry_callstack_top)) {
  52374. DUK_DDD(DUK_DDDPRINT("FASTRETURN success a=%ld b=%ld", (long) a, (long) b));
  52375. goto restart_execution;
  52376. }
  52377. }
  52378. #endif
  52379. /* No fast return, slow path. */
  52380. DUK_DDD(DUK_DDDPRINT("SLOWRETURN a=%ld b=%ld", (long) a, (long) b));
  52381. if (a & DUK_BC_RETURN_FLAG_HAVE_RETVAL) {
  52382. tv_val = DUK__REGCONSTP(b);
  52383. #if defined(DUK_OPT_FASTINT)
  52384. /* Explicit check for fastint downgrade. Do
  52385. * it also for consts for now, which is odd
  52386. * but harmless.
  52387. */
  52388. /* XXX: restrict to reg values only? */
  52389. DUK_TVAL_CHKFAST_INPLACE(tv_val);
  52390. #endif
  52391. duk_push_tval(ctx, tv_val);
  52392. } else {
  52393. duk_push_undefined(ctx);
  52394. }
  52395. duk_err_setup_heap_ljstate(thr, DUK_LJ_TYPE_RETURN);
  52396. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL); /* in bytecode executor, should always be set */
  52397. duk_err_longjmp(thr);
  52398. DUK_UNREACHABLE();
  52399. break;
  52400. }
  52401. case DUK_OP_CALL:
  52402. case DUK_OP_CALLI: {
  52403. duk_context *ctx = (duk_context *) thr;
  52404. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52405. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52406. duk_uint_fast_t idx;
  52407. duk_small_uint_t call_flags;
  52408. duk_small_uint_t flag_tailcall;
  52409. duk_small_uint_t flag_evalcall;
  52410. duk_tval *tv_func;
  52411. duk_hobject *obj_func;
  52412. duk_bool_t setup_rc;
  52413. duk_idx_t num_stack_args;
  52414. /* A -> flags
  52415. * B -> base register for call (base -> func, base+1 -> this, base+2 -> arg1 ... base+2+N-1 -> argN)
  52416. * (for DUK_OP_CALLI, 'b' is indirect)
  52417. * C -> nargs
  52418. */
  52419. /* these are not necessarily 0 or 1 (may be other non-zero), that's ok */
  52420. flag_tailcall = (a & DUK_BC_CALL_FLAG_TAILCALL);
  52421. flag_evalcall = (a & DUK_BC_CALL_FLAG_EVALCALL);
  52422. idx = (duk_uint_fast_t) DUK_DEC_B(ins);
  52423. if (DUK_DEC_OP(ins) == DUK_OP_CALLI) {
  52424. duk_tval *tv_ind = DUK__REGP(idx);
  52425. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  52426. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  52427. }
  52428. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  52429. if (!duk_is_valid_index(ctx, (duk_idx_t) idx)) {
  52430. /* XXX: improve check; check against nregs, not against top */
  52431. DUK__INTERNAL_ERROR("CALL out of bounds");
  52432. }
  52433. #endif
  52434. /*
  52435. * To determine whether to use an optimized Ecmascript-to-Ecmascript
  52436. * call, we need to know whether the final, non-bound function is an
  52437. * Ecmascript function.
  52438. *
  52439. * This is now implemented so that we start to do an ecma-to-ecma call
  52440. * setup which will resolve the bound chain as the first thing. If the
  52441. * final function is not eligible, the return value indicates that the
  52442. * ecma-to-ecma call is not possible. The setup will overwrite the call
  52443. * target at DUK__REGP(idx) with the final, non-bound function (which
  52444. * may be a lightfunc), and fudge arguments if necessary.
  52445. *
  52446. * XXX: If an ecma-to-ecma call is not possible, this initial call
  52447. * setup will do bound function chain resolution but won't do the
  52448. * "effective this binding" resolution which is quite confusing.
  52449. * Perhaps add a helper for doing bound function and effective this
  52450. * binding resolution - and call that explicitly? Ecma-to-ecma call
  52451. * setup and normal function handling can then assume this prestep has
  52452. * been done by the caller.
  52453. */
  52454. duk_set_top(ctx, (duk_idx_t) (idx + c + 2)); /* [ ... func this arg1 ... argN ] */
  52455. call_flags = 0;
  52456. if (flag_tailcall) {
  52457. /* We request a tailcall, but in some corner cases
  52458. * call handling can decide that a tailcall is
  52459. * actually not possible.
  52460. * See: test-bug-tailcall-preventyield-assert.c.
  52461. */
  52462. call_flags |= DUK_CALL_FLAG_IS_TAILCALL;
  52463. }
  52464. /* Compared to duk_handle_call():
  52465. * - protected call: never
  52466. * - ignore recursion limit: never
  52467. */
  52468. num_stack_args = c;
  52469. setup_rc = duk_handle_ecma_call_setup(thr,
  52470. num_stack_args,
  52471. call_flags);
  52472. if (setup_rc) {
  52473. /* Ecma-to-ecma call possible, may or may not be a tailcall.
  52474. * Avoid C recursion by being clever.
  52475. */
  52476. DUK_DDD(DUK_DDDPRINT("ecma-to-ecma call setup possible, restart execution"));
  52477. goto restart_execution;
  52478. }
  52479. DUK_DDD(DUK_DDDPRINT("ecma-to-ecma call not possible, target is native (may be lightfunc)"));
  52480. /* Recompute argument count: bound function handling may have shifted. */
  52481. num_stack_args = duk_get_top(ctx) - (idx + 2);
  52482. DUK_DDD(DUK_DDDPRINT("recomputed arg count: %ld\n", (long) num_stack_args));
  52483. tv_func = DUK__REGP(idx); /* Relookup if relocated */
  52484. if (DUK_TVAL_IS_LIGHTFUNC(tv_func)) {
  52485. call_flags = 0; /* not protected, respect reclimit, not constructor */
  52486. /* There is no eval() special handling here: eval() is never
  52487. * automatically converted to a lightfunc.
  52488. */
  52489. DUK_ASSERT(DUK_TVAL_GET_LIGHTFUNC_FUNCPTR(tv_func) != duk_bi_global_object_eval);
  52490. duk_handle_call(thr,
  52491. num_stack_args,
  52492. call_flags);
  52493. /* duk_js_call.c is required to restore the stack reserve
  52494. * so we only need to reset the top.
  52495. */
  52496. duk_set_top(ctx, (duk_idx_t) fun->nregs);
  52497. /* No need to reinit setjmp() catchpoint, as call handling
  52498. * will store and restore our state.
  52499. */
  52500. } else {
  52501. /* Call setup checks callability. */
  52502. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv_func));
  52503. obj_func = DUK_TVAL_GET_OBJECT(tv_func);
  52504. DUK_ASSERT(obj_func != NULL);
  52505. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(obj_func));
  52506. /*
  52507. * Other cases, use C recursion.
  52508. *
  52509. * If a tailcall was requested we ignore it and execute a normal call.
  52510. * Since Duktape 0.11.0 the compiler emits a RETURN opcode even after
  52511. * a tailcall to avoid test-bug-tailcall-thread-yield-resume.js.
  52512. *
  52513. * Direct eval call: (1) call target (before following bound function
  52514. * chain) is the built-in eval() function, and (2) call was made with
  52515. * the identifier 'eval'.
  52516. */
  52517. call_flags = 0; /* not protected, respect reclimit, not constructor */
  52518. if (DUK_HOBJECT_IS_NATIVEFUNCTION(obj_func) &&
  52519. ((duk_hnativefunction *) obj_func)->func == duk_bi_global_object_eval) {
  52520. if (flag_evalcall) {
  52521. DUK_DDD(DUK_DDDPRINT("call target is eval, call identifier was 'eval' -> direct eval"));
  52522. call_flags |= DUK_CALL_FLAG_DIRECT_EVAL;
  52523. } else {
  52524. DUK_DDD(DUK_DDDPRINT("call target is eval, call identifier was not 'eval' -> indirect eval"));
  52525. }
  52526. }
  52527. duk_handle_call(thr,
  52528. num_stack_args,
  52529. call_flags);
  52530. /* duk_js_call.c is required to restore the stack reserve
  52531. * so we only need to reset the top.
  52532. */
  52533. duk_set_top(ctx, (duk_idx_t) fun->nregs);
  52534. /* No need to reinit setjmp() catchpoint, as call handling
  52535. * will store and restore our state.
  52536. */
  52537. }
  52538. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  52539. /* When debugger is enabled, we need to recheck the activation
  52540. * status after returning.
  52541. */
  52542. goto restart_execution;
  52543. #endif
  52544. break;
  52545. }
  52546. case DUK_OP_TRYCATCH: {
  52547. duk_context *ctx = (duk_context *) thr;
  52548. duk_catcher *cat;
  52549. duk_tval *tv1;
  52550. duk_small_uint_fast_t a;
  52551. duk_small_uint_fast_t b;
  52552. duk_small_uint_fast_t c;
  52553. /* A -> flags
  52554. * B -> reg_catch; base register for 2 regs
  52555. * C -> semantics depend on flags: var_name or with_target
  52556. *
  52557. * If DUK_BC_TRYCATCH_FLAG_CATCH_BINDING set:
  52558. * C is constant index for catch binding variable name.
  52559. * Automatic declarative environment is established for
  52560. * the duration of the 'catch' clause.
  52561. *
  52562. * If DUK_BC_TRYCATCH_FLAG_WITH_BINDING set:
  52563. * C is reg/const index for with 'target value', which
  52564. * is coerced to an object and then used as a binding
  52565. * object for an environment record. The binding is
  52566. * initialized here, for the 'try' clause.
  52567. *
  52568. * Note that a TRYCATCH generated for a 'with' statement has no
  52569. * catch or finally parts.
  52570. */
  52571. /* XXX: side effect handling is quite awkward here */
  52572. DUK_DDD(DUK_DDDPRINT("TRYCATCH: reg_catch=%ld, var_name/with_target=%ld, have_catch=%ld, "
  52573. "have_finally=%ld, catch_binding=%ld, with_binding=%ld (flags=0x%02lx)",
  52574. (long) DUK_DEC_B(ins),
  52575. (long) DUK_DEC_C(ins),
  52576. (long) (DUK_DEC_A(ins) & DUK_BC_TRYCATCH_FLAG_HAVE_CATCH ? 1 : 0),
  52577. (long) (DUK_DEC_A(ins) & DUK_BC_TRYCATCH_FLAG_HAVE_FINALLY ? 1 : 0),
  52578. (long) (DUK_DEC_A(ins) & DUK_BC_TRYCATCH_FLAG_CATCH_BINDING ? 1 : 0),
  52579. (long) (DUK_DEC_A(ins) & DUK_BC_TRYCATCH_FLAG_WITH_BINDING ? 1 : 0),
  52580. (unsigned long) DUK_DEC_A(ins)));
  52581. a = DUK_DEC_A(ins);
  52582. b = DUK_DEC_B(ins);
  52583. c = DUK_DEC_C(ins);
  52584. DUK_ASSERT(thr->callstack_top >= 1);
  52585. /* 'with' target must be created first, in case we run out of memory */
  52586. /* XXX: refactor out? */
  52587. if (a & DUK_BC_TRYCATCH_FLAG_WITH_BINDING) {
  52588. DUK_DDD(DUK_DDDPRINT("need to initialize a with binding object"));
  52589. if (act->lex_env == NULL) {
  52590. DUK_ASSERT(act->var_env == NULL);
  52591. DUK_DDD(DUK_DDDPRINT("delayed environment initialization"));
  52592. /* must relookup act in case of side effects */
  52593. duk_js_init_activation_environment_records_delayed(thr, act);
  52594. act = thr->callstack + thr->callstack_top - 1;
  52595. }
  52596. DUK_ASSERT(act->lex_env != NULL);
  52597. DUK_ASSERT(act->var_env != NULL);
  52598. (void) duk_push_object_helper(ctx,
  52599. DUK_HOBJECT_FLAG_EXTENSIBLE |
  52600. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJENV),
  52601. -1); /* no prototype, updated below */
  52602. duk_push_tval(ctx, DUK__REGCONSTP(c));
  52603. duk_to_object(ctx, -1);
  52604. duk_dup(ctx, -1);
  52605. /* [ ... env target ] */
  52606. /* [ ... env target target ] */
  52607. duk_xdef_prop_stridx(thr, -3, DUK_STRIDX_INT_TARGET, DUK_PROPDESC_FLAGS_NONE);
  52608. duk_xdef_prop_stridx(thr, -2, DUK_STRIDX_INT_THIS, DUK_PROPDESC_FLAGS_NONE); /* always provideThis=true */
  52609. /* [ ... env ] */
  52610. DUK_DDD(DUK_DDDPRINT("environment for with binding: %!iT",
  52611. (duk_tval *) duk_get_tval(ctx, -1)));
  52612. }
  52613. /* allocate catcher and populate it (should be atomic) */
  52614. duk_hthread_catchstack_grow(thr);
  52615. cat = thr->catchstack + thr->catchstack_top;
  52616. DUK_ASSERT(thr->catchstack_top + 1 <= thr->catchstack_size);
  52617. thr->catchstack_top++;
  52618. cat->flags = DUK_CAT_TYPE_TCF;
  52619. cat->h_varname = NULL;
  52620. if (a & DUK_BC_TRYCATCH_FLAG_HAVE_CATCH) {
  52621. cat->flags |= DUK_CAT_FLAG_CATCH_ENABLED;
  52622. }
  52623. if (a & DUK_BC_TRYCATCH_FLAG_HAVE_FINALLY) {
  52624. cat->flags |= DUK_CAT_FLAG_FINALLY_ENABLED;
  52625. }
  52626. if (a & DUK_BC_TRYCATCH_FLAG_CATCH_BINDING) {
  52627. DUK_DDD(DUK_DDDPRINT("catch binding flag set to catcher"));
  52628. cat->flags |= DUK_CAT_FLAG_CATCH_BINDING_ENABLED;
  52629. tv1 = DUK__CONSTP(c);
  52630. DUK_ASSERT(DUK_TVAL_IS_STRING(tv1));
  52631. cat->h_varname = DUK_TVAL_GET_STRING(tv1);
  52632. } else if (a & DUK_BC_TRYCATCH_FLAG_WITH_BINDING) {
  52633. /* env created above to stack top */
  52634. duk_hobject *new_env;
  52635. DUK_DDD(DUK_DDDPRINT("lexenv active flag set to catcher"));
  52636. cat->flags |= DUK_CAT_FLAG_LEXENV_ACTIVE;
  52637. DUK_DDD(DUK_DDDPRINT("activating object env: %!iT",
  52638. (duk_tval *) duk_get_tval(ctx, -1)));
  52639. DUK_ASSERT(act->lex_env != NULL);
  52640. new_env = duk_get_hobject(ctx, -1);
  52641. DUK_ASSERT(new_env != NULL);
  52642. act = thr->callstack + thr->callstack_top - 1; /* relookup (side effects) */
  52643. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, new_env, act->lex_env);
  52644. act = thr->callstack + thr->callstack_top - 1; /* relookup (side effects) */
  52645. act->lex_env = new_env;
  52646. DUK_HOBJECT_INCREF(thr, new_env);
  52647. duk_pop(ctx);
  52648. } else {
  52649. ;
  52650. }
  52651. cat = thr->catchstack + thr->catchstack_top - 1; /* relookup (side effects) */
  52652. cat->callstack_index = thr->callstack_top - 1;
  52653. cat->pc_base = act->pc; /* pre-incremented, points to first jump slot */
  52654. cat->idx_base = (duk_size_t) (thr->valstack_bottom - thr->valstack) + b;
  52655. DUK_DDD(DUK_DDDPRINT("TRYCATCH catcher: flags=0x%08lx, callstack_index=%ld, pc_base=%ld, "
  52656. "idx_base=%ld, h_varname=%!O",
  52657. (unsigned long) cat->flags, (long) cat->callstack_index,
  52658. (long) cat->pc_base, (long) cat->idx_base, (duk_heaphdr *) cat->h_varname));
  52659. act->pc += 2; /* skip jump slots */
  52660. break;
  52661. }
  52662. /* Pre/post inc/dec for register variables, important for loops. */
  52663. case DUK_OP_PREINCR:
  52664. case DUK_OP_PREDECR:
  52665. case DUK_OP_POSTINCR:
  52666. case DUK_OP_POSTDECR: {
  52667. duk_context *ctx = (duk_context *) thr;
  52668. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52669. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52670. duk_tval *tv1, *tv2;
  52671. duk_tval tv_tmp;
  52672. duk_double_t x, y, z;
  52673. /* Two lowest bits of opcode are used to distinguish
  52674. * variants. Bit 0 = inc(0)/dec(1), bit 1 = pre(0)/post(1).
  52675. */
  52676. DUK_ASSERT((DUK_OP_PREINCR & 0x03) == 0x00);
  52677. DUK_ASSERT((DUK_OP_PREDECR & 0x03) == 0x01);
  52678. DUK_ASSERT((DUK_OP_POSTINCR & 0x03) == 0x02);
  52679. DUK_ASSERT((DUK_OP_POSTDECR & 0x03) == 0x03);
  52680. tv1 = DUK__REGP(bc);
  52681. #if defined(DUK_USE_FASTINT)
  52682. if (DUK_TVAL_IS_FASTINT(tv1)) {
  52683. duk_int64_t x_fi, y_fi, z_fi;
  52684. x_fi = DUK_TVAL_GET_FASTINT(tv1);
  52685. if (ins & DUK_ENC_OP(0x01)) {
  52686. if (x_fi == DUK_FASTINT_MIN) {
  52687. goto skip_fastint;
  52688. }
  52689. y_fi = x_fi - 1;
  52690. } else {
  52691. if (x_fi == DUK_FASTINT_MAX) {
  52692. goto skip_fastint;
  52693. }
  52694. y_fi = x_fi + 1;
  52695. }
  52696. DUK_TVAL_SET_FASTINT(tv1, y_fi); /* no need for refcount update */
  52697. tv2 = DUK__REGP(a);
  52698. DUK_TVAL_SET_TVAL(&tv_tmp, tv2);
  52699. z_fi = (ins & DUK_ENC_OP(0x02)) ? x_fi : y_fi;
  52700. DUK_TVAL_SET_FASTINT(tv2, z_fi); /* no need for incref */
  52701. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  52702. break;
  52703. }
  52704. skip_fastint:
  52705. #endif
  52706. if (DUK_TVAL_IS_NUMBER(tv1)) {
  52707. /* Fast path for the case where the register
  52708. * is a number (e.g. loop counter).
  52709. */
  52710. x = DUK_TVAL_GET_NUMBER(tv1);
  52711. if (ins & DUK_ENC_OP(0x01)) {
  52712. y = x - 1.0;
  52713. } else {
  52714. y = x + 1.0;
  52715. }
  52716. DUK_TVAL_SET_NUMBER(tv1, y); /* no need for refcount update */
  52717. } else {
  52718. x = duk_to_number(ctx, bc);
  52719. if (ins & DUK_ENC_OP(0x01)) {
  52720. y = x - 1.0;
  52721. } else {
  52722. y = x + 1.0;
  52723. }
  52724. duk_push_number(ctx, y);
  52725. duk_replace(ctx, bc);
  52726. }
  52727. tv2 = DUK__REGP(a);
  52728. DUK_TVAL_SET_TVAL(&tv_tmp, tv2);
  52729. z = (ins & DUK_ENC_OP(0x02)) ? x : y;
  52730. DUK_TVAL_SET_NUMBER(tv2, z); /* no need for incref */
  52731. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  52732. break;
  52733. }
  52734. /* Preinc/predec for var-by-name, slow path. */
  52735. case DUK_OP_PREINCV:
  52736. case DUK_OP_PREDECV:
  52737. case DUK_OP_POSTINCV:
  52738. case DUK_OP_POSTDECV: {
  52739. duk_context *ctx = (duk_context *) thr;
  52740. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52741. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52742. duk_double_t x, y;
  52743. duk_tval *tv1;
  52744. duk_hstring *name;
  52745. /* Two lowest bits of opcode are used to distinguish
  52746. * variants. Bit 0 = inc(0)/dec(1), bit 1 = pre(0)/post(1).
  52747. */
  52748. DUK_ASSERT((DUK_OP_PREINCV & 0x03) == 0x00);
  52749. DUK_ASSERT((DUK_OP_PREDECV & 0x03) == 0x01);
  52750. DUK_ASSERT((DUK_OP_POSTINCV & 0x03) == 0x02);
  52751. DUK_ASSERT((DUK_OP_POSTDECV & 0x03) == 0x03);
  52752. tv1 = DUK__CONSTP(bc);
  52753. DUK_ASSERT(DUK_TVAL_IS_STRING(tv1));
  52754. name = DUK_TVAL_GET_STRING(tv1);
  52755. DUK_ASSERT(name != NULL);
  52756. (void) duk_js_getvar_activation(thr, act, name, 1 /*throw*/); /* -> [... val this] */
  52757. /* XXX: fastint fast path would be very useful here */
  52758. x = duk_to_number(ctx, -2);
  52759. duk_pop_2(ctx);
  52760. if (ins & DUK_ENC_OP(0x01)) {
  52761. y = x - 1.0;
  52762. } else {
  52763. y = x + 1.0;
  52764. }
  52765. duk_push_number(ctx, y);
  52766. tv1 = duk_get_tval(ctx, -1);
  52767. DUK_ASSERT(tv1 != NULL);
  52768. duk_js_putvar_activation(thr, act, name, tv1, DUK__STRICT());
  52769. duk_pop(ctx);
  52770. duk_push_number(ctx, (ins & DUK_ENC_OP(0x02)) ? x : y);
  52771. duk_replace(ctx, (duk_idx_t) a);
  52772. break;
  52773. }
  52774. /* Preinc/predec for object properties. */
  52775. case DUK_OP_PREINCP:
  52776. case DUK_OP_PREDECP:
  52777. case DUK_OP_POSTINCP:
  52778. case DUK_OP_POSTDECP: {
  52779. duk_context *ctx = (duk_context *) thr;
  52780. duk_small_uint_fast_t a = DUK_DEC_A(ins);
  52781. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52782. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52783. duk_tval *tv_obj;
  52784. duk_tval *tv_key;
  52785. duk_tval *tv_val;
  52786. duk_bool_t rc;
  52787. duk_double_t x, y;
  52788. /* A -> target reg
  52789. * B -> object reg/const (may be const e.g. in "'foo'[1]")
  52790. * C -> key reg/const
  52791. */
  52792. /* Two lowest bits of opcode are used to distinguish
  52793. * variants. Bit 0 = inc(0)/dec(1), bit 1 = pre(0)/post(1).
  52794. */
  52795. DUK_ASSERT((DUK_OP_PREINCP & 0x03) == 0x00);
  52796. DUK_ASSERT((DUK_OP_PREDECP & 0x03) == 0x01);
  52797. DUK_ASSERT((DUK_OP_POSTINCP & 0x03) == 0x02);
  52798. DUK_ASSERT((DUK_OP_POSTDECP & 0x03) == 0x03);
  52799. tv_obj = DUK__REGCONSTP(b);
  52800. tv_key = DUK__REGCONSTP(c);
  52801. rc = duk_hobject_getprop(thr, tv_obj, tv_key); /* -> [val] */
  52802. DUK_UNREF(rc); /* ignore */
  52803. tv_obj = NULL; /* invalidated */
  52804. tv_key = NULL; /* invalidated */
  52805. x = duk_to_number(ctx, -1);
  52806. duk_pop(ctx);
  52807. if (ins & DUK_ENC_OP(0x01)) {
  52808. y = x - 1.0;
  52809. } else {
  52810. y = x + 1.0;
  52811. }
  52812. duk_push_number(ctx, y);
  52813. tv_val = duk_get_tval(ctx, -1);
  52814. DUK_ASSERT(tv_val != NULL);
  52815. tv_obj = DUK__REGCONSTP(b);
  52816. tv_key = DUK__REGCONSTP(c);
  52817. rc = duk_hobject_putprop(thr, tv_obj, tv_key, tv_val, DUK__STRICT());
  52818. DUK_UNREF(rc); /* ignore */
  52819. tv_obj = NULL; /* invalidated */
  52820. tv_key = NULL; /* invalidated */
  52821. duk_pop(ctx);
  52822. duk_push_number(ctx, (ins & DUK_ENC_OP(0x02)) ? x : y);
  52823. duk_replace(ctx, (duk_idx_t) a);
  52824. break;
  52825. }
  52826. case DUK_OP_EXTRA: {
  52827. /* XXX: shared decoding of 'b' and 'c'? */
  52828. duk_small_uint_fast_t extraop = DUK_DEC_A(ins);
  52829. switch ((int) extraop) {
  52830. /* XXX: switch cast? */
  52831. case DUK_EXTRAOP_NOP: {
  52832. /* nop */
  52833. break;
  52834. }
  52835. case DUK_EXTRAOP_INVALID: {
  52836. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, "INVALID opcode (%ld)", (long) DUK_DEC_BC(ins));
  52837. break;
  52838. }
  52839. case DUK_EXTRAOP_LDTHIS: {
  52840. /* Note: 'this' may be bound to any value, not just an object */
  52841. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52842. duk_tval tv_tmp;
  52843. duk_tval *tv1, *tv2;
  52844. tv1 = DUK__REGP(bc);
  52845. tv2 = thr->valstack_bottom - 1; /* 'this binding' is just under bottom */
  52846. DUK_ASSERT(tv2 >= thr->valstack);
  52847. DUK_DDD(DUK_DDDPRINT("LDTHIS: %!T to r%ld", (duk_tval *) tv2, (long) bc));
  52848. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  52849. DUK_TVAL_SET_TVAL(tv1, tv2);
  52850. DUK_TVAL_INCREF(thr, tv1);
  52851. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  52852. break;
  52853. }
  52854. case DUK_EXTRAOP_LDUNDEF: {
  52855. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52856. duk_tval tv_tmp;
  52857. duk_tval *tv1;
  52858. tv1 = DUK__REGP(bc);
  52859. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  52860. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv1);
  52861. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  52862. break;
  52863. }
  52864. case DUK_EXTRAOP_LDNULL: {
  52865. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52866. duk_tval tv_tmp;
  52867. duk_tval *tv1;
  52868. tv1 = DUK__REGP(bc);
  52869. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  52870. DUK_TVAL_SET_NULL(tv1);
  52871. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  52872. break;
  52873. }
  52874. case DUK_EXTRAOP_LDTRUE:
  52875. case DUK_EXTRAOP_LDFALSE: {
  52876. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52877. duk_tval tv_tmp;
  52878. duk_tval *tv1;
  52879. duk_small_uint_fast_t bval = (extraop == DUK_EXTRAOP_LDTRUE ? 1 : 0);
  52880. tv1 = DUK__REGP(bc);
  52881. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  52882. DUK_TVAL_SET_BOOLEAN(tv1, bval);
  52883. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  52884. break;
  52885. }
  52886. case DUK_EXTRAOP_NEWOBJ: {
  52887. duk_context *ctx = (duk_context *) thr;
  52888. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52889. duk_push_object(ctx);
  52890. duk_replace(ctx, (duk_idx_t) b);
  52891. break;
  52892. }
  52893. case DUK_EXTRAOP_NEWARR: {
  52894. duk_context *ctx = (duk_context *) thr;
  52895. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52896. duk_push_array(ctx);
  52897. duk_replace(ctx, (duk_idx_t) b);
  52898. break;
  52899. }
  52900. case DUK_EXTRAOP_SETALEN: {
  52901. duk_small_uint_fast_t b;
  52902. duk_small_uint_fast_t c;
  52903. duk_tval *tv1;
  52904. duk_hobject *h;
  52905. duk_uint32_t len;
  52906. b = DUK_DEC_B(ins); tv1 = DUK__REGP(b);
  52907. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv1));
  52908. h = DUK_TVAL_GET_OBJECT(tv1);
  52909. c = DUK_DEC_C(ins); tv1 = DUK__REGP(c);
  52910. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv1));
  52911. len = (duk_uint32_t) DUK_TVAL_GET_NUMBER(tv1);
  52912. duk_hobject_set_length(thr, h, len);
  52913. break;
  52914. }
  52915. case DUK_EXTRAOP_TYPEOF: {
  52916. duk_context *ctx = (duk_context *) thr;
  52917. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  52918. duk_push_hstring(ctx, duk_js_typeof(thr, DUK__REGP(bc)));
  52919. duk_replace(ctx, (duk_idx_t) bc);
  52920. break;
  52921. }
  52922. case DUK_EXTRAOP_TYPEOFID: {
  52923. duk_context *ctx = (duk_context *) thr;
  52924. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52925. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52926. duk_hstring *name;
  52927. duk_tval *tv;
  52928. /* B -> target register
  52929. * C -> constant index of identifier name
  52930. */
  52931. tv = DUK__REGCONSTP(c); /* XXX: this could be a DUK__CONSTP instead */
  52932. DUK_ASSERT(DUK_TVAL_IS_STRING(tv));
  52933. name = DUK_TVAL_GET_STRING(tv);
  52934. if (duk_js_getvar_activation(thr, act, name, 0 /*throw*/)) {
  52935. /* -> [... val this] */
  52936. tv = duk_get_tval(ctx, -2);
  52937. duk_push_hstring(ctx, duk_js_typeof(thr, tv));
  52938. duk_replace(ctx, (duk_idx_t) b);
  52939. duk_pop_2(ctx);
  52940. } else {
  52941. /* unresolvable, no stack changes */
  52942. duk_push_hstring_stridx(ctx, DUK_STRIDX_LC_UNDEFINED);
  52943. duk_replace(ctx, (duk_idx_t) b);
  52944. }
  52945. break;
  52946. }
  52947. case DUK_EXTRAOP_INITENUM: {
  52948. duk_context *ctx = (duk_context *) thr;
  52949. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52950. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52951. /*
  52952. * Enumeration semantics come from for-in statement, E5 Section 12.6.4.
  52953. * If called with 'null' or 'undefined', this opcode returns 'null' as
  52954. * the enumerator, which is special cased in NEXTENUM. This simplifies
  52955. * the compiler part
  52956. */
  52957. /* B -> register for writing enumerator object
  52958. * C -> value to be enumerated (register)
  52959. */
  52960. if (duk_is_null_or_undefined(ctx, (duk_idx_t) c)) {
  52961. duk_push_null(ctx);
  52962. duk_replace(ctx, (duk_idx_t) b);
  52963. } else {
  52964. duk_dup(ctx, (duk_idx_t) c);
  52965. duk_to_object(ctx, -1);
  52966. duk_hobject_enumerator_create(ctx, 0 /*enum_flags*/); /* [ ... val ] --> [ ... enum ] */
  52967. duk_replace(ctx, (duk_idx_t) b);
  52968. }
  52969. break;
  52970. }
  52971. case DUK_EXTRAOP_NEXTENUM: {
  52972. duk_context *ctx = (duk_context *) thr;
  52973. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  52974. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  52975. /*
  52976. * NEXTENUM checks whether the enumerator still has unenumerated
  52977. * keys. If so, the next key is loaded to the target register
  52978. * and the next instruction is skipped. Otherwise the next instruction
  52979. * will be executed, jumping out of the enumeration loop.
  52980. */
  52981. /* B -> target register for next key
  52982. * C -> enum register
  52983. */
  52984. DUK_DDD(DUK_DDDPRINT("NEXTENUM: b->%!T, c->%!T",
  52985. (duk_tval *) duk_get_tval(ctx, (duk_idx_t) b),
  52986. (duk_tval *) duk_get_tval(ctx, (duk_idx_t) c)));
  52987. if (duk_is_object(ctx, (duk_idx_t) c)) {
  52988. /* XXX: assert 'c' is an enumerator */
  52989. duk_dup(ctx, (duk_idx_t) c);
  52990. if (duk_hobject_enumerator_next(ctx, 0 /*get_value*/)) {
  52991. /* [ ... enum ] -> [ ... next_key ] */
  52992. DUK_DDD(DUK_DDDPRINT("enum active, next key is %!T, skip jump slot ",
  52993. (duk_tval *) duk_get_tval(ctx, -1)));
  52994. act->pc++;;
  52995. } else {
  52996. /* [ ... enum ] -> [ ... ] */
  52997. DUK_DDD(DUK_DDDPRINT("enum finished, execute jump slot"));
  52998. duk_push_undefined(ctx);
  52999. }
  53000. duk_replace(ctx, (duk_idx_t) b);
  53001. } else {
  53002. /* 'null' enumerator case -> behave as with an empty enumerator */
  53003. DUK_ASSERT(duk_is_null(ctx, (duk_idx_t) c));
  53004. DUK_DDD(DUK_DDDPRINT("enum is null, execute jump slot"));
  53005. }
  53006. break;
  53007. }
  53008. case DUK_EXTRAOP_INITSET:
  53009. case DUK_EXTRAOP_INITSETI:
  53010. case DUK_EXTRAOP_INITGET:
  53011. case DUK_EXTRAOP_INITGETI: {
  53012. duk_context *ctx = (duk_context *) thr;
  53013. duk_bool_t is_set = (extraop == DUK_EXTRAOP_INITSET || extraop == DUK_EXTRAOP_INITSETI);
  53014. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  53015. duk_uint_fast_t idx;
  53016. /* B -> object register
  53017. * C -> C+0 contains key, C+1 closure (value)
  53018. */
  53019. /*
  53020. * INITSET/INITGET are only used to initialize object literal keys.
  53021. * The compiler ensures that there cannot be a previous data property
  53022. * of the same name. It also ensures that setter and getter can only
  53023. * be initialized once (or not at all).
  53024. */
  53025. idx = (duk_uint_fast_t) DUK_DEC_C(ins);
  53026. if (extraop == DUK_EXTRAOP_INITSETI || extraop == DUK_EXTRAOP_INITGETI) {
  53027. duk_tval *tv_ind = DUK__REGP(idx);
  53028. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_ind));
  53029. idx = (duk_uint_fast_t) DUK_TVAL_GET_NUMBER(tv_ind);
  53030. }
  53031. #if defined(DUK_USE_EXEC_INDIRECT_BOUND_CHECK)
  53032. if (idx + 2 > (duk_uint_fast_t) duk_get_top(ctx)) {
  53033. /* XXX: use duk_is_valid_index() instead? */
  53034. /* XXX: improve check; check against nregs, not against top */
  53035. DUK__INTERNAL_ERROR("INITSET/INITGET out of bounds");
  53036. }
  53037. #endif
  53038. /* XXX: this is now a very unoptimal implementation -- this can be
  53039. * made very simple by direct manipulation of the object internals,
  53040. * given the guarantees above.
  53041. */
  53042. duk_push_hobject_bidx(ctx, DUK_BIDX_OBJECT_CONSTRUCTOR);
  53043. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_DEFINE_PROPERTY);
  53044. duk_push_undefined(ctx);
  53045. duk_dup(ctx, (duk_idx_t) b);
  53046. duk_dup(ctx, (duk_idx_t) (idx + 0));
  53047. duk_push_object(ctx); /* -> [ Object defineProperty undefined obj key desc ] */
  53048. duk_push_true(ctx);
  53049. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_ENUMERABLE);
  53050. duk_push_true(ctx);
  53051. duk_put_prop_stridx(ctx, -2, DUK_STRIDX_CONFIGURABLE);
  53052. duk_dup(ctx, (duk_idx_t) (idx + 1));
  53053. duk_put_prop_stridx(ctx, -2, (is_set ? DUK_STRIDX_SET : DUK_STRIDX_GET));
  53054. DUK_DDD(DUK_DDDPRINT("INITGET/INITSET: obj=%!T, key=%!T, desc=%!T",
  53055. (duk_tval *) duk_get_tval(ctx, -3),
  53056. (duk_tval *) duk_get_tval(ctx, -2),
  53057. (duk_tval *) duk_get_tval(ctx, -1)));
  53058. duk_call_method(ctx, 3); /* -> [ Object res ] */
  53059. duk_pop_2(ctx);
  53060. DUK_DDD(DUK_DDDPRINT("INITGET/INITSET AFTER: obj=%!T",
  53061. (duk_tval *) duk_get_tval(ctx, (duk_idx_t) b)));
  53062. break;
  53063. }
  53064. case DUK_EXTRAOP_ENDTRY: {
  53065. duk_catcher *cat;
  53066. duk_tval tv_tmp;
  53067. duk_tval *tv1;
  53068. DUK_ASSERT(thr->catchstack_top >= 1);
  53069. DUK_ASSERT(thr->callstack_top >= 1);
  53070. DUK_ASSERT(thr->catchstack[thr->catchstack_top - 1].callstack_index == thr->callstack_top - 1);
  53071. cat = thr->catchstack + thr->catchstack_top - 1;
  53072. DUK_DDD(DUK_DDDPRINT("ENDTRY: clearing catch active flag (regardless of whether it was set or not)"));
  53073. DUK_CAT_CLEAR_CATCH_ENABLED(cat);
  53074. if (DUK_CAT_HAS_FINALLY_ENABLED(cat)) {
  53075. DUK_DDD(DUK_DDDPRINT("ENDTRY: finally part is active, jump through 2nd jump slot with 'normal continuation'"));
  53076. tv1 = thr->valstack + cat->idx_base;
  53077. DUK_ASSERT(tv1 >= thr->valstack && tv1 < thr->valstack_top);
  53078. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  53079. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv1);
  53080. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  53081. tv1 = NULL;
  53082. tv1 = thr->valstack + cat->idx_base + 1;
  53083. DUK_ASSERT(tv1 >= thr->valstack && tv1 < thr->valstack_top);
  53084. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  53085. DUK_TVAL_SET_NUMBER(tv1, (duk_double_t) DUK_LJ_TYPE_NORMAL); /* XXX: set int */
  53086. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  53087. tv1 = NULL;
  53088. DUK_CAT_CLEAR_FINALLY_ENABLED(cat);
  53089. } else {
  53090. DUK_DDD(DUK_DDDPRINT("ENDTRY: no finally part, dismantle catcher, jump through 2nd jump slot (to end of statement)"));
  53091. duk_hthread_catchstack_unwind(thr, thr->catchstack_top - 1);
  53092. /* no need to unwind callstack */
  53093. }
  53094. act->pc = cat->pc_base + 1;
  53095. break;
  53096. }
  53097. case DUK_EXTRAOP_ENDCATCH: {
  53098. duk_catcher *cat;
  53099. duk_tval tv_tmp;
  53100. duk_tval *tv1;
  53101. DUK_ASSERT(thr->catchstack_top >= 1);
  53102. DUK_ASSERT(thr->callstack_top >= 1);
  53103. DUK_ASSERT(thr->catchstack[thr->catchstack_top - 1].callstack_index == thr->callstack_top - 1);
  53104. cat = thr->catchstack + thr->catchstack_top - 1;
  53105. DUK_ASSERT(!DUK_CAT_HAS_CATCH_ENABLED(cat)); /* cleared before entering catch part */
  53106. if (DUK_CAT_HAS_LEXENV_ACTIVE(cat)) {
  53107. duk_hobject *prev_env;
  53108. /* 'with' binding has no catch clause, so can't be here unless a normal try-catch */
  53109. DUK_ASSERT(DUK_CAT_HAS_CATCH_BINDING_ENABLED(cat));
  53110. DUK_ASSERT(act->lex_env != NULL);
  53111. DUK_DDD(DUK_DDDPRINT("ENDCATCH: popping catcher part lexical environment"));
  53112. prev_env = act->lex_env;
  53113. DUK_ASSERT(prev_env != NULL);
  53114. act->lex_env = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, prev_env);
  53115. DUK_CAT_CLEAR_LEXENV_ACTIVE(cat);
  53116. DUK_HOBJECT_DECREF(thr, prev_env); /* side effects */
  53117. }
  53118. if (DUK_CAT_HAS_FINALLY_ENABLED(cat)) {
  53119. DUK_DDD(DUK_DDDPRINT("ENDCATCH: finally part is active, jump through 2nd jump slot with 'normal continuation'"));
  53120. tv1 = thr->valstack + cat->idx_base;
  53121. DUK_ASSERT(tv1 >= thr->valstack && tv1 < thr->valstack_top);
  53122. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  53123. DUK_TVAL_SET_UNDEFINED_ACTUAL(tv1);
  53124. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  53125. tv1 = NULL;
  53126. tv1 = thr->valstack + cat->idx_base + 1;
  53127. DUK_ASSERT(tv1 >= thr->valstack && tv1 < thr->valstack_top);
  53128. DUK_TVAL_SET_TVAL(&tv_tmp, tv1);
  53129. DUK_TVAL_SET_NUMBER(tv1, (duk_double_t) DUK_LJ_TYPE_NORMAL); /* XXX: set int */
  53130. DUK_TVAL_DECREF(thr, &tv_tmp); /* side effects */
  53131. tv1 = NULL;
  53132. DUK_CAT_CLEAR_FINALLY_ENABLED(cat);
  53133. } else {
  53134. DUK_DDD(DUK_DDDPRINT("ENDCATCH: no finally part, dismantle catcher, jump through 2nd jump slot (to end of statement)"));
  53135. duk_hthread_catchstack_unwind(thr, thr->catchstack_top - 1);
  53136. /* no need to unwind callstack */
  53137. }
  53138. act->pc = cat->pc_base + 1;
  53139. break;
  53140. }
  53141. case DUK_EXTRAOP_ENDFIN: {
  53142. duk_context *ctx = (duk_context *) thr;
  53143. duk_catcher *cat;
  53144. duk_tval *tv1;
  53145. duk_small_uint_fast_t cont_type;
  53146. DUK_ASSERT(thr->catchstack_top >= 1);
  53147. DUK_ASSERT(thr->callstack_top >= 1);
  53148. DUK_ASSERT(thr->catchstack[thr->catchstack_top - 1].callstack_index == thr->callstack_top - 1);
  53149. cat = thr->catchstack + thr->catchstack_top - 1;
  53150. /* CATCH flag may be enabled or disabled here; it may be enabled if
  53151. * the statement has a catch block but the try block does not throw
  53152. * an error.
  53153. */
  53154. DUK_ASSERT(!DUK_CAT_HAS_FINALLY_ENABLED(cat)); /* cleared before entering finally */
  53155. /* XXX: assert idx_base */
  53156. DUK_DDD(DUK_DDDPRINT("ENDFIN: completion value=%!T, type=%!T",
  53157. (duk_tval *) (thr->valstack + cat->idx_base + 0),
  53158. (duk_tval *) (thr->valstack + cat->idx_base + 1)));
  53159. tv1 = thr->valstack + cat->idx_base + 1; /* type */
  53160. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv1));
  53161. cont_type = (duk_small_uint_fast_t) DUK_TVAL_GET_NUMBER(tv1);
  53162. if (cont_type == DUK_LJ_TYPE_NORMAL) {
  53163. DUK_DDD(DUK_DDDPRINT("ENDFIN: finally part finishing with 'normal' (non-abrupt) completion -> "
  53164. "dismantle catcher, resume execution after ENDFIN"));
  53165. duk_hthread_catchstack_unwind(thr, thr->catchstack_top - 1);
  53166. /* no need to unwind callstack */
  53167. } else {
  53168. DUK_DDD(DUK_DDDPRINT("ENDFIN: finally part finishing with abrupt completion, lj_type=%ld -> "
  53169. "dismantle catcher, re-throw error",
  53170. (long) cont_type));
  53171. duk_push_tval(ctx, thr->valstack + cat->idx_base);
  53172. /* XXX: assert lj type valid */
  53173. duk_err_setup_heap_ljstate(thr, (duk_small_int_t) cont_type);
  53174. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL); /* always in executor */
  53175. duk_err_longjmp(thr);
  53176. DUK_UNREACHABLE();
  53177. }
  53178. /* continue execution after ENDFIN */
  53179. break;
  53180. }
  53181. case DUK_EXTRAOP_THROW: {
  53182. duk_context *ctx = (duk_context *) thr;
  53183. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53184. /* Note: errors are augmented when they are created, not
  53185. * when they are thrown. So, don't augment here, it would
  53186. * break re-throwing for instance.
  53187. */
  53188. duk_dup(ctx, (duk_idx_t) bc);
  53189. DUK_DDD(DUK_DDDPRINT("THROW ERROR (BYTECODE): %!dT (before throw augment)",
  53190. (duk_tval *) duk_get_tval(ctx, -1)));
  53191. #if defined(DUK_USE_AUGMENT_ERROR_THROW)
  53192. duk_err_augment_error_throw(thr);
  53193. DUK_DDD(DUK_DDDPRINT("THROW ERROR (BYTECODE): %!dT (after throw augment)",
  53194. (duk_tval *) duk_get_tval(ctx, -1)));
  53195. #endif
  53196. duk_err_setup_heap_ljstate(thr, DUK_LJ_TYPE_THROW);
  53197. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL); /* always in executor */
  53198. duk_err_longjmp(thr);
  53199. DUK_UNREACHABLE();
  53200. break;
  53201. }
  53202. case DUK_EXTRAOP_INVLHS: {
  53203. DUK_ERROR(thr, DUK_ERR_REFERENCE_ERROR, "invalid lvalue");
  53204. DUK_UNREACHABLE();
  53205. break;
  53206. }
  53207. case DUK_EXTRAOP_UNM:
  53208. case DUK_EXTRAOP_UNP: {
  53209. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53210. duk__vm_arith_unary_op(thr, DUK__REGP(bc), bc, extraop);
  53211. break;
  53212. }
  53213. case DUK_EXTRAOP_DEBUGGER: {
  53214. /* Opcode only emitted by compiler when debugger
  53215. * support is enabled. Ignore it silently without
  53216. * debugger support, in case it has been loaded
  53217. * from precompiled bytecode.
  53218. */
  53219. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  53220. DUK_D(DUK_DPRINT("DEBUGGER statement encountered, halt execution"));
  53221. if (DUK_HEAP_IS_DEBUGGER_ATTACHED(thr->heap)) {
  53222. DUK_HEAP_SET_PAUSED(thr->heap);
  53223. goto restart_execution;
  53224. }
  53225. #else
  53226. DUK_D(DUK_DPRINT("DEBUGGER statement ignored, no debugger support"));
  53227. #endif
  53228. break;
  53229. }
  53230. case DUK_EXTRAOP_BREAK: {
  53231. duk_context *ctx = (duk_context *) thr;
  53232. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53233. /* always the "slow break" variant (longjmp'ing); a "fast break" is
  53234. * simply an DUK_OP_JUMP.
  53235. */
  53236. DUK_DDD(DUK_DDDPRINT("BREAK: %ld", (long) bc));
  53237. duk_push_uint(ctx, (duk_uint_t) bc);
  53238. duk_err_setup_heap_ljstate(thr, DUK_LJ_TYPE_BREAK);
  53239. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL); /* always in executor */
  53240. duk_err_longjmp(thr);
  53241. DUK_UNREACHABLE();
  53242. break;
  53243. }
  53244. case DUK_EXTRAOP_CONTINUE: {
  53245. duk_context *ctx = (duk_context *) thr;
  53246. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53247. /* always the "slow continue" variant (longjmp'ing); a "fast continue" is
  53248. * simply an DUK_OP_JUMP.
  53249. */
  53250. DUK_DDD(DUK_DDDPRINT("CONTINUE: %ld", (long) bc));
  53251. duk_push_uint(ctx, (duk_uint_t) bc);
  53252. duk_err_setup_heap_ljstate(thr, DUK_LJ_TYPE_CONTINUE);
  53253. DUK_ASSERT(thr->heap->lj.jmpbuf_ptr != NULL); /* always in executor */
  53254. duk_err_longjmp(thr);
  53255. DUK_UNREACHABLE();
  53256. break;
  53257. }
  53258. case DUK_EXTRAOP_BNOT: {
  53259. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53260. duk__vm_bitwise_not(thr, DUK__REGP(bc), bc);
  53261. break;
  53262. }
  53263. case DUK_EXTRAOP_LNOT: {
  53264. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53265. duk_tval *tv1;
  53266. tv1 = DUK__REGP(bc);
  53267. duk__vm_logical_not(thr, tv1, tv1);
  53268. break;
  53269. }
  53270. case DUK_EXTRAOP_INSTOF: {
  53271. duk_context *ctx = (duk_context *) thr;
  53272. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  53273. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  53274. duk_bool_t tmp;
  53275. tmp = duk_js_instanceof(thr, DUK__REGP(b), DUK__REGCONSTP(c));
  53276. duk_push_boolean(ctx, tmp);
  53277. duk_replace(ctx, (duk_idx_t) b);
  53278. break;
  53279. }
  53280. case DUK_EXTRAOP_IN: {
  53281. duk_context *ctx = (duk_context *) thr;
  53282. duk_small_uint_fast_t b = DUK_DEC_B(ins);
  53283. duk_small_uint_fast_t c = DUK_DEC_C(ins);
  53284. duk_bool_t tmp;
  53285. tmp = duk_js_in(thr, DUK__REGP(b), DUK__REGCONSTP(c));
  53286. duk_push_boolean(ctx, tmp);
  53287. duk_replace(ctx, (duk_idx_t) b);
  53288. break;
  53289. }
  53290. case DUK_EXTRAOP_LABEL: {
  53291. duk_catcher *cat;
  53292. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53293. /* allocate catcher and populate it (should be atomic) */
  53294. duk_hthread_catchstack_grow(thr);
  53295. cat = thr->catchstack + thr->catchstack_top;
  53296. thr->catchstack_top++;
  53297. cat->flags = DUK_CAT_TYPE_LABEL | (bc << DUK_CAT_LABEL_SHIFT);
  53298. cat->callstack_index = thr->callstack_top - 1;
  53299. cat->pc_base = act->pc; /* pre-incremented, points to first jump slot */
  53300. cat->idx_base = 0; /* unused for label */
  53301. cat->h_varname = NULL;
  53302. DUK_DDD(DUK_DDDPRINT("LABEL catcher: flags=0x%08lx, callstack_index=%ld, pc_base=%ld, "
  53303. "idx_base=%ld, h_varname=%!O, label_id=%ld",
  53304. (long) cat->flags, (long) cat->callstack_index, (long) cat->pc_base,
  53305. (long) cat->idx_base, (duk_heaphdr *) cat->h_varname, (long) DUK_CAT_GET_LABEL(cat)));
  53306. act->pc += 2; /* skip jump slots */
  53307. break;
  53308. }
  53309. case DUK_EXTRAOP_ENDLABEL: {
  53310. duk_catcher *cat;
  53311. #if defined(DUK_USE_DDDPRINT) || defined(DUK_USE_ASSERTIONS)
  53312. duk_uint_fast_t bc = DUK_DEC_BC(ins);
  53313. #endif
  53314. #if defined(DUK_USE_DDDPRINT)
  53315. DUK_DDD(DUK_DDDPRINT("ENDLABEL %ld", (long) bc));
  53316. #endif
  53317. DUK_ASSERT(thr->catchstack_top >= 1);
  53318. cat = thr->catchstack + thr->catchstack_top - 1;
  53319. DUK_UNREF(cat);
  53320. DUK_ASSERT(DUK_CAT_GET_TYPE(cat) == DUK_CAT_TYPE_LABEL);
  53321. DUK_ASSERT((duk_uint_fast_t) DUK_CAT_GET_LABEL(cat) == bc);
  53322. duk_hthread_catchstack_unwind(thr, thr->catchstack_top - 1);
  53323. /* no need to unwind callstack */
  53324. break;
  53325. }
  53326. #ifdef DUK_USE_DEBUG
  53327. case DUK_EXTRAOP_DUMPREG: {
  53328. DUK_D(DUK_DPRINT("DUMPREG: %ld -> %!T",
  53329. (long) DUK_DEC_BC(ins),
  53330. (duk_tval *) duk_get_tval((duk_context *) thr, (duk_idx_t) DUK_DEC_BC(ins))));
  53331. break;
  53332. }
  53333. case DUK_EXTRAOP_DUMPREGS: {
  53334. duk_idx_t i, i_top;
  53335. i_top = duk_get_top((duk_context *) thr);
  53336. DUK_D(DUK_DPRINT("DUMPREGS: %ld regs", (long) i_top));
  53337. for (i = 0; i < i_top; i++) {
  53338. DUK_D(DUK_DPRINT(" r%ld -> %!dT",
  53339. (long) i,
  53340. (duk_tval *) duk_get_tval((duk_context *) thr, i)));
  53341. }
  53342. break;
  53343. }
  53344. case DUK_EXTRAOP_LOGMARK: {
  53345. DUK_D(DUK_DPRINT("LOGMARK: mark %ld at pc %ld", (long) DUK_DEC_BC(ins), (long) (act->pc - 1))); /* -1, autoinc */
  53346. break;
  53347. }
  53348. #endif /* DUK_USE_DEBUG */
  53349. default: {
  53350. DUK__INTERNAL_ERROR("invalid extra opcode");
  53351. }
  53352. } /* end switch */
  53353. break;
  53354. }
  53355. default: {
  53356. /* this should never be possible, because the switch-case is
  53357. * comprehensive
  53358. */
  53359. DUK__INTERNAL_ERROR("invalid opcode");
  53360. break;
  53361. }
  53362. } /* end switch */
  53363. }
  53364. DUK_UNREACHABLE();
  53365. #ifndef DUK_USE_VERBOSE_EXECUTOR_ERRORS
  53366. internal_error:
  53367. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, "internal error in bytecode executor");
  53368. #endif
  53369. }
  53370. #undef DUK__INTERNAL_ERROR
  53371. #line 1 "duk_js_ops.c"
  53372. /*
  53373. * Ecmascript specification algorithm and conversion helpers.
  53374. *
  53375. * These helpers encapsulate the primitive Ecmascript operation
  53376. * semantics, and are used by the bytecode executor and the API
  53377. * (among other places). Note that some primitives are only
  53378. * implemented as part of the API and have no "internal" helper.
  53379. * (This is the case when an internal helper would not really be
  53380. * useful; e.g. the operation is rare, uses value stack heavily,
  53381. * etc.)
  53382. *
  53383. * The operation arguments depend on what is required to implement
  53384. * the operation:
  53385. *
  53386. * - If an operation is simple and stateless, and has no side
  53387. * effects, it won't take an duk_hthread argument and its
  53388. * arguments may be duk_tval pointers (which are safe as long
  53389. * as no side effects take place).
  53390. *
  53391. * - If complex coercions are required (e.g. a "ToNumber" coercion)
  53392. * or errors may be thrown, the operation takes an duk_hthread
  53393. * argument. This also implies that the operation may have
  53394. * arbitrary side effects, invalidating any duk_tval pointers.
  53395. *
  53396. * - For operations with potential side effects, arguments can be
  53397. * taken in several ways:
  53398. *
  53399. * a) as duk_tval pointers, which makes sense if the "common case"
  53400. * can be resolved without side effects (e.g. coercion); the
  53401. * arguments are pushed to the valstack for coercion if
  53402. * necessary
  53403. *
  53404. * b) as duk_tval values
  53405. *
  53406. * c) implicitly on value stack top
  53407. *
  53408. * d) as indices to the value stack
  53409. *
  53410. * Future work:
  53411. *
  53412. * - Argument styles may not be the most sensible in every case now.
  53413. *
  53414. * - In-place coercions might be useful for several operations, if
  53415. * in-place coercion is OK for the bytecode executor and the API.
  53416. */
  53417. /* include removed: duk_internal.h */
  53418. /*
  53419. * [[DefaultValue]] (E5 Section 8.12.8)
  53420. *
  53421. * ==> implemented in the API.
  53422. */
  53423. /*
  53424. * ToPrimitive() (E5 Section 9.1)
  53425. *
  53426. * ==> implemented in the API.
  53427. */
  53428. /*
  53429. * ToBoolean() (E5 Section 9.2)
  53430. */
  53431. DUK_INTERNAL duk_bool_t duk_js_toboolean(duk_tval *tv) {
  53432. switch (DUK_TVAL_GET_TAG(tv)) {
  53433. case DUK_TAG_UNDEFINED:
  53434. case DUK_TAG_NULL:
  53435. return 0;
  53436. case DUK_TAG_BOOLEAN:
  53437. return DUK_TVAL_GET_BOOLEAN(tv);
  53438. case DUK_TAG_STRING: {
  53439. duk_hstring *h = DUK_TVAL_GET_STRING(tv);
  53440. DUK_ASSERT(h != NULL);
  53441. return (DUK_HSTRING_GET_BYTELEN(h) > 0 ? 1 : 0);
  53442. }
  53443. case DUK_TAG_OBJECT: {
  53444. return 1;
  53445. }
  53446. case DUK_TAG_BUFFER: {
  53447. /* mimic semantics for strings */
  53448. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  53449. DUK_ASSERT(h != NULL);
  53450. return (DUK_HBUFFER_GET_SIZE(h) > 0 ? 1 : 0);
  53451. }
  53452. case DUK_TAG_POINTER: {
  53453. void *p = DUK_TVAL_GET_POINTER(tv);
  53454. return (p != NULL ? 1 : 0);
  53455. }
  53456. case DUK_TAG_LIGHTFUNC: {
  53457. return 1;
  53458. }
  53459. #if defined(DUK_USE_FASTINT)
  53460. case DUK_TAG_FASTINT:
  53461. if (DUK_TVAL_GET_FASTINT(tv) != 0) {
  53462. return 1;
  53463. } else {
  53464. return 0;
  53465. }
  53466. #endif
  53467. default: {
  53468. /* number */
  53469. duk_double_t d;
  53470. int c;
  53471. DUK_ASSERT(DUK_TVAL_IS_DOUBLE(tv));
  53472. d = DUK_TVAL_GET_DOUBLE(tv);
  53473. c = DUK_FPCLASSIFY((double) d);
  53474. if (c == DUK_FP_ZERO || c == DUK_FP_NAN) {
  53475. return 0;
  53476. } else {
  53477. return 1;
  53478. }
  53479. }
  53480. }
  53481. DUK_UNREACHABLE();
  53482. }
  53483. /*
  53484. * ToNumber() (E5 Section 9.3)
  53485. *
  53486. * Value to convert must be on stack top, and is popped before exit.
  53487. *
  53488. * See: http://www.cs.indiana.edu/~burger/FP-Printing-PLDI96.pdf
  53489. * http://www.cs.indiana.edu/~burger/fp/index.html
  53490. *
  53491. * Notes on the conversion:
  53492. *
  53493. * - There are specific requirements on the accuracy of the conversion
  53494. * through a "Mathematical Value" (MV), so this conversion is not
  53495. * trivial.
  53496. *
  53497. * - Quick rejects (e.g. based on first char) are difficult because
  53498. * the grammar allows leading and trailing white space.
  53499. *
  53500. * - Quick reject based on string length is difficult even after
  53501. * accounting for white space; there may be arbitrarily many
  53502. * decimal digits.
  53503. *
  53504. * - Standard grammar allows decimal values ("123"), hex values
  53505. * ("0x123") and infinities
  53506. *
  53507. * - Unlike source code literals, ToNumber() coerces empty strings
  53508. * and strings with only whitespace to zero (not NaN).
  53509. */
  53510. /* E5 Section 9.3.1 */
  53511. DUK_LOCAL duk_double_t duk__tonumber_string_raw(duk_hthread *thr) {
  53512. duk_context *ctx = (duk_context *) thr;
  53513. duk_small_uint_t s2n_flags;
  53514. duk_double_t d;
  53515. /* Quite lenient, e.g. allow empty as zero, but don't allow trailing
  53516. * garbage.
  53517. */
  53518. s2n_flags = DUK_S2N_FLAG_TRIM_WHITE |
  53519. DUK_S2N_FLAG_ALLOW_EXP |
  53520. DUK_S2N_FLAG_ALLOW_PLUS |
  53521. DUK_S2N_FLAG_ALLOW_MINUS |
  53522. DUK_S2N_FLAG_ALLOW_INF |
  53523. DUK_S2N_FLAG_ALLOW_FRAC |
  53524. DUK_S2N_FLAG_ALLOW_NAKED_FRAC |
  53525. DUK_S2N_FLAG_ALLOW_EMPTY_FRAC |
  53526. DUK_S2N_FLAG_ALLOW_EMPTY_AS_ZERO |
  53527. DUK_S2N_FLAG_ALLOW_LEADING_ZERO |
  53528. DUK_S2N_FLAG_ALLOW_AUTO_HEX_INT;
  53529. duk_numconv_parse(ctx, 10 /*radix*/, s2n_flags);
  53530. d = duk_get_number(ctx, -1);
  53531. duk_pop(ctx);
  53532. return d;
  53533. }
  53534. DUK_INTERNAL duk_double_t duk_js_tonumber(duk_hthread *thr, duk_tval *tv) {
  53535. duk_context *ctx = (duk_hthread *) thr;
  53536. DUK_ASSERT(thr != NULL);
  53537. DUK_ASSERT(tv != NULL);
  53538. switch (DUK_TVAL_GET_TAG(tv)) {
  53539. case DUK_TAG_UNDEFINED: {
  53540. /* return a specific NaN (although not strictly necessary) */
  53541. duk_double_union du;
  53542. DUK_DBLUNION_SET_NAN(&du);
  53543. DUK_ASSERT(DUK_DBLUNION_IS_NORMALIZED(&du));
  53544. return du.d;
  53545. }
  53546. case DUK_TAG_NULL: {
  53547. /* +0.0 */
  53548. return 0.0;
  53549. }
  53550. case DUK_TAG_BOOLEAN: {
  53551. if (DUK_TVAL_IS_BOOLEAN_TRUE(tv)) {
  53552. return 1.0;
  53553. }
  53554. return 0.0;
  53555. }
  53556. case DUK_TAG_STRING: {
  53557. duk_hstring *h = DUK_TVAL_GET_STRING(tv);
  53558. duk_push_hstring(ctx, h);
  53559. return duk__tonumber_string_raw(thr);
  53560. }
  53561. case DUK_TAG_OBJECT: {
  53562. /* Note: ToPrimitive(object,hint) == [[DefaultValue]](object,hint),
  53563. * so use [[DefaultValue]] directly.
  53564. */
  53565. duk_double_t d;
  53566. duk_push_tval(ctx, tv);
  53567. duk_to_defaultvalue(ctx, -1, DUK_HINT_NUMBER); /* 'tv' becomes invalid */
  53568. /* recursive call for a primitive value (guaranteed not to cause second
  53569. * recursion).
  53570. */
  53571. d = duk_js_tonumber(thr, duk_require_tval(ctx, -1));
  53572. duk_pop(ctx);
  53573. return d;
  53574. }
  53575. case DUK_TAG_BUFFER: {
  53576. /* Coerce like a string. This makes sense because addition also treats
  53577. * buffers like strings.
  53578. */
  53579. duk_hbuffer *h = DUK_TVAL_GET_BUFFER(tv);
  53580. duk_push_hbuffer(ctx, h);
  53581. duk_to_string(ctx, -1); /* XXX: expensive, but numconv now expects to see a string */
  53582. return duk__tonumber_string_raw(thr);
  53583. }
  53584. case DUK_TAG_POINTER: {
  53585. /* Coerce like boolean */
  53586. void *p = DUK_TVAL_GET_POINTER(tv);
  53587. return (p != NULL ? 1.0 : 0.0);
  53588. }
  53589. case DUK_TAG_LIGHTFUNC: {
  53590. /* +(function(){}) -> NaN */
  53591. return DUK_DOUBLE_NAN;
  53592. }
  53593. #if defined(DUK_USE_FASTINT)
  53594. case DUK_TAG_FASTINT:
  53595. return (duk_double_t) DUK_TVAL_GET_FASTINT(tv);
  53596. #endif
  53597. default: {
  53598. /* number */
  53599. DUK_ASSERT(DUK_TVAL_IS_DOUBLE(tv));
  53600. return DUK_TVAL_GET_DOUBLE(tv);
  53601. }
  53602. }
  53603. DUK_UNREACHABLE();
  53604. }
  53605. /*
  53606. * ToInteger() (E5 Section 9.4)
  53607. */
  53608. /* exposed, used by e.g. duk_bi_date.c */
  53609. DUK_INTERNAL duk_double_t duk_js_tointeger_number(duk_double_t x) {
  53610. duk_small_int_t c = (duk_small_int_t) DUK_FPCLASSIFY(x);
  53611. if (c == DUK_FP_NAN) {
  53612. return 0.0;
  53613. } else if (c == DUK_FP_ZERO || c == DUK_FP_INFINITE) {
  53614. /* XXX: FP_ZERO check can be removed, the else clause handles it
  53615. * correctly (preserving sign).
  53616. */
  53617. return x;
  53618. } else {
  53619. duk_small_int_t s = (duk_small_int_t) DUK_SIGNBIT(x);
  53620. x = DUK_FLOOR(DUK_FABS(x)); /* truncate towards zero */
  53621. if (s) {
  53622. x = -x;
  53623. }
  53624. return x;
  53625. }
  53626. }
  53627. DUK_INTERNAL duk_double_t duk_js_tointeger(duk_hthread *thr, duk_tval *tv) {
  53628. /* XXX: fastint */
  53629. duk_double_t d = duk_js_tonumber(thr, tv); /* invalidates tv */
  53630. return duk_js_tointeger_number(d);
  53631. }
  53632. /*
  53633. * ToInt32(), ToUint32(), ToUint16() (E5 Sections 9.5, 9.6, 9.7)
  53634. */
  53635. /* combined algorithm matching E5 Sections 9.5 and 9.6 */
  53636. DUK_LOCAL duk_double_t duk__toint32_touint32_helper(duk_double_t x, duk_bool_t is_toint32) {
  53637. duk_small_int_t c = (duk_small_int_t) DUK_FPCLASSIFY(x);
  53638. duk_small_int_t s;
  53639. if (c == DUK_FP_NAN || c == DUK_FP_ZERO || c == DUK_FP_INFINITE) {
  53640. return 0.0;
  53641. }
  53642. /* x = sign(x) * floor(abs(x)), i.e. truncate towards zero, keep sign */
  53643. s = (duk_small_int_t) DUK_SIGNBIT(x);
  53644. x = DUK_FLOOR(DUK_FABS(x));
  53645. if (s) {
  53646. x = -x;
  53647. }
  53648. /* NOTE: fmod(x) result sign is same as sign of x, which
  53649. * differs from what Javascript wants (see Section 9.6).
  53650. */
  53651. x = DUK_FMOD(x, DUK_DOUBLE_2TO32); /* -> x in ]-2**32, 2**32[ */
  53652. if (x < 0.0) {
  53653. x += DUK_DOUBLE_2TO32;
  53654. }
  53655. /* -> x in [0, 2**32[ */
  53656. if (is_toint32) {
  53657. if (x >= DUK_DOUBLE_2TO31) {
  53658. /* x in [2**31, 2**32[ */
  53659. x -= DUK_DOUBLE_2TO32; /* -> x in [-2**31,2**31[ */
  53660. }
  53661. }
  53662. return x;
  53663. }
  53664. DUK_INTERNAL duk_int32_t duk_js_toint32(duk_hthread *thr, duk_tval *tv) {
  53665. duk_double_t d;
  53666. #if defined(DUK_USE_FASTINT)
  53667. if (DUK_TVAL_IS_FASTINT(tv)) {
  53668. return DUK_TVAL_GET_FASTINT_I32(tv);
  53669. }
  53670. #endif
  53671. d = duk_js_tonumber(thr, tv); /* invalidates tv */
  53672. d = duk__toint32_touint32_helper(d, 1);
  53673. DUK_ASSERT(DUK_FPCLASSIFY(d) == DUK_FP_ZERO || DUK_FPCLASSIFY(d) == DUK_FP_NORMAL);
  53674. DUK_ASSERT(d >= -2147483648.0 && d <= 2147483647.0); /* [-0x80000000,0x7fffffff] */
  53675. DUK_ASSERT(d == ((duk_double_t) ((duk_int32_t) d))); /* whole, won't clip */
  53676. return (duk_int32_t) d;
  53677. }
  53678. DUK_INTERNAL duk_uint32_t duk_js_touint32(duk_hthread *thr, duk_tval *tv) {
  53679. duk_double_t d;
  53680. #if defined(DUK_USE_FASTINT)
  53681. if (DUK_TVAL_IS_FASTINT(tv)) {
  53682. return DUK_TVAL_GET_FASTINT_U32(tv);
  53683. }
  53684. #endif
  53685. d = duk_js_tonumber(thr, tv); /* invalidates tv */
  53686. d = duk__toint32_touint32_helper(d, 0);
  53687. DUK_ASSERT(DUK_FPCLASSIFY(d) == DUK_FP_ZERO || DUK_FPCLASSIFY(d) == DUK_FP_NORMAL);
  53688. DUK_ASSERT(d >= 0.0 && d <= 4294967295.0); /* [0x00000000, 0xffffffff] */
  53689. DUK_ASSERT(d == ((duk_double_t) ((duk_uint32_t) d))); /* whole, won't clip */
  53690. return (duk_uint32_t) d;
  53691. }
  53692. DUK_INTERNAL duk_uint16_t duk_js_touint16(duk_hthread *thr, duk_tval *tv) {
  53693. /* should be a safe way to compute this */
  53694. return (duk_uint16_t) (duk_js_touint32(thr, tv) & 0x0000ffffU);
  53695. }
  53696. /*
  53697. * ToString() (E5 Section 9.8)
  53698. *
  53699. * ==> implemented in the API.
  53700. */
  53701. /*
  53702. * ToObject() (E5 Section 9.9)
  53703. *
  53704. * ==> implemented in the API.
  53705. */
  53706. /*
  53707. * CheckObjectCoercible() (E5 Section 9.10)
  53708. *
  53709. * Note: no API equivalent now.
  53710. */
  53711. #if 0 /* unused */
  53712. DUK_INTERNAL void duk_js_checkobjectcoercible(duk_hthread *thr, duk_tval *tv_x) {
  53713. duk_small_uint_t tag = DUK_TVAL_GET_TAG(tv_x);
  53714. /* Note: this must match ToObject() behavior */
  53715. if (tag == DUK_TAG_UNDEFINED ||
  53716. tag == DUK_TAG_NULL ||
  53717. tag == DUK_TAG_POINTER ||
  53718. tag == DUK_TAG_BUFFER) {
  53719. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "not object coercible");
  53720. }
  53721. }
  53722. #endif
  53723. /*
  53724. * IsCallable() (E5 Section 9.11)
  53725. *
  53726. * XXX: API equivalent is a separate implementation now, and this has
  53727. * currently no callers.
  53728. */
  53729. #if 0 /* unused */
  53730. DUK_INTERNAL duk_bool_t duk_js_iscallable(duk_tval *tv_x) {
  53731. duk_hobject *obj;
  53732. if (!DUK_TVAL_IS_OBJECT(tv_x)) {
  53733. return 0;
  53734. }
  53735. obj = DUK_TVAL_GET_OBJECT(tv_x);
  53736. DUK_ASSERT(obj != NULL);
  53737. return DUK_HOBJECT_IS_CALLABLE(obj);
  53738. }
  53739. #endif
  53740. /*
  53741. * Loose equality, strict equality, and SameValue (E5 Sections 11.9.1, 11.9.4,
  53742. * 9.12). These have much in common so they can share some helpers.
  53743. *
  53744. * Future work notes:
  53745. *
  53746. * - Current implementation (and spec definition) has recursion; this should
  53747. * be fixed if possible.
  53748. *
  53749. * - String-to-number coercion should be possible without going through the
  53750. * value stack (and be more compact) if a shared helper is invoked.
  53751. */
  53752. /* Note that this is the same operation for strict and loose equality:
  53753. * - E5 Section 11.9.3, step 1.c (loose)
  53754. * - E5 Section 11.9.6, step 4 (strict)
  53755. */
  53756. DUK_LOCAL duk_bool_t duk__js_equals_number(duk_double_t x, duk_double_t y) {
  53757. #if defined(DUK_USE_PARANOID_MATH)
  53758. /* Straightforward algorithm, makes fewer compiler assumptions. */
  53759. duk_small_int_t cx = (duk_small_int_t) DUK_FPCLASSIFY(x);
  53760. duk_small_int_t cy = (duk_small_int_t) DUK_FPCLASSIFY(y);
  53761. if (cx == DUK_FP_NAN || cy == DUK_FP_NAN) {
  53762. return 0;
  53763. }
  53764. if (cx == DUK_FP_ZERO && cy == DUK_FP_ZERO) {
  53765. return 1;
  53766. }
  53767. if (x == y) {
  53768. return 1;
  53769. }
  53770. return 0;
  53771. #else /* DUK_USE_PARANOID_MATH */
  53772. /* Better equivalent algorithm. If the compiler is compliant, C and
  53773. * Ecmascript semantics are identical for this particular comparison.
  53774. * In particular, NaNs must never compare equal and zeroes must compare
  53775. * equal regardless of sign. Could also use a macro, but this inlines
  53776. * already nicely (no difference on gcc, for instance).
  53777. */
  53778. if (x == y) {
  53779. /* IEEE requires that NaNs compare false */
  53780. DUK_ASSERT(DUK_FPCLASSIFY(x) != DUK_FP_NAN);
  53781. DUK_ASSERT(DUK_FPCLASSIFY(y) != DUK_FP_NAN);
  53782. return 1;
  53783. } else {
  53784. /* IEEE requires that zeros compare the same regardless
  53785. * of their signed, so if both x and y are zeroes, they
  53786. * are caught above.
  53787. */
  53788. DUK_ASSERT(!(DUK_FPCLASSIFY(x) == DUK_FP_ZERO && DUK_FPCLASSIFY(y) == DUK_FP_ZERO));
  53789. return 0;
  53790. }
  53791. #endif /* DUK_USE_PARANOID_MATH */
  53792. }
  53793. DUK_LOCAL duk_bool_t duk__js_samevalue_number(duk_double_t x, duk_double_t y) {
  53794. #if defined(DUK_USE_PARANOID_MATH)
  53795. duk_small_int_t cx = (duk_small_int_t) DUK_FPCLASSIFY(x);
  53796. duk_small_int_t cy = (duk_small_int_t) DUK_FPCLASSIFY(y);
  53797. if (cx == DUK_FP_NAN && cy == DUK_FP_NAN) {
  53798. /* SameValue(NaN, NaN) = true, regardless of NaN sign or extra bits */
  53799. return 1;
  53800. }
  53801. if (cx == DUK_FP_ZERO && cy == DUK_FP_ZERO) {
  53802. /* Note: cannot assume that a non-zero return value of signbit() would
  53803. * always be the same -- hence cannot (portably) use something like:
  53804. *
  53805. * signbit(x) == signbit(y)
  53806. */
  53807. duk_small_int_t sx = (DUK_SIGNBIT(x) ? 1 : 0);
  53808. duk_small_int_t sy = (DUK_SIGNBIT(y) ? 1 : 0);
  53809. return (sx == sy);
  53810. }
  53811. /* normal comparison; known:
  53812. * - both x and y are not NaNs (but one of them can be)
  53813. * - both x and y are not zero (but one of them can be)
  53814. * - x and y may be denormal or infinite
  53815. */
  53816. return (x == y);
  53817. #else /* DUK_USE_PARANOID_MATH */
  53818. duk_small_int_t cx = (duk_small_int_t) DUK_FPCLASSIFY(x);
  53819. duk_small_int_t cy = (duk_small_int_t) DUK_FPCLASSIFY(y);
  53820. if (x == y) {
  53821. /* IEEE requires that NaNs compare false */
  53822. DUK_ASSERT(DUK_FPCLASSIFY(x) != DUK_FP_NAN);
  53823. DUK_ASSERT(DUK_FPCLASSIFY(y) != DUK_FP_NAN);
  53824. /* Using classification has smaller footprint than direct comparison. */
  53825. if (DUK_UNLIKELY(cx == DUK_FP_ZERO && cy == DUK_FP_ZERO)) {
  53826. /* Note: cannot assume that a non-zero return value of signbit() would
  53827. * always be the same -- hence cannot (portably) use something like:
  53828. *
  53829. * signbit(x) == signbit(y)
  53830. */
  53831. duk_small_int_t sx = (DUK_SIGNBIT(x) ? 1 : 0);
  53832. duk_small_int_t sy = (DUK_SIGNBIT(y) ? 1 : 0);
  53833. return (sx == sy);
  53834. }
  53835. return 1;
  53836. } else {
  53837. /* IEEE requires that zeros compare the same regardless
  53838. * of their signed, so if both x and y are zeroes, they
  53839. * are caught above.
  53840. */
  53841. DUK_ASSERT(!(DUK_FPCLASSIFY(x) == DUK_FP_ZERO && DUK_FPCLASSIFY(y) == DUK_FP_ZERO));
  53842. /* Difference to non-strict/strict comparison is that NaNs compare
  53843. * equal and signed zero signs matter.
  53844. */
  53845. if (DUK_UNLIKELY(cx == DUK_FP_NAN && cy == DUK_FP_NAN)) {
  53846. /* SameValue(NaN, NaN) = true, regardless of NaN sign or extra bits */
  53847. return 1;
  53848. }
  53849. return 0;
  53850. }
  53851. #endif /* DUK_USE_PARANOID_MATH */
  53852. }
  53853. DUK_INTERNAL duk_bool_t duk_js_equals_helper(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y, duk_small_int_t flags) {
  53854. duk_context *ctx = (duk_context *) thr;
  53855. duk_tval *tv_tmp;
  53856. /* If flags != 0 (strict or SameValue), thr can be NULL. For loose
  53857. * equals comparison it must be != NULL.
  53858. */
  53859. DUK_ASSERT(flags != 0 || thr != NULL);
  53860. /*
  53861. * Same type?
  53862. *
  53863. * Note: since number values have no explicit tag in the 8-byte
  53864. * representation, need the awkward if + switch.
  53865. */
  53866. #if defined(DUK_USE_FASTINT)
  53867. if (DUK_TVAL_IS_FASTINT(tv_x) && DUK_TVAL_IS_FASTINT(tv_y)) {
  53868. if (DUK_TVAL_GET_FASTINT(tv_x) == DUK_TVAL_GET_FASTINT(tv_y)) {
  53869. return 1;
  53870. } else {
  53871. return 0;
  53872. }
  53873. }
  53874. else
  53875. #endif
  53876. if (DUK_TVAL_IS_NUMBER(tv_x) && DUK_TVAL_IS_NUMBER(tv_y)) {
  53877. /* Catches both doubles and cases where only one argument is a fastint */
  53878. if (DUK_UNLIKELY((flags & DUK_EQUALS_FLAG_SAMEVALUE) != 0)) {
  53879. /* SameValue */
  53880. return duk__js_samevalue_number(DUK_TVAL_GET_NUMBER(tv_x),
  53881. DUK_TVAL_GET_NUMBER(tv_y));
  53882. } else {
  53883. /* equals and strict equals */
  53884. return duk__js_equals_number(DUK_TVAL_GET_NUMBER(tv_x),
  53885. DUK_TVAL_GET_NUMBER(tv_y));
  53886. }
  53887. } else if (DUK_TVAL_GET_TAG(tv_x) == DUK_TVAL_GET_TAG(tv_y)) {
  53888. switch (DUK_TVAL_GET_TAG(tv_x)) {
  53889. case DUK_TAG_UNDEFINED:
  53890. case DUK_TAG_NULL: {
  53891. return 1;
  53892. }
  53893. case DUK_TAG_BOOLEAN: {
  53894. return DUK_TVAL_GET_BOOLEAN(tv_x) == DUK_TVAL_GET_BOOLEAN(tv_y);
  53895. }
  53896. case DUK_TAG_POINTER: {
  53897. return DUK_TVAL_GET_POINTER(tv_x) == DUK_TVAL_GET_POINTER(tv_y);
  53898. }
  53899. case DUK_TAG_STRING:
  53900. case DUK_TAG_OBJECT: {
  53901. /* heap pointer comparison suffices */
  53902. return DUK_TVAL_GET_HEAPHDR(tv_x) == DUK_TVAL_GET_HEAPHDR(tv_y);
  53903. }
  53904. case DUK_TAG_BUFFER: {
  53905. if ((flags & (DUK_EQUALS_FLAG_STRICT | DUK_EQUALS_FLAG_SAMEVALUE)) != 0) {
  53906. /* heap pointer comparison suffices */
  53907. return DUK_TVAL_GET_HEAPHDR(tv_x) == DUK_TVAL_GET_HEAPHDR(tv_y);
  53908. } else {
  53909. /* non-strict equality for buffers compares contents */
  53910. duk_hbuffer *h_x = DUK_TVAL_GET_BUFFER(tv_x);
  53911. duk_hbuffer *h_y = DUK_TVAL_GET_BUFFER(tv_y);
  53912. duk_size_t len_x = DUK_HBUFFER_GET_SIZE(h_x);
  53913. duk_size_t len_y = DUK_HBUFFER_GET_SIZE(h_y);
  53914. void *buf_x;
  53915. void *buf_y;
  53916. if (len_x != len_y) {
  53917. return 0;
  53918. }
  53919. buf_x = (void *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h_x);
  53920. buf_y = (void *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h_y);
  53921. /* if len_x == len_y == 0, buf_x and/or buf_y may
  53922. * be NULL, but that's OK.
  53923. */
  53924. DUK_ASSERT(len_x == len_y);
  53925. DUK_ASSERT(len_x == 0 || buf_x != NULL);
  53926. DUK_ASSERT(len_y == 0 || buf_y != NULL);
  53927. return (DUK_MEMCMP(buf_x, buf_y, len_x) == 0) ? 1 : 0;
  53928. }
  53929. }
  53930. case DUK_TAG_LIGHTFUNC: {
  53931. /* At least 'magic' has a significant impact on function
  53932. * identity.
  53933. */
  53934. duk_small_uint_t lf_flags_x;
  53935. duk_small_uint_t lf_flags_y;
  53936. duk_c_function func_x;
  53937. duk_c_function func_y;
  53938. DUK_TVAL_GET_LIGHTFUNC(tv_x, func_x, lf_flags_x);
  53939. DUK_TVAL_GET_LIGHTFUNC(tv_y, func_y, lf_flags_y);
  53940. return ((func_x == func_y) && (lf_flags_x == lf_flags_y)) ? 1 : 0;
  53941. }
  53942. #if defined(DUK_USE_FASTINT)
  53943. case DUK_TAG_FASTINT:
  53944. #endif
  53945. default: {
  53946. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_x));
  53947. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_y));
  53948. DUK_UNREACHABLE();
  53949. return 0;
  53950. }
  53951. }
  53952. }
  53953. if ((flags & (DUK_EQUALS_FLAG_STRICT | DUK_EQUALS_FLAG_SAMEVALUE)) != 0) {
  53954. return 0;
  53955. }
  53956. DUK_ASSERT(flags == 0); /* non-strict equality from here on */
  53957. /*
  53958. * Types are different; various cases for non-strict comparison
  53959. *
  53960. * Since comparison is symmetric, we use a "swap trick" to reduce
  53961. * code size.
  53962. */
  53963. /* Undefined/null are considered equal (e.g. "null == undefined" -> true). */
  53964. if ((DUK_TVAL_IS_UNDEFINED(tv_x) && DUK_TVAL_IS_NULL(tv_y)) ||
  53965. (DUK_TVAL_IS_NULL(tv_x) && DUK_TVAL_IS_UNDEFINED(tv_y))) {
  53966. return 1;
  53967. }
  53968. /* Number/string-or-buffer -> coerce string to number (e.g. "'1.5' == 1.5" -> true). */
  53969. if (DUK_TVAL_IS_NUMBER(tv_x) && (DUK_TVAL_IS_STRING(tv_y) || DUK_TVAL_IS_BUFFER(tv_y))) {
  53970. /* the next 'if' is guaranteed to match after swap */
  53971. tv_tmp = tv_x;
  53972. tv_x = tv_y;
  53973. tv_y = tv_tmp;
  53974. }
  53975. if ((DUK_TVAL_IS_STRING(tv_x) || DUK_TVAL_IS_BUFFER(tv_x)) && DUK_TVAL_IS_NUMBER(tv_y)) {
  53976. /* XXX: this is possible without resorting to the value stack */
  53977. duk_double_t d1, d2;
  53978. d2 = DUK_TVAL_GET_NUMBER(tv_y);
  53979. duk_push_tval(ctx, tv_x);
  53980. duk_to_string(ctx, -1); /* buffer values are coerced first to string here */
  53981. duk_to_number(ctx, -1);
  53982. d1 = duk_require_number(ctx, -1);
  53983. duk_pop(ctx);
  53984. return duk__js_equals_number(d1, d2);
  53985. }
  53986. /* Buffer/string -> compare contents. */
  53987. if (DUK_TVAL_IS_BUFFER(tv_x) && DUK_TVAL_IS_STRING(tv_y)) {
  53988. tv_tmp = tv_x;
  53989. tv_x = tv_y;
  53990. tv_y = tv_tmp;
  53991. }
  53992. if (DUK_TVAL_IS_STRING(tv_x) && DUK_TVAL_IS_BUFFER(tv_y)) {
  53993. duk_hstring *h_x = DUK_TVAL_GET_STRING(tv_x);
  53994. duk_hbuffer *h_y = DUK_TVAL_GET_BUFFER(tv_y);
  53995. duk_size_t len_x = DUK_HSTRING_GET_BYTELEN(h_x);
  53996. duk_size_t len_y = DUK_HBUFFER_GET_SIZE(h_y);
  53997. void *buf_x;
  53998. void *buf_y;
  53999. if (len_x != len_y) {
  54000. return 0;
  54001. }
  54002. buf_x = (void *) DUK_HSTRING_GET_DATA(h_x);
  54003. buf_y = (void *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h_y);
  54004. /* if len_x == len_y == 0, buf_x and/or buf_y may
  54005. * be NULL, but that's OK.
  54006. */
  54007. DUK_ASSERT(len_x == len_y);
  54008. DUK_ASSERT(len_x == 0 || buf_x != NULL);
  54009. DUK_ASSERT(len_y == 0 || buf_y != NULL);
  54010. return (DUK_MEMCMP(buf_x, buf_y, len_x) == 0) ? 1 : 0;
  54011. }
  54012. /* Boolean/any -> coerce boolean to number and try again. If boolean is
  54013. * compared to a pointer, the final comparison after coercion now always
  54014. * yields false (as pointer vs. number compares to false), but this is
  54015. * not special cased.
  54016. */
  54017. if (DUK_TVAL_IS_BOOLEAN(tv_x)) {
  54018. tv_tmp = tv_x;
  54019. tv_x = tv_y;
  54020. tv_y = tv_tmp;
  54021. }
  54022. if (DUK_TVAL_IS_BOOLEAN(tv_y)) {
  54023. /* ToNumber(bool) is +1.0 or 0.0. Tagged boolean value is always 0 or 1. */
  54024. duk_bool_t rc;
  54025. DUK_ASSERT(DUK_TVAL_GET_BOOLEAN(tv_y) == 0 || DUK_TVAL_GET_BOOLEAN(tv_y) == 1);
  54026. duk_push_tval(ctx, tv_x);
  54027. duk_push_int(ctx, DUK_TVAL_GET_BOOLEAN(tv_y));
  54028. rc = duk_js_equals_helper(thr, duk_get_tval(ctx, -2), duk_get_tval(ctx, -1), 0 /*flags:nonstrict*/);
  54029. duk_pop_2(ctx);
  54030. return rc;
  54031. }
  54032. /* String-number-buffer/object -> coerce object to primitive (apparently without hint), then try again. */
  54033. if ((DUK_TVAL_IS_STRING(tv_x) || DUK_TVAL_IS_NUMBER(tv_x) || DUK_TVAL_IS_BUFFER(tv_x)) &&
  54034. DUK_TVAL_IS_OBJECT(tv_y)) {
  54035. tv_tmp = tv_x;
  54036. tv_x = tv_y;
  54037. tv_y = tv_tmp;
  54038. }
  54039. if (DUK_TVAL_IS_OBJECT(tv_x) &&
  54040. (DUK_TVAL_IS_STRING(tv_y) || DUK_TVAL_IS_NUMBER(tv_y) || DUK_TVAL_IS_BUFFER(tv_y))) {
  54041. duk_bool_t rc;
  54042. duk_push_tval(ctx, tv_x);
  54043. duk_push_tval(ctx, tv_y);
  54044. duk_to_primitive(ctx, -2, DUK_HINT_NONE); /* apparently no hint? */
  54045. rc = duk_js_equals_helper(thr, duk_get_tval(ctx, -2), duk_get_tval(ctx, -1), 0 /*flags:nonstrict*/);
  54046. duk_pop_2(ctx);
  54047. return rc;
  54048. }
  54049. /* Nothing worked -> not equal. */
  54050. return 0;
  54051. }
  54052. /*
  54053. * Comparisons (x >= y, x > y, x <= y, x < y)
  54054. *
  54055. * E5 Section 11.8.5: implement 'x < y' and then use negate and eval_left_first
  54056. * flags to get the rest.
  54057. */
  54058. /* XXX: this should probably just operate on the stack top, because it
  54059. * needs to push stuff on the stack anyway...
  54060. */
  54061. DUK_INTERNAL duk_small_int_t duk_js_string_compare(duk_hstring *h1, duk_hstring *h2) {
  54062. /*
  54063. * String comparison (E5 Section 11.8.5, step 4), which
  54064. * needs to compare codepoint by codepoint.
  54065. *
  54066. * However, UTF-8 allows us to use strcmp directly: the shared
  54067. * prefix will be encoded identically (UTF-8 has unique encoding)
  54068. * and the first differing character can be compared with a simple
  54069. * unsigned byte comparison (which strcmp does).
  54070. *
  54071. * This will not work properly for non-xutf-8 strings, but this
  54072. * is not an issue for compliance.
  54073. */
  54074. duk_size_t h1_len, h2_len, prefix_len;
  54075. duk_small_int_t rc;
  54076. DUK_ASSERT(h1 != NULL);
  54077. DUK_ASSERT(h2 != NULL);
  54078. h1_len = DUK_HSTRING_GET_BYTELEN(h1);
  54079. h2_len = DUK_HSTRING_GET_BYTELEN(h2);
  54080. prefix_len = (h1_len <= h2_len ? h1_len : h2_len);
  54081. /* XXX: this special case can now be removed with DUK_MEMCMP */
  54082. /* memcmp() should return zero (equal) for zero length, but avoid
  54083. * it because there are some platform specific bugs. Don't use
  54084. * strncmp() because it stops comparing at a NUL.
  54085. */
  54086. if (prefix_len == 0) {
  54087. rc = 0;
  54088. } else {
  54089. rc = DUK_MEMCMP((const char *) DUK_HSTRING_GET_DATA(h1),
  54090. (const char *) DUK_HSTRING_GET_DATA(h2),
  54091. prefix_len);
  54092. }
  54093. if (rc < 0) {
  54094. return -1;
  54095. } else if (rc > 0) {
  54096. return 1;
  54097. }
  54098. /* prefix matches, lengths matter now */
  54099. if (h1_len < h2_len) {
  54100. /* e.g. "x" < "xx" */
  54101. return -1;
  54102. } else if (h1_len > h2_len) {
  54103. return 1;
  54104. }
  54105. return 0;
  54106. }
  54107. DUK_INTERNAL duk_bool_t duk_js_compare_helper(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y, duk_small_int_t flags) {
  54108. duk_context *ctx = (duk_context *) thr;
  54109. duk_double_t d1, d2;
  54110. duk_small_int_t c1, c2;
  54111. duk_small_int_t s1, s2;
  54112. duk_small_int_t rc;
  54113. duk_bool_t retval;
  54114. /* Fast path for fastints */
  54115. #if defined(DUK_USE_FASTINT)
  54116. if (DUK_TVAL_IS_FASTINT(tv_x) && DUK_TVAL_IS_FASTINT(tv_y)) {
  54117. duk_int64_t v1 = DUK_TVAL_GET_FASTINT(tv_x);
  54118. duk_int64_t v2 = DUK_TVAL_GET_FASTINT(tv_y);
  54119. if (v1 < v2) {
  54120. /* 'lt is true' */
  54121. retval = 1;
  54122. } else {
  54123. retval = 0;
  54124. }
  54125. if (flags & DUK_COMPARE_FLAG_NEGATE) {
  54126. retval ^= 1;
  54127. }
  54128. return retval;
  54129. }
  54130. #endif /* DUK_USE_FASTINT */
  54131. /* Fast path for numbers (one of which may be a fastint) */
  54132. #if 1 /* XXX: make fast paths optional for size minimization? */
  54133. if (DUK_TVAL_IS_NUMBER(tv_x) && DUK_TVAL_IS_NUMBER(tv_y)) {
  54134. d1 = DUK_TVAL_GET_NUMBER(tv_x);
  54135. d2 = DUK_TVAL_GET_NUMBER(tv_y);
  54136. c1 = DUK_FPCLASSIFY(d1);
  54137. c2 = DUK_FPCLASSIFY(d2);
  54138. if (c1 == DUK_FP_NORMAL && c2 == DUK_FP_NORMAL) {
  54139. /* XXX: this is a very narrow check, and doesn't cover
  54140. * zeroes, subnormals, infinities, which compare normally.
  54141. */
  54142. if (d1 < d2) {
  54143. /* 'lt is true' */
  54144. retval = 1;
  54145. } else {
  54146. retval = 0;
  54147. }
  54148. if (flags & DUK_COMPARE_FLAG_NEGATE) {
  54149. retval ^= 1;
  54150. }
  54151. return retval;
  54152. }
  54153. }
  54154. #endif
  54155. /* Slow path */
  54156. duk_push_tval(ctx, tv_x);
  54157. duk_push_tval(ctx, tv_y);
  54158. if (flags & DUK_COMPARE_FLAG_EVAL_LEFT_FIRST) {
  54159. duk_to_primitive(ctx, -2, DUK_HINT_NUMBER);
  54160. duk_to_primitive(ctx, -1, DUK_HINT_NUMBER);
  54161. } else {
  54162. duk_to_primitive(ctx, -1, DUK_HINT_NUMBER);
  54163. duk_to_primitive(ctx, -2, DUK_HINT_NUMBER);
  54164. }
  54165. /* Note: reuse variables */
  54166. tv_x = duk_get_tval(ctx, -2);
  54167. tv_y = duk_get_tval(ctx, -1);
  54168. if (DUK_TVAL_IS_STRING(tv_x) && DUK_TVAL_IS_STRING(tv_y)) {
  54169. duk_hstring *h1 = DUK_TVAL_GET_STRING(tv_x);
  54170. duk_hstring *h2 = DUK_TVAL_GET_STRING(tv_y);
  54171. DUK_ASSERT(h1 != NULL);
  54172. DUK_ASSERT(h2 != NULL);
  54173. rc = duk_js_string_compare(h1, h2);
  54174. if (rc < 0) {
  54175. goto lt_true;
  54176. } else {
  54177. goto lt_false;
  54178. }
  54179. } else {
  54180. /* Ordering should not matter (E5 Section 11.8.5, step 3.a) but
  54181. * preserve it just in case.
  54182. */
  54183. if (flags & DUK_COMPARE_FLAG_EVAL_LEFT_FIRST) {
  54184. d1 = duk_to_number(ctx, -2);
  54185. d2 = duk_to_number(ctx, -1);
  54186. } else {
  54187. d2 = duk_to_number(ctx, -1);
  54188. d1 = duk_to_number(ctx, -2);
  54189. }
  54190. c1 = (duk_small_int_t) DUK_FPCLASSIFY(d1);
  54191. s1 = (duk_small_int_t) DUK_SIGNBIT(d1);
  54192. c2 = (duk_small_int_t) DUK_FPCLASSIFY(d2);
  54193. s2 = (duk_small_int_t) DUK_SIGNBIT(d2);
  54194. if (c1 == DUK_FP_NAN || c2 == DUK_FP_NAN) {
  54195. goto lt_undefined;
  54196. }
  54197. if (c1 == DUK_FP_ZERO && c2 == DUK_FP_ZERO) {
  54198. /* For all combinations: +0 < +0, +0 < -0, -0 < +0, -0 < -0,
  54199. * steps e, f, and g.
  54200. */
  54201. goto lt_false;
  54202. }
  54203. if (d1 == d2) {
  54204. goto lt_false;
  54205. }
  54206. if (c1 == DUK_FP_INFINITE && s1 == 0) {
  54207. /* x == +Infinity */
  54208. goto lt_false;
  54209. }
  54210. if (c2 == DUK_FP_INFINITE && s2 == 0) {
  54211. /* y == +Infinity */
  54212. goto lt_true;
  54213. }
  54214. if (c2 == DUK_FP_INFINITE && s2 != 0) {
  54215. /* y == -Infinity */
  54216. goto lt_false;
  54217. }
  54218. if (c1 == DUK_FP_INFINITE && s1 != 0) {
  54219. /* x == -Infinity */
  54220. goto lt_true;
  54221. }
  54222. if (d1 < d2) {
  54223. goto lt_true;
  54224. }
  54225. goto lt_false;
  54226. }
  54227. lt_undefined:
  54228. /* Note: undefined from Section 11.8.5 always results in false
  54229. * return (see e.g. Section 11.8.3) - hence special treatment here.
  54230. */
  54231. retval = 0;
  54232. goto cleanup;
  54233. lt_true:
  54234. if (flags & DUK_COMPARE_FLAG_NEGATE) {
  54235. retval = 0;
  54236. goto cleanup;
  54237. } else {
  54238. retval = 1;
  54239. goto cleanup;
  54240. }
  54241. /* never here */
  54242. lt_false:
  54243. if (flags & DUK_COMPARE_FLAG_NEGATE) {
  54244. retval = 1;
  54245. goto cleanup;
  54246. } else {
  54247. retval = 0;
  54248. goto cleanup;
  54249. }
  54250. /* never here */
  54251. cleanup:
  54252. duk_pop_2(ctx);
  54253. return retval;
  54254. }
  54255. /*
  54256. * instanceof
  54257. */
  54258. /*
  54259. * E5 Section 11.8.6 describes the main algorithm, which uses
  54260. * [[HasInstance]]. [[HasInstance]] is defined for only
  54261. * function objects:
  54262. *
  54263. * - Normal functions:
  54264. * E5 Section 15.3.5.3
  54265. * - Functions established with Function.prototype.bind():
  54266. * E5 Section 15.3.4.5.3
  54267. *
  54268. * For other objects, a TypeError is thrown.
  54269. */
  54270. DUK_INTERNAL duk_bool_t duk_js_instanceof(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y) {
  54271. duk_context *ctx = (duk_context *) thr;
  54272. duk_hobject *func;
  54273. duk_hobject *val;
  54274. duk_hobject *proto;
  54275. duk_uint_t sanity;
  54276. /*
  54277. * Get the values onto the stack first. It would be possible to cover
  54278. * some normal cases without resorting to the value stack.
  54279. *
  54280. * The right hand side could be a light function (as they generally
  54281. * behave like objects). Light functions never have a 'prototype'
  54282. * property so E5.1 Section 15.3.5.3 step 3 always throws a TypeError.
  54283. * Using duk_require_hobject() is thus correct (except for error msg).
  54284. */
  54285. duk_push_tval(ctx, tv_x);
  54286. duk_push_tval(ctx, tv_y);
  54287. func = duk_require_hobject(ctx, -1);
  54288. /*
  54289. * For bound objects, [[HasInstance]] just calls the target function
  54290. * [[HasInstance]]. If that is again a bound object, repeat until
  54291. * we find a non-bound Function object.
  54292. */
  54293. /* XXX: this bound function resolution also happens elsewhere,
  54294. * move into a shared helper.
  54295. */
  54296. sanity = DUK_HOBJECT_BOUND_CHAIN_SANITY;
  54297. do {
  54298. /* check func supports [[HasInstance]] (this is checked for every function
  54299. * in the bound chain, including the final one)
  54300. */
  54301. if (!DUK_HOBJECT_IS_CALLABLE(func)) {
  54302. /*
  54303. * Note: of native Ecmascript objects, only Function instances
  54304. * have a [[HasInstance]] internal property. Custom objects might
  54305. * also have it, but not in current implementation.
  54306. *
  54307. * XXX: add a separate flag, DUK_HOBJECT_FLAG_ALLOW_INSTANCEOF?
  54308. */
  54309. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "invalid instanceof rval");
  54310. }
  54311. if (!DUK_HOBJECT_HAS_BOUND(func)) {
  54312. break;
  54313. }
  54314. /* [ ... lval rval ] */
  54315. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_TARGET); /* -> [ ... lval rval new_rval ] */
  54316. duk_replace(ctx, -1); /* -> [ ... lval new_rval ] */
  54317. func = duk_require_hobject(ctx, -1);
  54318. /* func support for [[HasInstance]] checked in the beginning of the loop */
  54319. } while (--sanity > 0);
  54320. if (sanity == 0) {
  54321. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_BOUND_CHAIN_LIMIT);
  54322. }
  54323. /*
  54324. * 'func' is now a non-bound object which supports [[HasInstance]]
  54325. * (which here just means DUK_HOBJECT_FLAG_CALLABLE). Move on
  54326. * to execute E5 Section 15.3.5.3.
  54327. */
  54328. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func));
  54329. DUK_ASSERT(DUK_HOBJECT_IS_CALLABLE(func));
  54330. /* [ ... lval rval(func) ] */
  54331. /* Handle lightfuncs through object coercion for now. */
  54332. /* XXX: direct implementation */
  54333. val = duk_get_hobject_or_lfunc_coerce(ctx, -2);
  54334. if (!val) {
  54335. goto pop_and_false;
  54336. }
  54337. duk_get_prop_stridx(ctx, -1, DUK_STRIDX_PROTOTYPE); /* -> [ ... lval rval rval.prototype ] */
  54338. proto = duk_require_hobject(ctx, -1);
  54339. duk_pop(ctx); /* -> [ ... lval rval ] */
  54340. sanity = DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY;
  54341. do {
  54342. /*
  54343. * Note: prototype chain is followed BEFORE first comparison. This
  54344. * means that the instanceof lval is never itself compared to the
  54345. * rval.prototype property. This is apparently intentional, see E5
  54346. * Section 15.3.5.3, step 4.a.
  54347. *
  54348. * Also note:
  54349. *
  54350. * js> (function() {}) instanceof Function
  54351. * true
  54352. * js> Function instanceof Function
  54353. * true
  54354. *
  54355. * For the latter, h_proto will be Function.prototype, which is the
  54356. * built-in Function prototype. Because Function.[[Prototype]] is
  54357. * also the built-in Function prototype, the result is true.
  54358. */
  54359. val = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, val);
  54360. if (!val) {
  54361. goto pop_and_false;
  54362. } else if (val == proto) {
  54363. goto pop_and_true;
  54364. }
  54365. /* follow prototype chain */
  54366. } while (--sanity > 0);
  54367. if (sanity == 0) {
  54368. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_PROTOTYPE_CHAIN_LIMIT);
  54369. }
  54370. DUK_UNREACHABLE();
  54371. pop_and_false:
  54372. duk_pop_2(ctx);
  54373. return 0;
  54374. pop_and_true:
  54375. duk_pop_2(ctx);
  54376. return 1;
  54377. }
  54378. /*
  54379. * in
  54380. */
  54381. /*
  54382. * E5 Sections 11.8.7, 8.12.6.
  54383. *
  54384. * Basically just a property existence check using [[HasProperty]].
  54385. */
  54386. DUK_INTERNAL duk_bool_t duk_js_in(duk_hthread *thr, duk_tval *tv_x, duk_tval *tv_y) {
  54387. duk_context *ctx = (duk_context *) thr;
  54388. duk_bool_t retval;
  54389. /*
  54390. * Get the values onto the stack first. It would be possible to cover
  54391. * some normal cases without resorting to the value stack (e.g. if
  54392. * lval is already a string).
  54393. */
  54394. /* XXX: The ES5/5.1/6 specifications require that the key in 'key in obj'
  54395. * must be string coerced before the internal HasProperty() algorithm is
  54396. * invoked. A fast path skipping coercion could be safely implemented for
  54397. * numbers (as number-to-string coercion has no side effects). For ES6
  54398. * proxy behavior, the trap 'key' argument must be in a string coerced
  54399. * form (which is a shame).
  54400. */
  54401. /* TypeError if rval is not an object (or lightfunc which should behave
  54402. * like a Function instance).
  54403. */
  54404. duk_push_tval(ctx, tv_x);
  54405. duk_push_tval(ctx, tv_y);
  54406. duk_require_type_mask(ctx, -1, DUK_TYPE_MASK_OBJECT | DUK_TYPE_MASK_LIGHTFUNC);
  54407. duk_to_string(ctx, -2); /* coerce lval with ToString() */
  54408. retval = duk_hobject_hasprop(thr, duk_get_tval(ctx, -1), duk_get_tval(ctx, -2));
  54409. duk_pop_2(ctx);
  54410. return retval;
  54411. }
  54412. /*
  54413. * typeof
  54414. *
  54415. * E5 Section 11.4.3.
  54416. *
  54417. * Very straightforward. The only question is what to return for our
  54418. * non-standard tag / object types.
  54419. *
  54420. * There is an unfortunate string constant define naming problem with
  54421. * typeof return values for e.g. "Object" and "object"; careful with
  54422. * the built-in string defines. The LC_XXX defines are used for the
  54423. * lowercase variants now.
  54424. */
  54425. DUK_INTERNAL duk_hstring *duk_js_typeof(duk_hthread *thr, duk_tval *tv_x) {
  54426. duk_small_int_t stridx = 0;
  54427. switch (DUK_TVAL_GET_TAG(tv_x)) {
  54428. case DUK_TAG_UNDEFINED: {
  54429. stridx = DUK_STRIDX_LC_UNDEFINED;
  54430. break;
  54431. }
  54432. case DUK_TAG_NULL: {
  54433. /* Note: not a typo, "object" is returned for a null value */
  54434. stridx = DUK_STRIDX_LC_OBJECT;
  54435. break;
  54436. }
  54437. case DUK_TAG_BOOLEAN: {
  54438. stridx = DUK_STRIDX_LC_BOOLEAN;
  54439. break;
  54440. }
  54441. case DUK_TAG_POINTER: {
  54442. /* implementation specific */
  54443. stridx = DUK_STRIDX_LC_POINTER;
  54444. break;
  54445. }
  54446. case DUK_TAG_STRING: {
  54447. stridx = DUK_STRIDX_LC_STRING;
  54448. break;
  54449. }
  54450. case DUK_TAG_OBJECT: {
  54451. duk_hobject *obj = DUK_TVAL_GET_OBJECT(tv_x);
  54452. DUK_ASSERT(obj != NULL);
  54453. if (DUK_HOBJECT_IS_CALLABLE(obj)) {
  54454. stridx = DUK_STRIDX_LC_FUNCTION;
  54455. } else {
  54456. stridx = DUK_STRIDX_LC_OBJECT;
  54457. }
  54458. break;
  54459. }
  54460. case DUK_TAG_BUFFER: {
  54461. /* implementation specific */
  54462. stridx = DUK_STRIDX_LC_BUFFER;
  54463. break;
  54464. }
  54465. case DUK_TAG_LIGHTFUNC: {
  54466. stridx = DUK_STRIDX_LC_FUNCTION;
  54467. break;
  54468. }
  54469. #if defined(DUK_USE_FASTINT)
  54470. case DUK_TAG_FASTINT:
  54471. #endif
  54472. default: {
  54473. /* number */
  54474. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv_x));
  54475. stridx = DUK_STRIDX_LC_NUMBER;
  54476. break;
  54477. }
  54478. }
  54479. DUK_ASSERT(stridx >= 0 && stridx < DUK_HEAP_NUM_STRINGS);
  54480. return DUK_HTHREAD_GET_STRING(thr, stridx);
  54481. }
  54482. /*
  54483. * Array index and length
  54484. *
  54485. * Array index: E5 Section 15.4
  54486. * Array length: E5 Section 15.4.5.1 steps 3.c - 3.d (array length write)
  54487. *
  54488. * The DUK_HSTRING_GET_ARRIDX_SLOW() and DUK_HSTRING_GET_ARRIDX_FAST() macros
  54489. * call duk_js_to_arrayindex_string_helper().
  54490. */
  54491. DUK_INTERNAL duk_small_int_t duk_js_to_arrayindex_raw_string(const duk_uint8_t *str, duk_uint32_t blen, duk_uarridx_t *out_idx) {
  54492. duk_uarridx_t res, new_res;
  54493. if (blen == 0 || blen > 10) {
  54494. goto parse_fail;
  54495. }
  54496. if (str[0] == (duk_uint8_t) '0' && blen > 1) {
  54497. goto parse_fail;
  54498. }
  54499. /* Accept 32-bit decimal integers, no leading zeroes, signs, etc.
  54500. * Leading zeroes are not accepted (zero index "0" is an exception
  54501. * handled above).
  54502. */
  54503. res = 0;
  54504. while (blen-- > 0) {
  54505. duk_uint8_t c = *str++;
  54506. if (c >= (duk_uint8_t) '0' && c <= (duk_uint8_t) '9') {
  54507. new_res = res * 10 + (duk_uint32_t) (c - (duk_uint8_t) '0');
  54508. if (new_res < res) {
  54509. /* overflow, more than 32 bits -> not an array index */
  54510. goto parse_fail;
  54511. }
  54512. res = new_res;
  54513. } else {
  54514. goto parse_fail;
  54515. }
  54516. }
  54517. *out_idx = res;
  54518. return 1;
  54519. parse_fail:
  54520. *out_idx = DUK_HSTRING_NO_ARRAY_INDEX;
  54521. return 0;
  54522. }
  54523. /* Called by duk_hstring.h macros */
  54524. DUK_INTERNAL duk_uarridx_t duk_js_to_arrayindex_string_helper(duk_hstring *h) {
  54525. duk_uarridx_t res;
  54526. duk_small_int_t rc;
  54527. if (!DUK_HSTRING_HAS_ARRIDX(h)) {
  54528. return DUK_HSTRING_NO_ARRAY_INDEX;
  54529. }
  54530. rc = duk_js_to_arrayindex_raw_string(DUK_HSTRING_GET_DATA(h),
  54531. DUK_HSTRING_GET_BYTELEN(h),
  54532. &res);
  54533. DUK_UNREF(rc);
  54534. DUK_ASSERT(rc != 0);
  54535. return res;
  54536. }
  54537. #line 1 "duk_js_var.c"
  54538. /*
  54539. * Identifier access and function closure handling.
  54540. *
  54541. * Provides the primitives for slow path identifier accesses: GETVAR,
  54542. * PUTVAR, DELVAR, etc. The fast path, direct register accesses, should
  54543. * be used for most identifier accesses. Consequently, these slow path
  54544. * primitives should be optimized for maximum compactness.
  54545. *
  54546. * Ecmascript environment records (declarative and object) are represented
  54547. * as internal objects with control keys. Environment records have a
  54548. * parent record ("outer environment reference") which is represented by
  54549. * the implicit prototype for technical reasons (in other words, it is a
  54550. * convenient field). The prototype chain is not followed in the ordinary
  54551. * sense for variable lookups.
  54552. *
  54553. * See identifier-handling.txt for more details on the identifier algorithms
  54554. * and the internal representation. See function-objects.txt for details on
  54555. * what function templates and instances are expected to look like.
  54556. *
  54557. * Care must be taken to avoid duk_tval pointer invalidation caused by
  54558. * e.g. value stack or object resizing.
  54559. *
  54560. * TODO: properties for function instances could be initialized much more
  54561. * efficiently by creating a property allocation for a certain size and
  54562. * filling in keys and values directly (and INCREFing both with "bulk incref"
  54563. * primitives.
  54564. *
  54565. * XXX: duk_hobject_getprop() and duk_hobject_putprop() calls are a bit
  54566. * awkward (especially because they follow the prototype chain); rework
  54567. * if "raw" own property helpers are added.
  54568. */
  54569. /* include removed: duk_internal.h */
  54570. /*
  54571. * Local result type for duk__get_identifier_reference() lookup.
  54572. */
  54573. typedef struct {
  54574. duk_hobject *holder; /* for object-bound identifiers */
  54575. duk_tval *value; /* for register-bound and declarative env identifiers */
  54576. duk_int_t attrs; /* property attributes for identifier (relevant if value != NULL) */
  54577. duk_tval *this_binding;
  54578. duk_hobject *env;
  54579. } duk__id_lookup_result;
  54580. /*
  54581. * Create a new function object based on a "template function" which contains
  54582. * compiled bytecode, constants, etc, but lacks a lexical environment.
  54583. *
  54584. * Ecmascript requires that each created closure is a separate object, with
  54585. * its own set of editable properties. However, structured property values
  54586. * (such as the formal arguments list and the variable map) are shared.
  54587. * Also the bytecode, constants, and inner functions are shared.
  54588. *
  54589. * See E5 Section 13.2 for detailed requirements on the function objects;
  54590. * there are no similar requirements for function "templates" which are an
  54591. * implementation dependent internal feature. Also see function-objects.txt
  54592. * for a discussion on the function instance properties provided by this
  54593. * implementation.
  54594. *
  54595. * Notes:
  54596. *
  54597. * * Order of internal properties should match frequency of use, since the
  54598. * properties will be linearly scanned on lookup (functions usually don't
  54599. * have enough properties to warrant a hash part).
  54600. *
  54601. * * The created closure is independent of its template; they do share the
  54602. * same 'data' buffer object, but the template object itself can be freed
  54603. * even if the closure object remains reachable.
  54604. */
  54605. DUK_LOCAL void duk__inc_data_inner_refcounts(duk_hthread *thr, duk_hcompiledfunction *f) {
  54606. duk_tval *tv, *tv_end;
  54607. duk_hobject **funcs, **funcs_end;
  54608. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, f) != NULL); /* compiled functions must be created 'atomically' */
  54609. DUK_UNREF(thr);
  54610. tv = DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(thr->heap, f);
  54611. tv_end = DUK_HCOMPILEDFUNCTION_GET_CONSTS_END(thr->heap, f);
  54612. while (tv < tv_end) {
  54613. DUK_TVAL_INCREF(thr, tv);
  54614. tv++;
  54615. }
  54616. funcs = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(thr->heap, f);
  54617. funcs_end = DUK_HCOMPILEDFUNCTION_GET_FUNCS_END(thr->heap, f);
  54618. while (funcs < funcs_end) {
  54619. DUK_HEAPHDR_INCREF(thr, (duk_heaphdr *) *funcs);
  54620. funcs++;
  54621. }
  54622. }
  54623. /* Push a new closure on the stack.
  54624. *
  54625. * Note: if fun_temp has NEWENV, i.e. a new lexical and variable declaration
  54626. * is created when the function is called, only outer_lex_env matters
  54627. * (outer_var_env is ignored and may or may not be same as outer_lex_env).
  54628. */
  54629. DUK_LOCAL const duk_uint16_t duk__closure_copy_proplist[] = {
  54630. /* order: most frequent to least frequent */
  54631. DUK_STRIDX_INT_VARMAP,
  54632. DUK_STRIDX_INT_FORMALS,
  54633. DUK_STRIDX_NAME,
  54634. DUK_STRIDX_INT_PC2LINE,
  54635. DUK_STRIDX_FILE_NAME,
  54636. DUK_STRIDX_INT_SOURCE
  54637. };
  54638. DUK_INTERNAL
  54639. void duk_js_push_closure(duk_hthread *thr,
  54640. duk_hcompiledfunction *fun_temp,
  54641. duk_hobject *outer_var_env,
  54642. duk_hobject *outer_lex_env) {
  54643. duk_context *ctx = (duk_context *) thr;
  54644. duk_hcompiledfunction *fun_clos;
  54645. duk_small_uint_t i;
  54646. duk_uint_t len_value;
  54647. DUK_ASSERT(fun_temp != NULL);
  54648. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, fun_temp) != NULL);
  54649. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_FUNCS(thr->heap, fun_temp) != NULL);
  54650. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_BYTECODE(thr->heap, fun_temp) != NULL);
  54651. DUK_ASSERT(outer_var_env != NULL);
  54652. DUK_ASSERT(outer_lex_env != NULL);
  54653. duk_push_compiledfunction(ctx);
  54654. duk_push_hobject(ctx, &fun_temp->obj); /* -> [ ... closure template ] */
  54655. fun_clos = (duk_hcompiledfunction *) duk_get_hcompiledfunction(ctx, -2);
  54656. DUK_ASSERT(fun_clos != NULL);
  54657. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION((duk_hobject *) fun_clos));
  54658. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, fun_clos) == NULL);
  54659. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_FUNCS(thr->heap, fun_clos) == NULL);
  54660. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_BYTECODE(thr->heap, fun_clos) == NULL);
  54661. DUK_HCOMPILEDFUNCTION_SET_DATA(thr->heap, fun_clos, DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, fun_temp));
  54662. DUK_HCOMPILEDFUNCTION_SET_FUNCS(thr->heap, fun_clos, DUK_HCOMPILEDFUNCTION_GET_FUNCS(thr->heap, fun_temp));
  54663. DUK_HCOMPILEDFUNCTION_SET_BYTECODE(thr->heap, fun_clos, DUK_HCOMPILEDFUNCTION_GET_BYTECODE(thr->heap, fun_temp));
  54664. /* Note: all references inside 'data' need to get their refcounts
  54665. * upped too. This is the case because refcounts are decreased
  54666. * through every function referencing 'data' independently.
  54667. */
  54668. DUK_HBUFFER_INCREF(thr, DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, fun_clos));
  54669. duk__inc_data_inner_refcounts(thr, fun_temp);
  54670. fun_clos->nregs = fun_temp->nregs;
  54671. fun_clos->nargs = fun_temp->nargs;
  54672. #if defined(DUK_USE_DEBUGGER_SUPPORT)
  54673. fun_clos->start_line = fun_temp->start_line;
  54674. fun_clos->end_line = fun_temp->end_line;
  54675. #endif
  54676. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, fun_clos) != NULL);
  54677. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_FUNCS(thr->heap, fun_clos) != NULL);
  54678. DUK_ASSERT(DUK_HCOMPILEDFUNCTION_GET_BYTECODE(thr->heap, fun_clos) != NULL);
  54679. /* XXX: could also copy from template, but there's no way to have any
  54680. * other value here now (used code has no access to the template).
  54681. */
  54682. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, &fun_clos->obj, thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE]);
  54683. /*
  54684. * Init/assert flags, copying them where appropriate. Some flags
  54685. * (like NEWENV) are processed separately below.
  54686. */
  54687. /* XXX: copy flags using a mask */
  54688. DUK_ASSERT(DUK_HOBJECT_HAS_EXTENSIBLE(&fun_clos->obj));
  54689. DUK_HOBJECT_SET_CONSTRUCTABLE(&fun_clos->obj); /* Note: not set in template (has no "prototype") */
  54690. DUK_ASSERT(DUK_HOBJECT_HAS_CONSTRUCTABLE(&fun_clos->obj));
  54691. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(&fun_clos->obj));
  54692. DUK_ASSERT(DUK_HOBJECT_HAS_COMPILEDFUNCTION(&fun_clos->obj));
  54693. DUK_ASSERT(!DUK_HOBJECT_HAS_NATIVEFUNCTION(&fun_clos->obj));
  54694. DUK_ASSERT(!DUK_HOBJECT_HAS_THREAD(&fun_clos->obj));
  54695. /* DUK_HOBJECT_FLAG_ARRAY_PART: don't care */
  54696. if (DUK_HOBJECT_HAS_STRICT(&fun_temp->obj)) {
  54697. DUK_HOBJECT_SET_STRICT(&fun_clos->obj);
  54698. }
  54699. if (DUK_HOBJECT_HAS_NOTAIL(&fun_temp->obj)) {
  54700. DUK_HOBJECT_SET_NOTAIL(&fun_clos->obj);
  54701. }
  54702. /* DUK_HOBJECT_FLAG_NEWENV: handled below */
  54703. DUK_ASSERT(!DUK_HOBJECT_HAS_NAMEBINDING(&fun_clos->obj));
  54704. if (DUK_HOBJECT_HAS_CREATEARGS(&fun_temp->obj)) {
  54705. DUK_HOBJECT_SET_CREATEARGS(&fun_clos->obj);
  54706. }
  54707. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARRAY(&fun_clos->obj));
  54708. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_STRINGOBJ(&fun_clos->obj));
  54709. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARGUMENTS(&fun_clos->obj));
  54710. /*
  54711. * Setup environment record properties based on the template and
  54712. * its flags.
  54713. *
  54714. * If DUK_HOBJECT_HAS_NEWENV(fun_temp) is true, the environment
  54715. * records represent identifiers "outside" the function; the
  54716. * "inner" environment records are created on demand. Otherwise,
  54717. * the environment records are those that will be directly used
  54718. * (e.g. for declarations).
  54719. *
  54720. * _Lexenv is always set; _Varenv defaults to _Lexenv if missing,
  54721. * so _Varenv is only set if _Lexenv != _Varenv.
  54722. *
  54723. * This is relatively complex, see doc/identifier-handling.txt.
  54724. */
  54725. if (DUK_HOBJECT_HAS_NEWENV(&fun_temp->obj)) {
  54726. DUK_HOBJECT_SET_NEWENV(&fun_clos->obj);
  54727. if (DUK_HOBJECT_HAS_NAMEBINDING(&fun_temp->obj)) {
  54728. duk_hobject *proto;
  54729. /*
  54730. * Named function expression, name needs to be bound
  54731. * in an intermediate environment record. The "outer"
  54732. * lexical/variable environment will thus be:
  54733. *
  54734. * a) { funcname: <func>, __prototype: outer_lex_env }
  54735. * b) { funcname: <func>, __prototype: <globalenv> } (if outer_lex_env missing)
  54736. */
  54737. DUK_ASSERT(duk_has_prop_stridx(ctx, -1, DUK_STRIDX_NAME)); /* required if NAMEBINDING set */
  54738. if (outer_lex_env) {
  54739. proto = outer_lex_env;
  54740. } else {
  54741. proto = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  54742. }
  54743. /* -> [ ... closure template env ] */
  54744. (void) duk_push_object_helper_proto(ctx,
  54745. DUK_HOBJECT_FLAG_EXTENSIBLE |
  54746. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_DECENV),
  54747. proto);
  54748. /* It's important that duk_xdef_prop() is a 'raw define' so that any
  54749. * properties in an ancestor are never an issue (they should never be
  54750. * e.g. non-writable, but just in case).
  54751. */
  54752. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_NAME); /* -> [ ... closure template env funcname ] */
  54753. duk_dup(ctx, -4); /* -> [ ... closure template env funcname closure ] */
  54754. duk_xdef_prop(ctx, -3, DUK_PROPDESC_FLAGS_NONE); /* -> [ ... closure template env ] */
  54755. /* env[funcname] = closure */
  54756. /* [ ... closure template env ] */
  54757. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_INT_LEXENV, DUK_PROPDESC_FLAGS_WC);
  54758. /* since closure has NEWENV, never define DUK_STRIDX_INT_VARENV, as it
  54759. * will be ignored anyway
  54760. */
  54761. /* [ ... closure template ] */
  54762. } else {
  54763. /*
  54764. * Other cases (function declaration, anonymous function expression,
  54765. * strict direct eval code). The "outer" environment will be whatever
  54766. * the caller gave us.
  54767. */
  54768. duk_push_hobject(ctx, outer_lex_env); /* -> [ ... closure template env ] */
  54769. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_INT_LEXENV, DUK_PROPDESC_FLAGS_WC);
  54770. /* since closure has NEWENV, never define DUK_STRIDX_INT_VARENV, as it
  54771. * will be ignored anyway
  54772. */
  54773. /* [ ... closure template ] */
  54774. }
  54775. } else {
  54776. /*
  54777. * Function gets no new environment when called. This is the
  54778. * case for global code, indirect eval code, and non-strict
  54779. * direct eval code. There is no direct correspondence to the
  54780. * E5 specification, as global/eval code is not exposed as a
  54781. * function.
  54782. */
  54783. DUK_ASSERT(!DUK_HOBJECT_HAS_NAMEBINDING(&fun_temp->obj));
  54784. duk_push_hobject(ctx, outer_lex_env); /* -> [ ... closure template env ] */
  54785. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_INT_LEXENV, DUK_PROPDESC_FLAGS_WC);
  54786. if (outer_var_env != outer_lex_env) {
  54787. duk_push_hobject(ctx, outer_var_env); /* -> [ ... closure template env ] */
  54788. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_INT_VARENV, DUK_PROPDESC_FLAGS_WC);
  54789. }
  54790. }
  54791. #ifdef DUK_USE_DDDPRINT
  54792. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_INT_VARENV);
  54793. duk_get_prop_stridx(ctx, -3, DUK_STRIDX_INT_LEXENV);
  54794. DUK_DDD(DUK_DDDPRINT("closure varenv -> %!ipT, lexenv -> %!ipT",
  54795. (duk_tval *) duk_get_tval(ctx, -2),
  54796. (duk_tval *) duk_get_tval(ctx, -1)));
  54797. duk_pop_2(ctx);
  54798. #endif
  54799. /*
  54800. * Copy some internal properties directly
  54801. *
  54802. * The properties will be writable and configurable, but not enumerable.
  54803. */
  54804. /* [ ... closure template ] */
  54805. DUK_DDD(DUK_DDDPRINT("copying properties: closure=%!iT, template=%!iT",
  54806. (duk_tval *) duk_get_tval(ctx, -2),
  54807. (duk_tval *) duk_get_tval(ctx, -1)));
  54808. for (i = 0; i < (duk_small_uint_t) (sizeof(duk__closure_copy_proplist) / sizeof(duk_uint16_t)); i++) {
  54809. duk_small_int_t stridx = (duk_small_int_t) duk__closure_copy_proplist[i];
  54810. if (duk_get_prop_stridx(ctx, -1, stridx)) {
  54811. /* [ ... closure template val ] */
  54812. DUK_DDD(DUK_DDDPRINT("copying property, stridx=%ld -> found", (long) stridx));
  54813. duk_xdef_prop_stridx(ctx, -3, stridx, DUK_PROPDESC_FLAGS_WC);
  54814. } else {
  54815. DUK_DDD(DUK_DDDPRINT("copying property, stridx=%ld -> not found", (long) stridx));
  54816. duk_pop(ctx);
  54817. }
  54818. }
  54819. /*
  54820. * "length" maps to number of formals (E5 Section 13.2) for function
  54821. * declarations/expressions (non-bound functions). Note that 'nargs'
  54822. * is NOT necessarily equal to the number of arguments.
  54823. */
  54824. /* [ ... closure template ] */
  54825. len_value = 0;
  54826. /* XXX: use helper for size optimization */
  54827. if (duk_get_prop_stridx(ctx, -2, DUK_STRIDX_INT_FORMALS)) {
  54828. /* [ ... closure template formals ] */
  54829. DUK_ASSERT(duk_has_prop_stridx(ctx, -1, DUK_STRIDX_LENGTH));
  54830. DUK_ASSERT(duk_get_length(ctx, -1) <= DUK_UINT_MAX); /* formal arg limits */
  54831. len_value = (duk_uint_t) duk_get_length(ctx, -1);
  54832. } else {
  54833. /* XXX: what to do if _Formals is not empty but compiler has
  54834. * optimized it away -- read length from an explicit property
  54835. * then?
  54836. */
  54837. }
  54838. duk_pop(ctx);
  54839. duk_push_uint(ctx, len_value); /* [ ... closure template len_value ] */
  54840. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_LENGTH, DUK_PROPDESC_FLAGS_NONE);
  54841. /*
  54842. * "prototype" is, by default, a fresh object with the "constructor"
  54843. * property.
  54844. *
  54845. * Note that this creates a circular reference for every function
  54846. * instance (closure) which prevents refcount-based collection of
  54847. * function instances.
  54848. *
  54849. * XXX: Try to avoid creating the default prototype object, because
  54850. * many functions are not used as constructors and the default
  54851. * prototype is unnecessary. Perhaps it could be created on-demand
  54852. * when it is first accessed?
  54853. */
  54854. /* [ ... closure template ] */
  54855. duk_push_object(ctx); /* -> [ ... closure template newobj ] */
  54856. duk_dup(ctx, -3); /* -> [ ... closure template newobj closure ] */
  54857. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_CONSTRUCTOR, DUK_PROPDESC_FLAGS_WC); /* -> [ ... closure template newobj ] */
  54858. duk_compact(ctx, -1); /* compact the prototype */
  54859. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_PROTOTYPE, DUK_PROPDESC_FLAGS_W); /* -> [ ... closure template ] */
  54860. /*
  54861. * "arguments" and "caller" must be mapped to throwers for strict
  54862. * mode and bound functions (E5 Section 15.3.5).
  54863. *
  54864. * XXX: This is expensive to have for every strict function instance.
  54865. * Try to implement as virtual properties or on-demand created properties.
  54866. */
  54867. /* [ ... closure template ] */
  54868. if (DUK_HOBJECT_HAS_STRICT(&fun_clos->obj)) {
  54869. duk_xdef_prop_stridx_thrower(ctx, -2, DUK_STRIDX_CALLER, DUK_PROPDESC_FLAGS_NONE);
  54870. duk_xdef_prop_stridx_thrower(ctx, -2, DUK_STRIDX_LC_ARGUMENTS, DUK_PROPDESC_FLAGS_NONE);
  54871. } else {
  54872. #ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
  54873. DUK_DDD(DUK_DDDPRINT("function is non-strict and non-standard 'caller' property in use, add initial 'null' value"));
  54874. duk_push_null(ctx);
  54875. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_CALLER, DUK_PROPDESC_FLAGS_NONE);
  54876. #else
  54877. DUK_DDD(DUK_DDDPRINT("function is non-strict and non-standard 'caller' property not used"));
  54878. #endif
  54879. }
  54880. /*
  54881. * "name" is a non-standard property found in at least V8, Rhino, smjs.
  54882. * For Rhino and smjs it is non-writable, non-enumerable, and non-configurable;
  54883. * for V8 it is writable, non-enumerable, non-configurable. It is also defined
  54884. * for an anonymous function expression in which case the value is an empty string.
  54885. * We could also leave name 'undefined' for anonymous functions but that would
  54886. * differ from behavior of other engines, so use an empty string.
  54887. *
  54888. * XXX: make optional? costs something per function.
  54889. */
  54890. /* [ ... closure template ] */
  54891. if (duk_get_prop_stridx(ctx, -1, DUK_STRIDX_NAME)) {
  54892. /* [ ... closure template name ] */
  54893. DUK_ASSERT(duk_is_string(ctx, -1));
  54894. } else {
  54895. /* [ ... closure template undefined ] */
  54896. duk_pop(ctx);
  54897. duk_push_hstring_stridx(ctx, DUK_STRIDX_EMPTY_STRING);
  54898. }
  54899. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_NAME, DUK_PROPDESC_FLAGS_NONE); /* -> [ ... closure template ] */
  54900. /*
  54901. * Compact the closure, in most cases no properties will be added later.
  54902. * Also, without this the closures end up having unused property slots
  54903. * (e.g. in Duktape 0.9.0, 8 slots would be allocated and only 7 used).
  54904. * A better future solution would be to allocate the closure directly
  54905. * to correct size (and setup the properties directly without going
  54906. * through the API).
  54907. */
  54908. duk_compact(ctx, -2);
  54909. /*
  54910. * Some assertions (E5 Section 13.2).
  54911. */
  54912. DUK_ASSERT(DUK_HOBJECT_GET_CLASS_NUMBER(&fun_clos->obj) == DUK_HOBJECT_CLASS_FUNCTION);
  54913. DUK_ASSERT(DUK_HOBJECT_GET_PROTOTYPE(thr->heap, &fun_clos->obj) == thr->builtins[DUK_BIDX_FUNCTION_PROTOTYPE]);
  54914. DUK_ASSERT(DUK_HOBJECT_HAS_EXTENSIBLE(&fun_clos->obj));
  54915. DUK_ASSERT(duk_has_prop_stridx(ctx, -2, DUK_STRIDX_LENGTH) != 0);
  54916. DUK_ASSERT(duk_has_prop_stridx(ctx, -2, DUK_STRIDX_PROTOTYPE) != 0);
  54917. DUK_ASSERT(duk_has_prop_stridx(ctx, -2, DUK_STRIDX_NAME) != 0); /* non-standard */
  54918. DUK_ASSERT(!DUK_HOBJECT_HAS_STRICT(&fun_clos->obj) ||
  54919. duk_has_prop_stridx(ctx, -2, DUK_STRIDX_CALLER) != 0);
  54920. DUK_ASSERT(!DUK_HOBJECT_HAS_STRICT(&fun_clos->obj) ||
  54921. duk_has_prop_stridx(ctx, -2, DUK_STRIDX_LC_ARGUMENTS) != 0);
  54922. /*
  54923. * Finish
  54924. */
  54925. /* [ ... closure template ] */
  54926. DUK_DDD(DUK_DDDPRINT("created function instance: template=%!iT -> closure=%!iT",
  54927. (duk_tval *) duk_get_tval(ctx, -1),
  54928. (duk_tval *) duk_get_tval(ctx, -2)));
  54929. duk_pop(ctx);
  54930. /* [ ... closure ] */
  54931. }
  54932. /*
  54933. * Delayed activation environment record initialization (for functions
  54934. * with NEWENV).
  54935. *
  54936. * The non-delayed initialization is handled by duk_handle_call().
  54937. */
  54938. /* shared helper */
  54939. DUK_INTERNAL
  54940. duk_hobject *duk_create_activation_environment_record(duk_hthread *thr,
  54941. duk_hobject *func,
  54942. duk_size_t idx_bottom) {
  54943. duk_context *ctx = (duk_context *) thr;
  54944. duk_hobject *env;
  54945. duk_hobject *parent;
  54946. duk_tval *tv;
  54947. DUK_ASSERT(thr != NULL);
  54948. DUK_ASSERT(func != NULL);
  54949. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_INT_LEXENV(thr));
  54950. if (tv) {
  54951. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  54952. DUK_ASSERT(DUK_HOBJECT_IS_ENV(DUK_TVAL_GET_OBJECT(tv)));
  54953. parent = DUK_TVAL_GET_OBJECT(tv);
  54954. } else {
  54955. parent = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  54956. }
  54957. (void) duk_push_object_helper(ctx,
  54958. DUK_HOBJECT_FLAG_EXTENSIBLE |
  54959. DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_DECENV),
  54960. -1); /* no prototype, updated below */
  54961. env = duk_require_hobject(ctx, -1);
  54962. DUK_ASSERT(env != NULL);
  54963. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, env, parent); /* parent env is the prototype */
  54964. /* open scope information, for compiled functions only */
  54965. if (DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  54966. duk_push_hthread(ctx, thr);
  54967. duk_xdef_prop_stridx_wec(ctx, -2, DUK_STRIDX_INT_THREAD);
  54968. duk_push_hobject(ctx, func);
  54969. duk_xdef_prop_stridx_wec(ctx, -2, DUK_STRIDX_INT_CALLEE);
  54970. duk_push_size_t(ctx, idx_bottom);
  54971. duk_xdef_prop_stridx_wec(ctx, -2, DUK_STRIDX_INT_REGBASE);
  54972. }
  54973. return env;
  54974. }
  54975. DUK_INTERNAL
  54976. void duk_js_init_activation_environment_records_delayed(duk_hthread *thr,
  54977. duk_activation *act) {
  54978. duk_context *ctx = (duk_context *) thr;
  54979. duk_hobject *func;
  54980. duk_hobject *env;
  54981. func = DUK_ACT_GET_FUNC(act);
  54982. DUK_ASSERT(func != NULL);
  54983. DUK_ASSERT(!DUK_HOBJECT_HAS_BOUND(func)); /* bound functions are never in act 'func' */
  54984. /*
  54985. * Delayed initialization only occurs for 'NEWENV' functions.
  54986. */
  54987. DUK_ASSERT(DUK_HOBJECT_HAS_NEWENV(func));
  54988. DUK_ASSERT(act->lex_env == NULL);
  54989. DUK_ASSERT(act->var_env == NULL);
  54990. env = duk_create_activation_environment_record(thr, func, act->idx_bottom);
  54991. DUK_ASSERT(env != NULL);
  54992. DUK_DDD(DUK_DDDPRINT("created delayed fresh env: %!ipO", (duk_heaphdr *) env));
  54993. #ifdef DUK_USE_DDDPRINT
  54994. {
  54995. duk_hobject *p = env;
  54996. while (p) {
  54997. DUK_DDD(DUK_DDDPRINT(" -> %!ipO", (duk_heaphdr *) p));
  54998. p = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, p);
  54999. }
  55000. }
  55001. #endif
  55002. act->lex_env = env;
  55003. act->var_env = env;
  55004. DUK_HOBJECT_INCREF(thr, env); /* XXX: incref by count (here 2 times) */
  55005. DUK_HOBJECT_INCREF(thr, env);
  55006. duk_pop(ctx);
  55007. }
  55008. /*
  55009. * Closing environment records.
  55010. *
  55011. * The environment record MUST be closed with the thread where its activation
  55012. * is. In other words (if 'env' is open):
  55013. *
  55014. * - 'thr' must match _env.thread
  55015. * - 'func' must match _env.callee
  55016. * - 'regbase' must match _env.regbase
  55017. *
  55018. * These are not looked up from the env to minimize code size.
  55019. *
  55020. * XXX: should access the own properties directly instead of using the API
  55021. */
  55022. DUK_INTERNAL void duk_js_close_environment_record(duk_hthread *thr, duk_hobject *env, duk_hobject *func, duk_size_t regbase) {
  55023. duk_context *ctx = (duk_context *) thr;
  55024. duk_uint_fast32_t i;
  55025. DUK_ASSERT(thr != NULL);
  55026. DUK_ASSERT(env != NULL);
  55027. /* func is NULL for lightfuncs */
  55028. if (!DUK_HOBJECT_IS_DECENV(env) || DUK_HOBJECT_HAS_ENVRECCLOSED(env)) {
  55029. DUK_DDD(DUK_DDDPRINT("environment record not a declarative record, "
  55030. "or already closed: %!iO",
  55031. (duk_heaphdr *) env));
  55032. return;
  55033. }
  55034. DUK_DDD(DUK_DDDPRINT("closing environment record: %!iO, func: %!iO, regbase: %ld",
  55035. (duk_heaphdr *) env, (duk_heaphdr *) func, (long) regbase));
  55036. duk_push_hobject(ctx, env);
  55037. /* assertions: env must be closed in the same thread as where it runs */
  55038. #ifdef DUK_USE_ASSERTIONS
  55039. {
  55040. /* [... env] */
  55041. if (duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_CALLEE)) {
  55042. DUK_ASSERT(duk_is_object(ctx, -1));
  55043. DUK_ASSERT(duk_get_hobject(ctx, -1) == (duk_hobject *) func);
  55044. }
  55045. duk_pop(ctx);
  55046. if (duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_THREAD)) {
  55047. DUK_ASSERT(duk_is_object(ctx, -1));
  55048. DUK_ASSERT(duk_get_hobject(ctx, -1) == (duk_hobject *) thr);
  55049. }
  55050. duk_pop(ctx);
  55051. if (duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_REGBASE)) {
  55052. DUK_ASSERT(duk_is_number(ctx, -1));
  55053. DUK_ASSERT(duk_get_number(ctx, -1) == (double) regbase);
  55054. }
  55055. duk_pop(ctx);
  55056. /* [... env] */
  55057. }
  55058. #endif
  55059. if (func != NULL && DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  55060. duk_hobject *varmap;
  55061. duk_hstring *key;
  55062. duk_tval *tv;
  55063. duk_uint_t regnum;
  55064. /* XXX: additional conditions when to close variables? we don't want to do it
  55065. * unless the environment may have "escaped" (referenced in a function closure).
  55066. * With delayed environments, the existence is probably good enough of a check.
  55067. */
  55068. /* XXX: any way to detect faster whether something needs to be closed?
  55069. * We now look up _Callee and then skip the rest.
  55070. */
  55071. /* Note: we rely on the _Varmap having a bunch of nice properties, like:
  55072. * - being compacted and unmodified during this process
  55073. * - not containing an array part
  55074. * - having correct value types
  55075. */
  55076. /* [... env] */
  55077. if (!duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_CALLEE)) {
  55078. DUK_DDD(DUK_DDDPRINT("env has no callee property, nothing to close; re-delete the control properties just in case"));
  55079. duk_pop(ctx);
  55080. goto skip_varmap;
  55081. }
  55082. /* [... env callee] */
  55083. if (!duk_get_prop_stridx(ctx, -1, DUK_STRIDX_INT_VARMAP)) {
  55084. DUK_DDD(DUK_DDDPRINT("callee has no varmap property, nothing to close; delete the control properties"));
  55085. duk_pop_2(ctx);
  55086. goto skip_varmap;
  55087. }
  55088. varmap = duk_require_hobject(ctx, -1);
  55089. DUK_ASSERT(varmap != NULL);
  55090. DUK_DDD(DUK_DDDPRINT("varmap: %!O", (duk_heaphdr *) varmap));
  55091. /* [... env callee varmap] */
  55092. DUK_DDD(DUK_DDDPRINT("copying bound register values, %ld bound regs", (long) DUK_HOBJECT_GET_ENEXT(varmap)));
  55093. for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(varmap); i++) {
  55094. key = DUK_HOBJECT_E_GET_KEY(thr->heap, varmap, i);
  55095. DUK_ASSERT(key != NULL); /* assume keys are compacted */
  55096. DUK_ASSERT(!DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, varmap, i)); /* assume plain values */
  55097. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, varmap, i);
  55098. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv)); /* assume value is a number */
  55099. regnum = (duk_uint_t) DUK_TVAL_GET_NUMBER(tv);
  55100. DUK_ASSERT_DISABLE(regnum >= 0); /* unsigned */
  55101. DUK_ASSERT(regnum < ((duk_hcompiledfunction *) func)->nregs); /* regnum is sane */
  55102. DUK_ASSERT(thr->valstack + regbase + regnum >= thr->valstack);
  55103. DUK_ASSERT(thr->valstack + regbase + regnum < thr->valstack_top);
  55104. /* XXX: slightly awkward */
  55105. duk_push_hstring(ctx, key);
  55106. duk_push_tval(ctx, thr->valstack + regbase + regnum);
  55107. DUK_DDD(DUK_DDDPRINT("closing identifier '%s' -> reg %ld, value %!T",
  55108. (const char *) duk_require_string(ctx, -2),
  55109. (long) regnum,
  55110. (duk_tval *) duk_get_tval(ctx, -1)));
  55111. /* [... env callee varmap key val] */
  55112. /* if property already exists, overwrites silently */
  55113. duk_xdef_prop(ctx, -5, DUK_PROPDESC_FLAGS_WE); /* writable but not deletable */
  55114. }
  55115. duk_pop_2(ctx);
  55116. /* [... env] */
  55117. }
  55118. skip_varmap:
  55119. /* [... env] */
  55120. duk_del_prop_stridx(ctx, -1, DUK_STRIDX_INT_CALLEE);
  55121. duk_del_prop_stridx(ctx, -1, DUK_STRIDX_INT_THREAD);
  55122. duk_del_prop_stridx(ctx, -1, DUK_STRIDX_INT_REGBASE);
  55123. duk_pop(ctx);
  55124. DUK_HOBJECT_SET_ENVRECCLOSED(env);
  55125. DUK_DDD(DUK_DDDPRINT("environment record after being closed: %!O",
  55126. (duk_heaphdr *) env));
  55127. }
  55128. /*
  55129. * GETIDREF: a GetIdentifierReference-like helper.
  55130. *
  55131. * Provides a parent traversing lookup and a single level lookup
  55132. * (for HasBinding).
  55133. *
  55134. * Instead of returning the value, returns a bunch of values allowing
  55135. * the caller to read, write, or delete the binding. Value pointers
  55136. * are duk_tval pointers which can be mutated directly as long as
  55137. * refcounts are properly updated. Note that any operation which may
  55138. * reallocate valstacks or compact objects may invalidate the returned
  55139. * duk_tval (but not object) pointers, so caller must be very careful.
  55140. *
  55141. * If starting environment record 'env' is given, 'act' is ignored.
  55142. * However, if 'env' is NULL, the caller may identify, in 'act', an
  55143. * activation which hasn't had its declarative environment initialized
  55144. * yet. The activation registers are then looked up, and its parent
  55145. * traversed normally.
  55146. *
  55147. * The 'out' structure values are only valid if the function returns
  55148. * success (non-zero).
  55149. */
  55150. /* lookup name from an open declarative record's registers */
  55151. DUK_LOCAL
  55152. duk_bool_t duk__getid_open_decl_env_regs(duk_hthread *thr,
  55153. duk_hstring *name,
  55154. duk_hobject *env,
  55155. duk__id_lookup_result *out) {
  55156. duk_hthread *env_thr;
  55157. duk_hobject *env_func;
  55158. duk_size_t env_regbase;
  55159. duk_hobject *varmap;
  55160. duk_tval *tv;
  55161. duk_size_t reg_rel;
  55162. duk_size_t idx;
  55163. DUK_ASSERT(thr != NULL);
  55164. DUK_ASSERT(name != NULL);
  55165. DUK_ASSERT(env != NULL);
  55166. DUK_ASSERT(out != NULL);
  55167. DUK_ASSERT(DUK_HOBJECT_IS_DECENV(env));
  55168. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_CALLEE(thr));
  55169. if (!tv) {
  55170. /* env is closed, should be missing _Callee, _Thread, _Regbase */
  55171. DUK_ASSERT(duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_CALLEE(thr)) == NULL);
  55172. DUK_ASSERT(duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_THREAD(thr)) == NULL);
  55173. DUK_ASSERT(duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_REGBASE(thr)) == NULL);
  55174. return 0;
  55175. }
  55176. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  55177. DUK_ASSERT(DUK_TVAL_GET_OBJECT(tv) != NULL);
  55178. DUK_ASSERT(DUK_HOBJECT_IS_COMPILEDFUNCTION(DUK_TVAL_GET_OBJECT(tv)));
  55179. env_func = DUK_TVAL_GET_OBJECT(tv);
  55180. DUK_ASSERT(env_func != NULL);
  55181. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, env_func, DUK_HTHREAD_STRING_INT_VARMAP(thr));
  55182. if (!tv) {
  55183. return 0;
  55184. }
  55185. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  55186. varmap = DUK_TVAL_GET_OBJECT(tv);
  55187. DUK_ASSERT(varmap != NULL);
  55188. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, varmap, name);
  55189. if (!tv) {
  55190. return 0;
  55191. }
  55192. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  55193. reg_rel = (duk_size_t) DUK_TVAL_GET_NUMBER(tv);
  55194. DUK_ASSERT_DISABLE(reg_rel >= 0); /* unsigned */
  55195. DUK_ASSERT(reg_rel < ((duk_hcompiledfunction *) env_func)->nregs);
  55196. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_THREAD(thr));
  55197. DUK_ASSERT(tv != NULL);
  55198. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  55199. DUK_ASSERT(DUK_TVAL_GET_OBJECT(tv) != NULL);
  55200. DUK_ASSERT(DUK_HOBJECT_IS_THREAD(DUK_TVAL_GET_OBJECT(tv)));
  55201. env_thr = (duk_hthread *) DUK_TVAL_GET_OBJECT(tv);
  55202. DUK_ASSERT(env_thr != NULL);
  55203. /* Note: env_thr != thr is quite possible and normal, so careful
  55204. * with what thread is used for valstack lookup.
  55205. */
  55206. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_REGBASE(thr));
  55207. DUK_ASSERT(tv != NULL);
  55208. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  55209. env_regbase = (duk_size_t) DUK_TVAL_GET_NUMBER(tv);
  55210. idx = env_regbase + reg_rel;
  55211. tv = env_thr->valstack + idx;
  55212. DUK_ASSERT(tv >= env_thr->valstack && tv < env_thr->valstack_end); /* XXX: more accurate? */
  55213. out->value = tv;
  55214. out->attrs = DUK_PROPDESC_FLAGS_W; /* registers are mutable, non-deletable */
  55215. out->this_binding = NULL; /* implicit this value always undefined for
  55216. * declarative environment records.
  55217. */
  55218. out->env = env;
  55219. out->holder = NULL;
  55220. return 1;
  55221. }
  55222. /* lookup name from current activation record's functions' registers */
  55223. DUK_LOCAL
  55224. duk_bool_t duk__getid_activation_regs(duk_hthread *thr,
  55225. duk_hstring *name,
  55226. duk_activation *act,
  55227. duk__id_lookup_result *out) {
  55228. duk_tval *tv;
  55229. duk_hobject *func;
  55230. duk_hobject *varmap;
  55231. duk_size_t reg_rel;
  55232. duk_size_t idx;
  55233. DUK_ASSERT(thr != NULL);
  55234. DUK_ASSERT(name != NULL);
  55235. DUK_ASSERT(act != NULL);
  55236. DUK_ASSERT(out != NULL);
  55237. func = DUK_ACT_GET_FUNC(act);
  55238. DUK_ASSERT(func != NULL);
  55239. DUK_ASSERT(DUK_HOBJECT_HAS_NEWENV(func));
  55240. if (!DUK_HOBJECT_IS_COMPILEDFUNCTION(func)) {
  55241. return 0;
  55242. }
  55243. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_INT_VARMAP(thr));
  55244. if (!tv) {
  55245. return 0;
  55246. }
  55247. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  55248. varmap = DUK_TVAL_GET_OBJECT(tv);
  55249. DUK_ASSERT(varmap != NULL);
  55250. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, varmap, name);
  55251. if (!tv) {
  55252. return 0;
  55253. }
  55254. DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
  55255. reg_rel = (duk_size_t) DUK_TVAL_GET_NUMBER(tv);
  55256. DUK_ASSERT_DISABLE(reg_rel >= 0);
  55257. DUK_ASSERT(reg_rel < ((duk_hcompiledfunction *) func)->nregs);
  55258. idx = act->idx_bottom + reg_rel;
  55259. DUK_ASSERT(idx >= act->idx_bottom);
  55260. tv = thr->valstack + idx;
  55261. out->value = tv;
  55262. out->attrs = DUK_PROPDESC_FLAGS_W; /* registers are mutable, non-deletable */
  55263. out->this_binding = NULL; /* implicit this value always undefined for
  55264. * declarative environment records.
  55265. */
  55266. out->env = NULL;
  55267. out->holder = NULL;
  55268. return 1;
  55269. }
  55270. DUK_LOCAL
  55271. duk_bool_t duk__get_identifier_reference(duk_hthread *thr,
  55272. duk_hobject *env,
  55273. duk_hstring *name,
  55274. duk_activation *act,
  55275. duk_bool_t parents,
  55276. duk__id_lookup_result *out) {
  55277. duk_tval *tv;
  55278. duk_uint_t sanity;
  55279. DUK_ASSERT(thr != NULL);
  55280. DUK_ASSERT(env != NULL || act != NULL);
  55281. DUK_ASSERT(name != NULL);
  55282. DUK_ASSERT(out != NULL);
  55283. DUK_ASSERT(!env || DUK_HOBJECT_IS_ENV(env));
  55284. DUK_ASSERT(!env || !DUK_HOBJECT_HAS_ARRAY_PART(env));
  55285. /*
  55286. * Conceptually, we look for the identifier binding by starting from
  55287. * 'env' and following to chain of environment records (represented
  55288. * by the prototype chain).
  55289. *
  55290. * If 'env' is NULL, the current activation does not yet have an
  55291. * allocated declarative environment record; this should be treated
  55292. * exactly as if the environment record existed but had no bindings
  55293. * other than register bindings.
  55294. *
  55295. * Note: we assume that with the DUK_HOBJECT_FLAG_NEWENV cleared
  55296. * the environment will always be initialized immediately; hence
  55297. * a NULL 'env' should only happen with the flag set. This is the
  55298. * case for: (1) function calls, and (2) strict, direct eval calls.
  55299. */
  55300. if (env == NULL && act != NULL) {
  55301. duk_hobject *func;
  55302. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference: env is NULL, activation is non-NULL -> "
  55303. "delayed env case, look up activation regs first"));
  55304. /*
  55305. * Try registers
  55306. */
  55307. if (duk__getid_activation_regs(thr, name, act, out)) {
  55308. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference successful: "
  55309. "name=%!O -> value=%!T, attrs=%ld, this=%!T, env=%!O, holder=%!O "
  55310. "(found from register bindings when env=NULL)",
  55311. (duk_heaphdr *) name, (duk_tval *) out->value,
  55312. (long) out->attrs, (duk_tval *) out->this_binding,
  55313. (duk_heaphdr *) out->env, (duk_heaphdr *) out->holder));
  55314. return 1;
  55315. }
  55316. DUK_DDD(DUK_DDDPRINT("not found in current activation regs"));
  55317. /*
  55318. * Not found in registers, proceed to the parent record.
  55319. * Here we need to determine what the parent would be,
  55320. * if 'env' was not NULL (i.e. same logic as when initializing
  55321. * the record).
  55322. *
  55323. * Note that environment initialization is only deferred when
  55324. * DUK_HOBJECT_HAS_NEWENV is set, and this only happens for:
  55325. * - Function code
  55326. * - Strict eval code
  55327. *
  55328. * We only need to check _Lexenv here; _Varenv exists only if it
  55329. * differs from _Lexenv (and thus _Lexenv will also be present).
  55330. */
  55331. if (!parents) {
  55332. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference failed, no parent traversal "
  55333. "(not found from register bindings when env=NULL)"));
  55334. goto fail_not_found;
  55335. }
  55336. func = DUK_ACT_GET_FUNC(act);
  55337. DUK_ASSERT(func != NULL);
  55338. DUK_ASSERT(DUK_HOBJECT_HAS_NEWENV(func));
  55339. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_INT_LEXENV(thr));
  55340. if (tv) {
  55341. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  55342. env = DUK_TVAL_GET_OBJECT(tv);
  55343. } else {
  55344. DUK_ASSERT(duk_hobject_find_existing_entry_tval_ptr(thr->heap, func, DUK_HTHREAD_STRING_INT_VARENV(thr)) == NULL);
  55345. env = thr->builtins[DUK_BIDX_GLOBAL_ENV];
  55346. }
  55347. DUK_DDD(DUK_DDDPRINT("continue lookup from env: %!iO",
  55348. (duk_heaphdr *) env));
  55349. }
  55350. /*
  55351. * Prototype walking starting from 'env'.
  55352. *
  55353. * ('act' is not needed anywhere here.)
  55354. */
  55355. sanity = DUK_HOBJECT_PROTOTYPE_CHAIN_SANITY;
  55356. while (env != NULL) {
  55357. duk_small_int_t cl;
  55358. duk_int_t attrs;
  55359. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference, name=%!O, considering env=%p -> %!iO",
  55360. (duk_heaphdr *) name,
  55361. (void *) env,
  55362. (duk_heaphdr *) env));
  55363. DUK_ASSERT(env != NULL);
  55364. DUK_ASSERT(DUK_HOBJECT_IS_ENV(env));
  55365. DUK_ASSERT(!DUK_HOBJECT_HAS_ARRAY_PART(env));
  55366. cl = DUK_HOBJECT_GET_CLASS_NUMBER(env);
  55367. DUK_ASSERT(cl == DUK_HOBJECT_CLASS_OBJENV || cl == DUK_HOBJECT_CLASS_DECENV);
  55368. if (cl == DUK_HOBJECT_CLASS_DECENV) {
  55369. /*
  55370. * Declarative environment record.
  55371. *
  55372. * Identifiers can never be stored in ancestors and are
  55373. * always plain values, so we can use an internal helper
  55374. * and access the value directly with an duk_tval ptr.
  55375. *
  55376. * A closed environment is only indicated by it missing
  55377. * the "book-keeping" properties required for accessing
  55378. * register-bound variables.
  55379. */
  55380. if (DUK_HOBJECT_HAS_ENVRECCLOSED(env)) {
  55381. /* already closed */
  55382. goto skip_regs;
  55383. }
  55384. if (duk__getid_open_decl_env_regs(thr, name, env, out)) {
  55385. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference successful: "
  55386. "name=%!O -> value=%!T, attrs=%ld, this=%!T, env=%!O, holder=%!O "
  55387. "(declarative environment record, scope open, found in regs)",
  55388. (duk_heaphdr *) name, (duk_tval *) out->value,
  55389. (long) out->attrs, (duk_tval *) out->this_binding,
  55390. (duk_heaphdr *) out->env, (duk_heaphdr *) out->holder));
  55391. return 1;
  55392. }
  55393. skip_regs:
  55394. tv = duk_hobject_find_existing_entry_tval_ptr_and_attrs(thr->heap, env, name, &attrs);
  55395. if (tv) {
  55396. out->value = tv;
  55397. out->attrs = attrs;
  55398. out->this_binding = NULL; /* implicit this value always undefined for
  55399. * declarative environment records.
  55400. */
  55401. out->env = env;
  55402. out->holder = env;
  55403. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference successful: "
  55404. "name=%!O -> value=%!T, attrs=%ld, this=%!T, env=%!O, holder=%!O "
  55405. "(declarative environment record, found in properties)",
  55406. (duk_heaphdr *) name, (duk_tval *) out->value,
  55407. (long) out->attrs, (duk_tval *) out->this_binding,
  55408. (duk_heaphdr *) out->env, (duk_heaphdr *) out->holder));
  55409. return 1;
  55410. }
  55411. } else {
  55412. /*
  55413. * Object environment record.
  55414. *
  55415. * Binding (target) object is an external, uncontrolled object.
  55416. * Identifier may be bound in an ancestor property, and may be
  55417. * an accessor.
  55418. */
  55419. /* XXX: we could save space by using _Target OR _This. If _Target, assume
  55420. * this binding is undefined. If _This, assumes this binding is _This, and
  55421. * target is also _This. One property would then be enough.
  55422. */
  55423. duk_hobject *target;
  55424. DUK_ASSERT(cl == DUK_HOBJECT_CLASS_OBJENV);
  55425. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_TARGET(thr));
  55426. DUK_ASSERT(tv != NULL);
  55427. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  55428. target = DUK_TVAL_GET_OBJECT(tv);
  55429. DUK_ASSERT(target != NULL);
  55430. /* Note: we must traverse the prototype chain, so use an actual
  55431. * hasprop call here. The property may also be an accessor, so
  55432. * we can't get an duk_tval pointer here.
  55433. *
  55434. * out->holder is NOT set to the actual duk_hobject where the
  55435. * property is found, but rather the target object.
  55436. */
  55437. if (duk_hobject_hasprop_raw(thr, target, name)) {
  55438. out->value = NULL; /* can't get value, may be accessor */
  55439. out->attrs = 0; /* irrelevant when out->value == NULL */
  55440. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_THIS(thr));
  55441. out->this_binding = tv; /* may be NULL */
  55442. out->env = env;
  55443. out->holder = target;
  55444. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference successful: "
  55445. "name=%!O -> value=%!T, attrs=%ld, this=%!T, env=%!O, holder=%!O "
  55446. "(object environment record)",
  55447. (duk_heaphdr *) name, (duk_tval *) out->value,
  55448. (long) out->attrs, (duk_tval *) out->this_binding,
  55449. (duk_heaphdr *) out->env, (duk_heaphdr *) out->holder));
  55450. return 1;
  55451. }
  55452. }
  55453. if (!parents) {
  55454. DUK_DDD(DUK_DDDPRINT("duk__get_identifier_reference failed, no parent traversal "
  55455. "(not found from first traversed env)"));
  55456. goto fail_not_found;
  55457. }
  55458. if (sanity-- == 0) {
  55459. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_PROTOTYPE_CHAIN_LIMIT);
  55460. }
  55461. env = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, env);
  55462. };
  55463. /*
  55464. * Not found (even in global object)
  55465. */
  55466. fail_not_found:
  55467. return 0;
  55468. }
  55469. /*
  55470. * HASVAR: check identifier binding from a given environment record
  55471. * without traversing its parents.
  55472. *
  55473. * This primitive is not exposed to user code as such, but is used
  55474. * internally for e.g. declaration binding instantiation.
  55475. *
  55476. * See E5 Sections:
  55477. * 10.2.1.1.1 HasBinding(N)
  55478. * 10.2.1.2.1 HasBinding(N)
  55479. *
  55480. * Note: strictness has no bearing on this check. Hence we don't take
  55481. * a 'strict' parameter.
  55482. */
  55483. #if 0 /*unused*/
  55484. DUK_INTERNAL
  55485. duk_bool_t duk_js_hasvar_envrec(duk_hthread *thr,
  55486. duk_hobject *env,
  55487. duk_hstring *name) {
  55488. duk__id_lookup_result ref;
  55489. duk_bool_t parents;
  55490. DUK_DDD(DUK_DDDPRINT("hasvar: thr=%p, env=%p, name=%!O "
  55491. "(env -> %!dO)",
  55492. (void *) thr, (void *) env, (duk_heaphdr *) name,
  55493. (duk_heaphdr *) env));
  55494. DUK_ASSERT(thr != NULL);
  55495. DUK_ASSERT(env != NULL);
  55496. DUK_ASSERT(name != NULL);
  55497. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(env);
  55498. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(name);
  55499. DUK_ASSERT(DUK_HOBJECT_IS_ENV(env));
  55500. DUK_ASSERT(!DUK_HOBJECT_HAS_ARRAY_PART(env));
  55501. /* lookup results is ignored */
  55502. parents = 0;
  55503. return duk__get_identifier_reference(thr, env, name, NULL, parents, &ref);
  55504. }
  55505. #endif
  55506. /*
  55507. * GETVAR
  55508. *
  55509. * See E5 Sections:
  55510. * 11.1.2 Identifier Reference
  55511. * 10.3.1 Identifier Resolution
  55512. * 11.13.1 Simple Assignment [example of where the Reference is GetValue'd]
  55513. * 8.7.1 GetValue (V)
  55514. * 8.12.1 [[GetOwnProperty]] (P)
  55515. * 8.12.2 [[GetProperty]] (P)
  55516. * 8.12.3 [[Get]] (P)
  55517. *
  55518. * If 'throw' is true, always leaves two values on top of stack: [val this].
  55519. *
  55520. * If 'throw' is false, returns 0 if identifier cannot be resolved, and the
  55521. * stack will be unaffected in this case. If identifier is resolved, returns
  55522. * 1 and leaves [val this] on top of stack.
  55523. *
  55524. * Note: the 'strict' flag of a reference returned by GetIdentifierReference
  55525. * is ignored by GetValue. Hence we don't take a 'strict' parameter.
  55526. *
  55527. * The 'throw' flag is needed for implementing 'typeof' for an unreferenced
  55528. * identifier. An unreference identifier in other contexts generates a
  55529. * ReferenceError.
  55530. */
  55531. DUK_LOCAL
  55532. duk_bool_t duk__getvar_helper(duk_hthread *thr,
  55533. duk_hobject *env,
  55534. duk_activation *act,
  55535. duk_hstring *name,
  55536. duk_bool_t throw_flag) {
  55537. duk_context *ctx = (duk_context *) thr;
  55538. duk__id_lookup_result ref;
  55539. duk_tval tv_tmp_obj;
  55540. duk_tval tv_tmp_key;
  55541. duk_bool_t parents;
  55542. DUK_DDD(DUK_DDDPRINT("getvar: thr=%p, env=%p, act=%p, name=%!O "
  55543. "(env -> %!dO)",
  55544. (void *) thr, (void *) env, (void *) act,
  55545. (duk_heaphdr *) name, (duk_heaphdr *) env));
  55546. DUK_ASSERT(thr != NULL);
  55547. DUK_ASSERT(name != NULL);
  55548. /* env and act may be NULL */
  55549. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(env);
  55550. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(name);
  55551. parents = 1; /* follow parent chain */
  55552. if (duk__get_identifier_reference(thr, env, name, act, parents, &ref)) {
  55553. if (ref.value) {
  55554. DUK_ASSERT(ref.this_binding == NULL); /* always for register bindings */
  55555. duk_push_tval(ctx, ref.value);
  55556. duk_push_undefined(ctx);
  55557. } else {
  55558. DUK_ASSERT(ref.holder != NULL);
  55559. /* Note: getprop may invoke any getter and invalidate any
  55560. * duk_tval pointers, so this must be done first.
  55561. */
  55562. if (ref.this_binding) {
  55563. duk_push_tval(ctx, ref.this_binding);
  55564. } else {
  55565. duk_push_undefined(ctx);
  55566. }
  55567. DUK_TVAL_SET_OBJECT(&tv_tmp_obj, ref.holder);
  55568. DUK_TVAL_SET_STRING(&tv_tmp_key, name);
  55569. (void) duk_hobject_getprop(thr, &tv_tmp_obj, &tv_tmp_key); /* [this value] */
  55570. /* ref.value, ref.this.binding invalidated here by getprop call */
  55571. duk_insert(ctx, -2); /* [this value] -> [value this] */
  55572. }
  55573. return 1;
  55574. } else {
  55575. if (throw_flag) {
  55576. DUK_ERROR(thr, DUK_ERR_REFERENCE_ERROR,
  55577. "identifier '%s' undefined",
  55578. (const char *) DUK_HSTRING_GET_DATA(name));
  55579. }
  55580. return 0;
  55581. }
  55582. }
  55583. DUK_INTERNAL
  55584. duk_bool_t duk_js_getvar_envrec(duk_hthread *thr,
  55585. duk_hobject *env,
  55586. duk_hstring *name,
  55587. duk_bool_t throw_flag) {
  55588. return duk__getvar_helper(thr, env, NULL, name, throw_flag);
  55589. }
  55590. DUK_INTERNAL
  55591. duk_bool_t duk_js_getvar_activation(duk_hthread *thr,
  55592. duk_activation *act,
  55593. duk_hstring *name,
  55594. duk_bool_t throw_flag) {
  55595. DUK_ASSERT(act != NULL);
  55596. return duk__getvar_helper(thr, act->lex_env, act, name, throw_flag);
  55597. }
  55598. /*
  55599. * PUTVAR
  55600. *
  55601. * See E5 Sections:
  55602. * 11.1.2 Identifier Reference
  55603. * 10.3.1 Identifier Resolution
  55604. * 11.13.1 Simple Assignment [example of where the Reference is PutValue'd]
  55605. * 8.7.2 PutValue (V,W) [see especially step 3.b, undefined -> automatic global in non-strict mode]
  55606. * 8.12.4 [[CanPut]] (P)
  55607. * 8.12.5 [[Put]] (P)
  55608. *
  55609. * Note: may invalidate any valstack (or object) duk_tval pointers because
  55610. * putting a value may reallocate any object or any valstack. Caller beware.
  55611. */
  55612. DUK_LOCAL
  55613. void duk__putvar_helper(duk_hthread *thr,
  55614. duk_hobject *env,
  55615. duk_activation *act,
  55616. duk_hstring *name,
  55617. duk_tval *val,
  55618. duk_bool_t strict) {
  55619. duk__id_lookup_result ref;
  55620. duk_tval tv_tmp_obj;
  55621. duk_tval tv_tmp_key;
  55622. duk_bool_t parents;
  55623. DUK_DDD(DUK_DDDPRINT("putvar: thr=%p, env=%p, act=%p, name=%!O, val=%p, strict=%ld "
  55624. "(env -> %!dO, val -> %!T)",
  55625. (void *) thr, (void *) env, (void *) act,
  55626. (duk_heaphdr *) name, (void *) val, (long) strict,
  55627. (duk_heaphdr *) env, (duk_tval *) val));
  55628. DUK_ASSERT(thr != NULL);
  55629. DUK_ASSERT(name != NULL);
  55630. DUK_ASSERT(val != NULL);
  55631. /* env and act may be NULL */
  55632. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(env);
  55633. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(name);
  55634. DUK_ASSERT_REFCOUNT_NONZERO_TVAL(val);
  55635. /*
  55636. * In strict mode E5 protects 'eval' and 'arguments' from being
  55637. * assigned to (or even declared anywhere). Attempt to do so
  55638. * should result in a compile time SyntaxError. See the internal
  55639. * design documentation for details.
  55640. *
  55641. * Thus, we should never come here, run-time, for strict code,
  55642. * and name 'eval' or 'arguments'.
  55643. */
  55644. DUK_ASSERT(!strict ||
  55645. (name != DUK_HTHREAD_STRING_EVAL(thr) &&
  55646. name != DUK_HTHREAD_STRING_LC_ARGUMENTS(thr)));
  55647. /*
  55648. * Lookup variable and update in-place if found.
  55649. */
  55650. parents = 1; /* follow parent chain */
  55651. if (duk__get_identifier_reference(thr, env, name, act, parents, &ref)) {
  55652. if (ref.value && (ref.attrs & DUK_PROPDESC_FLAG_WRITABLE)) {
  55653. /* Update duk_tval in-place if pointer provided and the
  55654. * property is writable. If the property is not writable
  55655. * (immutable binding), use duk_hobject_putprop() which
  55656. * will respect mutability.
  55657. */
  55658. duk_tval tv_tmp;
  55659. duk_tval *tv_val;
  55660. DUK_ASSERT(ref.this_binding == NULL); /* always for register bindings */
  55661. tv_val = ref.value;
  55662. DUK_ASSERT(tv_val != NULL);
  55663. DUK_TVAL_SET_TVAL(&tv_tmp, tv_val);
  55664. DUK_TVAL_SET_TVAL(tv_val, val);
  55665. DUK_TVAL_INCREF(thr, val);
  55666. DUK_TVAL_DECREF(thr, &tv_tmp); /* must be last */
  55667. /* ref.value and ref.this_binding invalidated here */
  55668. } else {
  55669. DUK_ASSERT(ref.holder != NULL);
  55670. DUK_TVAL_SET_OBJECT(&tv_tmp_obj, ref.holder);
  55671. DUK_TVAL_SET_STRING(&tv_tmp_key, name);
  55672. (void) duk_hobject_putprop(thr, &tv_tmp_obj, &tv_tmp_key, val, strict);
  55673. /* ref.value and ref.this_binding invalidated here */
  55674. }
  55675. return;
  55676. }
  55677. /*
  55678. * Not found: write to global object (non-strict) or ReferenceError
  55679. * (strict); see E5 Section 8.7.2, step 3.
  55680. */
  55681. if (strict) {
  55682. DUK_DDD(DUK_DDDPRINT("identifier binding not found, strict => reference error"));
  55683. DUK_ERROR(thr, DUK_ERR_REFERENCE_ERROR, "identifier not defined");
  55684. }
  55685. DUK_DDD(DUK_DDDPRINT("identifier binding not found, not strict => set to global"));
  55686. DUK_TVAL_SET_OBJECT(&tv_tmp_obj, thr->builtins[DUK_BIDX_GLOBAL]);
  55687. DUK_TVAL_SET_STRING(&tv_tmp_key, name);
  55688. (void) duk_hobject_putprop(thr, &tv_tmp_obj, &tv_tmp_key, val, 0); /* 0 = no throw */
  55689. /* NB: 'val' may be invalidated here because put_value may realloc valstack,
  55690. * caller beware.
  55691. */
  55692. }
  55693. DUK_INTERNAL
  55694. void duk_js_putvar_envrec(duk_hthread *thr,
  55695. duk_hobject *env,
  55696. duk_hstring *name,
  55697. duk_tval *val,
  55698. duk_bool_t strict) {
  55699. duk__putvar_helper(thr, env, NULL, name, val, strict);
  55700. }
  55701. DUK_INTERNAL
  55702. void duk_js_putvar_activation(duk_hthread *thr,
  55703. duk_activation *act,
  55704. duk_hstring *name,
  55705. duk_tval *val,
  55706. duk_bool_t strict) {
  55707. DUK_ASSERT(act != NULL);
  55708. duk__putvar_helper(thr, act->lex_env, act, name, val, strict);
  55709. }
  55710. /*
  55711. * DELVAR
  55712. *
  55713. * See E5 Sections:
  55714. * 11.4.1 The delete operator
  55715. * 10.2.1.1.5 DeleteBinding (N) [declarative environment record]
  55716. * 10.2.1.2.5 DeleteBinding (N) [object environment record]
  55717. *
  55718. * Variable bindings established inside eval() are deletable (configurable),
  55719. * other bindings are not, including variables declared in global level.
  55720. * Registers are always non-deletable, and the deletion of other bindings
  55721. * is controlled by the configurable flag.
  55722. *
  55723. * For strict mode code, the 'delete' operator should fail with a compile
  55724. * time SyntaxError if applied to identifiers. Hence, no strict mode
  55725. * run-time deletion of identifiers should ever happen. This function
  55726. * should never be called from strict mode code!
  55727. */
  55728. DUK_LOCAL
  55729. duk_bool_t duk__delvar_helper(duk_hthread *thr,
  55730. duk_hobject *env,
  55731. duk_activation *act,
  55732. duk_hstring *name) {
  55733. duk__id_lookup_result ref;
  55734. duk_bool_t parents;
  55735. DUK_DDD(DUK_DDDPRINT("delvar: thr=%p, env=%p, act=%p, name=%!O "
  55736. "(env -> %!dO)",
  55737. (void *) thr, (void *) env, (void *) act,
  55738. (duk_heaphdr *) name, (duk_heaphdr *) env));
  55739. DUK_ASSERT(thr != NULL);
  55740. DUK_ASSERT(name != NULL);
  55741. /* env and act may be NULL */
  55742. DUK_ASSERT_REFCOUNT_NONZERO_HEAPHDR(name);
  55743. parents = 1; /* follow parent chain */
  55744. if (duk__get_identifier_reference(thr, env, name, act, parents, &ref)) {
  55745. if (ref.value && !(ref.attrs & DUK_PROPDESC_FLAG_CONFIGURABLE)) {
  55746. /* Identifier found in registers (always non-deletable)
  55747. * or declarative environment record and non-configurable.
  55748. */
  55749. return 0;
  55750. }
  55751. DUK_ASSERT(ref.holder != NULL);
  55752. return duk_hobject_delprop_raw(thr, ref.holder, name, 0);
  55753. }
  55754. /*
  55755. * Not found (even in global object).
  55756. *
  55757. * In non-strict mode this is a silent SUCCESS (!), see E5 Section 11.4.1,
  55758. * step 3.b. In strict mode this case is a compile time SyntaxError so
  55759. * we should not come here.
  55760. */
  55761. DUK_DDD(DUK_DDDPRINT("identifier to be deleted not found: name=%!O "
  55762. "(treated as silent success)",
  55763. (duk_heaphdr *) name));
  55764. return 1;
  55765. }
  55766. #if 0 /*unused*/
  55767. DUK_INTERNAL
  55768. duk_bool_t duk_js_delvar_envrec(duk_hthread *thr,
  55769. duk_hobject *env,
  55770. duk_hstring *name) {
  55771. return duk__delvar_helper(thr, env, NULL, name);
  55772. }
  55773. #endif
  55774. DUK_INTERNAL
  55775. duk_bool_t duk_js_delvar_activation(duk_hthread *thr,
  55776. duk_activation *act,
  55777. duk_hstring *name) {
  55778. DUK_ASSERT(act != NULL);
  55779. return duk__delvar_helper(thr, act->lex_env, act, name);
  55780. }
  55781. /*
  55782. * DECLVAR
  55783. *
  55784. * See E5 Sections:
  55785. * 10.4.3 Entering Function Code
  55786. * 10.5 Declaration Binding Instantion
  55787. * 12.2 Variable Statement
  55788. * 11.1.2 Identifier Reference
  55789. * 10.3.1 Identifier Resolution
  55790. *
  55791. * Variable declaration behavior is mainly discussed in Section 10.5,
  55792. * and is not discussed in the execution semantics (Sections 11-13).
  55793. *
  55794. * Conceptually declarations happen when code (global, eval, function)
  55795. * is entered, before any user code is executed. In practice, register-
  55796. * bound identifiers are 'declared' automatically (by virtue of being
  55797. * allocated to registers with the initial value 'undefined'). Other
  55798. * identifiers are declared in the function prologue with this primitive.
  55799. *
  55800. * Since non-register bindings eventually back to an internal object's
  55801. * properties, the 'prop_flags' argument is used to specify binding
  55802. * type:
  55803. *
  55804. * - Immutable binding: set DUK_PROPDESC_FLAG_WRITABLE to false
  55805. * - Non-deletable binding: set DUK_PROPDESC_FLAG_CONFIGURABLE to false
  55806. * - The flag DUK_PROPDESC_FLAG_ENUMERABLE should be set, although it
  55807. * doesn't really matter for internal objects
  55808. *
  55809. * All bindings are non-deletable mutable bindings except:
  55810. *
  55811. * - Declarations in eval code (mutable, deletable)
  55812. * - 'arguments' binding in strict function code (immutable)
  55813. * - Function name binding of a function expression (immutable)
  55814. *
  55815. * Declarations may go to declarative environment records (always
  55816. * so for functions), but may also go to object environment records
  55817. * (e.g. global code). The global object environment has special
  55818. * behavior when re-declaring a function (but not a variable); see
  55819. * E5.1 specification, Section 10.5, step 5.e.
  55820. *
  55821. * Declarations always go to the 'top-most' environment record, i.e.
  55822. * we never check the record chain. It's not an error even if a
  55823. * property (even an immutable or non-deletable one) of the same name
  55824. * already exists.
  55825. *
  55826. * If a declared variable already exists, its value needs to be updated
  55827. * (if possible). Returns 1 if a PUTVAR needs to be done by the caller;
  55828. * otherwise returns 0.
  55829. */
  55830. DUK_LOCAL
  55831. duk_bool_t duk__declvar_helper(duk_hthread *thr,
  55832. duk_hobject *env,
  55833. duk_hstring *name,
  55834. duk_tval *val,
  55835. duk_small_int_t prop_flags,
  55836. duk_bool_t is_func_decl) {
  55837. duk_context *ctx = (duk_context *) thr;
  55838. duk_hobject *holder;
  55839. duk_bool_t parents;
  55840. duk__id_lookup_result ref;
  55841. duk_tval *tv;
  55842. DUK_DDD(DUK_DDDPRINT("declvar: thr=%p, env=%p, name=%!O, val=%!T, prop_flags=0x%08lx, is_func_decl=%ld "
  55843. "(env -> %!iO)",
  55844. (void *) thr, (void *) env, (duk_heaphdr *) name,
  55845. (duk_tval *) val, (unsigned long) prop_flags,
  55846. (unsigned int) is_func_decl, (duk_heaphdr *) env));
  55847. DUK_ASSERT(thr != NULL);
  55848. DUK_ASSERT(env != NULL);
  55849. DUK_ASSERT(name != NULL);
  55850. DUK_ASSERT(val != NULL);
  55851. /* Note: in strict mode the compiler should reject explicit
  55852. * declaration of 'eval' or 'arguments'. However, internal
  55853. * bytecode may declare 'arguments' in the function prologue.
  55854. * We don't bother checking (or asserting) for these now.
  55855. */
  55856. /* Note: val is a stable duk_tval pointer. The caller makes
  55857. * a value copy into its stack frame, so 'tv_val' is not subject
  55858. * to side effects here.
  55859. */
  55860. /*
  55861. * Check whether already declared.
  55862. *
  55863. * We need to check whether the binding exists in the environment
  55864. * without walking its parents. However, we still need to check
  55865. * register-bound identifiers and the prototype chain of an object
  55866. * environment target object.
  55867. */
  55868. parents = 0; /* just check 'env' */
  55869. if (duk__get_identifier_reference(thr, env, name, NULL, parents, &ref)) {
  55870. duk_int_t e_idx;
  55871. duk_int_t h_idx;
  55872. duk_small_int_t flags;
  55873. /*
  55874. * Variable already declared, ignore re-declaration.
  55875. * The only exception is the updated behavior of E5.1 for
  55876. * global function declarations, E5.1 Section 10.5, step 5.e.
  55877. * This behavior does not apply to global variable declarations.
  55878. */
  55879. if (!(is_func_decl && env == thr->builtins[DUK_BIDX_GLOBAL_ENV])) {
  55880. DUK_DDD(DUK_DDDPRINT("re-declare a binding, ignoring"));
  55881. return 1; /* 1 -> needs a PUTVAR */
  55882. }
  55883. /*
  55884. * Special behavior in E5.1.
  55885. *
  55886. * Note that even though parents == 0, the conflicting property
  55887. * may be an inherited property (currently our global object's
  55888. * prototype is Object.prototype). Step 5.e first operates on
  55889. * the existing property (which is potentially in an ancestor)
  55890. * and then defines a new property in the global object (and
  55891. * never modifies the ancestor).
  55892. *
  55893. * Also note that this logic would become even more complicated
  55894. * if the conflicting property might be a virtual one. Object
  55895. * prototype has no virtual properties, though.
  55896. *
  55897. * XXX: this is now very awkward, rework.
  55898. */
  55899. DUK_DDD(DUK_DDDPRINT("re-declare a function binding in global object, "
  55900. "updated E5.1 processing"));
  55901. DUK_ASSERT(ref.holder != NULL);
  55902. holder = ref.holder;
  55903. /* holder will be set to the target object, not the actual object
  55904. * where the property was found (see duk__get_identifier_reference()).
  55905. */
  55906. DUK_ASSERT(DUK_HOBJECT_GET_CLASS_NUMBER(holder) == DUK_HOBJECT_CLASS_GLOBAL);
  55907. DUK_ASSERT(!DUK_HOBJECT_HAS_EXOTIC_ARRAY(holder)); /* global object doesn't have array part */
  55908. /* XXX: use a helper for prototype traversal; no loop check here */
  55909. /* must be found: was found earlier, and cannot be inherited */
  55910. for (;;) {
  55911. DUK_ASSERT(holder != NULL);
  55912. duk_hobject_find_existing_entry(thr->heap, holder, name, &e_idx, &h_idx);
  55913. if (e_idx >= 0) {
  55914. break;
  55915. }
  55916. /* SCANBUILD: NULL pointer dereference, doesn't actually trigger,
  55917. * asserted above.
  55918. */
  55919. holder = DUK_HOBJECT_GET_PROTOTYPE(thr->heap, holder);
  55920. }
  55921. DUK_ASSERT(holder != NULL);
  55922. DUK_ASSERT(e_idx >= 0);
  55923. /* SCANBUILD: scan-build produces a NULL pointer dereference warning
  55924. * below; it never actually triggers because holder is actually never
  55925. * NULL.
  55926. */
  55927. /* ref.holder is global object, holder is the object with the
  55928. * conflicting property.
  55929. */
  55930. flags = DUK_HOBJECT_E_GET_FLAGS(thr->heap, holder, e_idx);
  55931. if (!(flags & DUK_PROPDESC_FLAG_CONFIGURABLE)) {
  55932. if (flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  55933. DUK_DDD(DUK_DDDPRINT("existing property is a non-configurable "
  55934. "accessor -> reject"));
  55935. goto fail_existing_attributes;
  55936. }
  55937. if (!((flags & DUK_PROPDESC_FLAG_WRITABLE) &&
  55938. (flags & DUK_PROPDESC_FLAG_ENUMERABLE))) {
  55939. DUK_DDD(DUK_DDDPRINT("existing property is a non-configurable "
  55940. "plain property which is not writable and "
  55941. "enumerable -> reject"));
  55942. goto fail_existing_attributes;
  55943. }
  55944. DUK_DDD(DUK_DDDPRINT("existing property is not configurable but "
  55945. "is plain, enumerable, and writable -> "
  55946. "allow redeclaration"));
  55947. }
  55948. if (holder == ref.holder) {
  55949. /* XXX: if duk_hobject_define_property_internal() was updated
  55950. * to handle a pre-existing accessor property, this would be
  55951. * a simple call (like for the ancestor case).
  55952. */
  55953. DUK_DDD(DUK_DDDPRINT("redefine, offending property in global object itself"));
  55954. if (flags & DUK_PROPDESC_FLAG_ACCESSOR) {
  55955. duk_hobject *tmp;
  55956. tmp = DUK_HOBJECT_E_GET_VALUE_GETTER(thr->heap, holder, e_idx);
  55957. DUK_HOBJECT_E_SET_VALUE_GETTER(thr->heap, holder, e_idx, NULL);
  55958. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  55959. DUK_UNREF(tmp);
  55960. tmp = DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, holder, e_idx);
  55961. DUK_HOBJECT_E_SET_VALUE_SETTER(thr->heap, holder, e_idx, NULL);
  55962. DUK_HOBJECT_DECREF_ALLOWNULL(thr, tmp);
  55963. DUK_UNREF(tmp);
  55964. } else {
  55965. duk_tval tv_tmp;
  55966. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, holder, e_idx);
  55967. DUK_TVAL_SET_TVAL(&tv_tmp, tv);
  55968. DUK_TVAL_SET_UNDEFINED_UNUSED(tv);
  55969. DUK_TVAL_DECREF(thr, &tv_tmp);
  55970. }
  55971. /* Here val would be potentially invalid if we didn't make
  55972. * a value copy at the caller.
  55973. */
  55974. tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, holder, e_idx);
  55975. DUK_TVAL_SET_TVAL(tv, val);
  55976. DUK_TVAL_INCREF(thr, tv);
  55977. DUK_HOBJECT_E_SET_FLAGS(thr->heap, holder, e_idx, prop_flags);
  55978. DUK_DDD(DUK_DDDPRINT("updated global binding, final result: "
  55979. "value -> %!T, prop_flags=0x%08lx",
  55980. (duk_tval *) DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, holder, e_idx),
  55981. (unsigned long) prop_flags));
  55982. } else {
  55983. DUK_DDD(DUK_DDDPRINT("redefine, offending property in ancestor"));
  55984. DUK_ASSERT(ref.holder == thr->builtins[DUK_BIDX_GLOBAL]);
  55985. duk_push_tval(ctx, val);
  55986. duk_hobject_define_property_internal(thr, ref.holder, name, prop_flags);
  55987. }
  55988. return 0;
  55989. }
  55990. /*
  55991. * Not found (in registers or record objects). Declare
  55992. * to current variable environment.
  55993. */
  55994. /*
  55995. * Get holder object
  55996. */
  55997. if (DUK_HOBJECT_IS_DECENV(env)) {
  55998. holder = env;
  55999. } else {
  56000. DUK_ASSERT(DUK_HOBJECT_IS_OBJENV(env));
  56001. tv = duk_hobject_find_existing_entry_tval_ptr(thr->heap, env, DUK_HTHREAD_STRING_INT_TARGET(thr));
  56002. DUK_ASSERT(tv != NULL);
  56003. DUK_ASSERT(DUK_TVAL_IS_OBJECT(tv));
  56004. holder = DUK_TVAL_GET_OBJECT(tv);
  56005. DUK_ASSERT(holder != NULL);
  56006. }
  56007. /*
  56008. * Define new property
  56009. *
  56010. * Note: this may fail if the holder is not extensible.
  56011. */
  56012. /* XXX: this is awkward as we use an internal method which doesn't handle
  56013. * extensibility etc correctly. Basically we'd want to do a [[DefineOwnProperty]]
  56014. * or Object.defineProperty() here.
  56015. */
  56016. if (!DUK_HOBJECT_HAS_EXTENSIBLE(holder)) {
  56017. goto fail_not_extensible;
  56018. }
  56019. duk_push_hobject(ctx, holder);
  56020. duk_push_hstring(ctx, name);
  56021. duk_push_tval(ctx, val);
  56022. duk_xdef_prop(ctx, -3, prop_flags); /* [holder name val] -> [holder] */
  56023. duk_pop(ctx);
  56024. return 0;
  56025. fail_existing_attributes:
  56026. fail_not_extensible:
  56027. DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, "declaration failed");
  56028. return 0;
  56029. }
  56030. DUK_INTERNAL
  56031. duk_bool_t duk_js_declvar_activation(duk_hthread *thr,
  56032. duk_activation *act,
  56033. duk_hstring *name,
  56034. duk_tval *val,
  56035. duk_small_int_t prop_flags,
  56036. duk_bool_t is_func_decl) {
  56037. duk_hobject *env;
  56038. duk_tval tv_val_copy;
  56039. /*
  56040. * Make a value copy of the input val. This ensures that
  56041. * side effects cannot invalidate the pointer.
  56042. */
  56043. DUK_TVAL_SET_TVAL(&tv_val_copy, val);
  56044. val = &tv_val_copy;
  56045. /*
  56046. * Delayed env creation check
  56047. */
  56048. if (!act->var_env) {
  56049. DUK_ASSERT(act->lex_env == NULL);
  56050. duk_js_init_activation_environment_records_delayed(thr, act);
  56051. }
  56052. DUK_ASSERT(act->lex_env != NULL);
  56053. DUK_ASSERT(act->var_env != NULL);
  56054. env = act->var_env;
  56055. DUK_ASSERT(env != NULL);
  56056. DUK_ASSERT(DUK_HOBJECT_IS_ENV(env));
  56057. return duk__declvar_helper(thr, env, name, val, prop_flags, is_func_decl);
  56058. }
  56059. #line 1 "duk_lexer.c"
  56060. /*
  56061. * Lexer for source files, ToNumber() string conversions, RegExp expressions,
  56062. * and JSON.
  56063. *
  56064. * Provides a stream of Ecmascript tokens from an UTF-8/CESU-8 buffer. The
  56065. * caller can also rewind the token stream into a certain position which is
  56066. * needed by the compiler part for multi-pass scanning. Tokens are
  56067. * represented as duk_token structures, and contain line number information.
  56068. * Token types are identified with DUK_TOK_* defines.
  56069. *
  56070. * Characters are decoded into a fixed size lookup window consisting of
  56071. * decoded Unicode code points, with window positions past the end of the
  56072. * input filled with an invalid codepoint (-1). The tokenizer can thus
  56073. * perform multiple character lookups efficiently and with few sanity
  56074. * checks (such as access outside the end of the input), which keeps the
  56075. * tokenization code small at the cost of performance.
  56076. *
  56077. * Character data in tokens (such as identifier names and string literals)
  56078. * is encoded into CESU-8 format on-the-fly while parsing the token in
  56079. * question. The string data is made reachable to garbage collection by
  56080. * placing the token-related values in value stack entries allocated for
  56081. * this purpose by the caller. The characters exist in Unicode code point
  56082. * form only in the fixed size lookup window, which keeps character data
  56083. * expansion (of especially ASCII data) low.
  56084. *
  56085. * Token parsing supports the full range of Unicode characters as described
  56086. * in the E5 specification. Parsing has been optimized for ASCII characters
  56087. * because ordinary Ecmascript code consists almost entirely of ASCII
  56088. * characters. Matching of complex Unicode codepoint sets (such as in the
  56089. * IdentifierStart and IdentifierPart productions) is optimized for size,
  56090. * and is done using a linear scan of a bit-packed list of ranges. This is
  56091. * very slow, but should never be entered unless the source code actually
  56092. * contains Unicode characters.
  56093. *
  56094. * Ecmascript tokenization is partially context sensitive. First,
  56095. * additional future reserved words are recognized in strict mode (see E5
  56096. * Section 7.6.1.2). Second, a forward slash character ('/') can be
  56097. * recognized either as starting a RegExp literal or as a division operator,
  56098. * depending on context. The caller must provide necessary context flags
  56099. * when requesting a new token.
  56100. *
  56101. * Future work:
  56102. *
  56103. * * Make the input window a circular array to avoid copying. This would
  56104. * not necessarily complicate the tokenizer much, although it would make
  56105. * the window fetches more expensive (one AND).
  56106. *
  56107. * * Make line number tracking optional, as it consumes space. Also, is
  56108. * tracking end line really useful for tokens?
  56109. *
  56110. * * Add a feature flag for disabling UTF-8 decoding of input, as most
  56111. * source code is ASCII. Because of Unicode escapes written in ASCII,
  56112. * this does not allow Unicode support to be removed from e.g.
  56113. * duk_unicode_is_identifier_start() nor does it allow removal of CESU-8
  56114. * encoding of e.g. string literals.
  56115. *
  56116. * * Add a feature flag for disabling Unicode compliance of e.g. identifier
  56117. * names. This allows for a build more than a kilobyte smaller, because
  56118. * Unicode ranges needed by duk_unicode_is_identifier_start() and
  56119. * duk_unicode_is_identifier_part() can be dropped. String literals
  56120. * should still be allowed to contain escaped Unicode, so this still does
  56121. * not allow removal of CESU-8 encoding of e.g. string literals.
  56122. *
  56123. * * Character lookup tables for codepoints above BMP could be stripped.
  56124. *
  56125. * * Strictly speaking, E5 specification requires that source code consists
  56126. * of 16-bit code units, and if not, must be conceptually converted to
  56127. * that format first. The current lexer processes Unicode code points
  56128. * and allows characters outside the BMP. These should be converted to
  56129. * surrogate pairs while reading the source characters into the window,
  56130. * not after tokens have been formed (as is done now). However, the fix
  56131. * is not trivial because two characters are decoded from one codepoint.
  56132. *
  56133. * * Optimize for speed as well as size. Large if-else ladders are slow.
  56134. */
  56135. /* include removed: duk_internal.h */
  56136. /*
  56137. * Various defines and file specific helper macros
  56138. */
  56139. #define DUK__MAX_RE_DECESC_DIGITS 9
  56140. #define DUK__MAX_RE_QUANT_DIGITS 9 /* Does not allow e.g. 2**31-1, but one more would allow overflows of u32. */
  56141. #define DUK__LOOKUP(lex_ctx,index) ((lex_ctx)->window[(index)])
  56142. #define DUK__ADVANCE(lex_ctx,count) duk__advance_chars((lex_ctx), (count))
  56143. #define DUK__INITBUFFER(lex_ctx) duk__initbuffer((lex_ctx))
  56144. #define DUK__APPENDBUFFER(lex_ctx,x) duk__appendbuffer((lex_ctx), (duk_codepoint_t) (x))
  56145. /* whether to use macros or helper function depends on call count */
  56146. #define DUK__ISDIGIT(x) ((x) >= DUK_ASC_0 && (x) <= DUK_ASC_9)
  56147. #define DUK__ISHEXDIGIT(x) duk__is_hex_digit((x))
  56148. #define DUK__ISOCTDIGIT(x) ((x) >= DUK_ASC_0 && (x) <= DUK_ASC_7)
  56149. #define DUK__ISDIGIT03(x) ((x) >= DUK_ASC_0 && (x) <= DUK_ASC_3)
  56150. #define DUK__ISDIGIT47(x) ((x) >= DUK_ASC_4 && (x) <= DUK_ASC_7)
  56151. /* lookup shorthands (note: assume context variable is named 'lex_ctx') */
  56152. #define DUK__L0() DUK__LOOKUP(lex_ctx, 0)
  56153. #define DUK__L1() DUK__LOOKUP(lex_ctx, 1)
  56154. #define DUK__L2() DUK__LOOKUP(lex_ctx, 2)
  56155. #define DUK__L3() DUK__LOOKUP(lex_ctx, 3)
  56156. #define DUK__L4() DUK__LOOKUP(lex_ctx, 4)
  56157. #define DUK__L5() DUK__LOOKUP(lex_ctx, 5)
  56158. /* packed advance/token number macro used by multiple functions */
  56159. #define DUK__ADVTOK(adv,tok) (((adv) << 8) + (tok))
  56160. /*
  56161. * Read a character from the window leading edge and update the line counter.
  56162. *
  56163. * Decodes UTF-8/CESU-8 leniently with support for code points from U+0000 to
  56164. * U+10FFFF, causing an error if the input is unparseable. Leniency means:
  56165. *
  56166. * * Unicode code point validation is intentionally not performed,
  56167. * except to check that the codepoint does not exceed 0x10ffff.
  56168. *
  56169. * * In particular, surrogate pairs are allowed and not combined, which
  56170. * allows source files to represent all SourceCharacters with CESU-8.
  56171. * Broken surrogate pairs are allowed, as Ecmascript does not mandate
  56172. * their validation.
  56173. *
  56174. * * Allow non-shortest UTF-8 encodings.
  56175. *
  56176. * Leniency here causes few security concerns because all character data is
  56177. * decoded into Unicode codepoints before lexer processing, and is then
  56178. * re-encoded into CESU-8. The source can be parsed as strict UTF-8 with
  56179. * a compiler option. However, Ecmascript source characters include -all-
  56180. * 16-bit unsigned integer codepoints, so leniency seems to be appropriate.
  56181. *
  56182. * Note that codepoints above the BMP are not strictly SourceCharacters,
  56183. * but the lexer still accepts them as such. Before ending up in a string
  56184. * or an identifier name, codepoints above BMP are converted into surrogate
  56185. * pairs and then CESU-8 encoded, resulting in 16-bit Unicode data as
  56186. * expected by Ecmascript.
  56187. *
  56188. * An alternative approach to dealing with invalid or partial sequences
  56189. * would be to skip them and replace them with e.g. the Unicode replacement
  56190. * character U+FFFD. This has limited utility because a replacement character
  56191. * will most likely cause a parse error, unless it occurs inside a string.
  56192. * Further, Ecmascript source is typically pure ASCII.
  56193. *
  56194. * See:
  56195. *
  56196. * http://en.wikipedia.org/wiki/UTF-8
  56197. * http://en.wikipedia.org/wiki/CESU-8
  56198. * http://tools.ietf.org/html/rfc3629
  56199. * http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences
  56200. *
  56201. * Future work:
  56202. *
  56203. * * Reject other invalid Unicode sequences (see Wikipedia entry for examples)
  56204. * in strict UTF-8 mode.
  56205. *
  56206. * * Size optimize. An attempt to use a 16-byte lookup table for the first
  56207. * byte resulted in a code increase though.
  56208. *
  56209. * * Is checking against maximum 0x10ffff really useful? 4-byte encoding
  56210. * imposes a certain limit anyway.
  56211. */
  56212. DUK_LOCAL duk_codepoint_t duk__read_char(duk_lexer_ctx *lex_ctx) {
  56213. /* attempting to reduce size of 'len' and/or 'i' resulted in larger code */
  56214. duk_codepoint_t x;
  56215. duk_small_int_t len;
  56216. duk_small_int_t i;
  56217. const duk_uint8_t *p;
  56218. #ifdef DUK_USE_STRICT_UTF8_SOURCE
  56219. duk_codepoint_t mincp;
  56220. #endif
  56221. duk_size_t input_offset;
  56222. input_offset = lex_ctx->input_offset;
  56223. if (DUK_UNLIKELY(input_offset >= lex_ctx->input_length)) {
  56224. /* If input_offset were assigned a negative value, it would
  56225. * result in a large positive value. Most likely it would be
  56226. * larger than input_length and be caught here. In any case
  56227. * no memory unsafe behavior would happen.
  56228. */
  56229. return -1;
  56230. }
  56231. p = lex_ctx->input + input_offset;
  56232. x = (int) *p++;
  56233. if (x < 0x80L) {
  56234. /* 0xxx xxxx -> fast path */
  56235. len = 1;
  56236. goto fastpath;
  56237. } else if (x < 0xc0L) {
  56238. /* 10xx xxxx -> invalid */
  56239. goto error_encoding;
  56240. } else if (x < 0xe0L) {
  56241. /* 110x xxxx 10xx xxxx */
  56242. len = 2;
  56243. #ifdef DUK_USE_STRICT_UTF8_SOURCE
  56244. mincp = 0x80L;
  56245. #endif
  56246. x = x & 0x1fL;
  56247. } else if (x < 0xf0L) {
  56248. /* 1110 xxxx 10xx xxxx 10xx xxxx */
  56249. len = 3;
  56250. #ifdef DUK_USE_STRICT_UTF8_SOURCE
  56251. mincp = 0x800L;
  56252. #endif
  56253. x = x & 0x0fL;
  56254. } else if (x < 0xf8L) {
  56255. /* 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx */
  56256. len = 4;
  56257. #ifdef DUK_USE_STRICT_UTF8_SOURCE
  56258. mincp = 0x10000L;
  56259. #endif
  56260. x = x & 0x07;
  56261. } else {
  56262. /* no point in supporting encodings of 5 or more bytes */
  56263. goto error_encoding;
  56264. }
  56265. DUK_ASSERT(lex_ctx->input_length >= lex_ctx->input_offset);
  56266. if ((duk_size_t) len > (duk_size_t) (lex_ctx->input_length - lex_ctx->input_offset)) {
  56267. goto error_clipped;
  56268. }
  56269. for (i = 1; i < len; i++) {
  56270. duk_small_int_t y = *p++;
  56271. if ((y & 0xc0) != 0x80) {
  56272. /* check that byte has the form 10xx xxxx */
  56273. goto error_encoding;
  56274. }
  56275. x = x << 6;
  56276. x += y & 0x3f;
  56277. }
  56278. /* check final character validity */
  56279. if (x > 0x10ffffL) {
  56280. goto error_encoding;
  56281. }
  56282. #ifdef DUK_USE_STRICT_UTF8_SOURCE
  56283. if (x < mincp || (x >= 0xd800L && x <= 0xdfffL) || x == 0xfffeL) {
  56284. goto error_encoding;
  56285. }
  56286. #endif
  56287. /* fall through */
  56288. fastpath:
  56289. /* input offset tracking */
  56290. lex_ctx->input_offset += len;
  56291. /* line tracking */
  56292. if ((x == 0x000aL) ||
  56293. ((x == 0x000dL) && (lex_ctx->input_offset >= lex_ctx->input_length ||
  56294. lex_ctx->input[lex_ctx->input_offset] != 0x000aL)) ||
  56295. (x == 0x2028L) ||
  56296. (x == 0x2029L)) {
  56297. /* lookup for 0x000a above assumes shortest encoding now */
  56298. /* E5 Section 7.3, treat the following as newlines:
  56299. * LF
  56300. * CR [not followed by LF]
  56301. * LS
  56302. * PS
  56303. *
  56304. * For CR LF, CR is ignored if it is followed by LF, and the LF will bump
  56305. * the line number.
  56306. */
  56307. lex_ctx->input_line++;
  56308. }
  56309. return x;
  56310. error_clipped: /* clipped codepoint */
  56311. error_encoding: /* invalid codepoint encoding or codepoint */
  56312. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR, "char decode failed");
  56313. return 0;
  56314. }
  56315. /*
  56316. * Advance lookup window by N characters. Also used to fill the window
  56317. * after position is changed (call with count == DUK_LEXER_WINDOW_SIZE).
  56318. *
  56319. * XXX: A lot of copying now, perhaps change to circular array or at
  56320. * least use memcpy(). For memcpy(), putting all elements of the
  56321. * window (code point, offset, line) into a struct would allow one
  56322. * memcpy() to slide the window, instead of three separate copys.
  56323. */
  56324. DUK_LOCAL void duk__advance_chars(duk_lexer_ctx *lex_ctx, duk_small_int_t count) {
  56325. duk_small_int_t i, n;
  56326. DUK_ASSERT(count >= 0 && count <= DUK_LEXER_WINDOW_SIZE);
  56327. /* Without this check, gcc -O4 will complain the following for the
  56328. * first for-loop below:
  56329. *
  56330. * duk_lexer.c:301:19: error: array subscript is above array bounds [-Werror=array-bounds]
  56331. *
  56332. * Check for range explicitly; this also protects against legitimate
  56333. * internal errors and avoids memory unsafe behavior in such cases.
  56334. */
  56335. if (DUK_UNLIKELY(!(count >= 0 && count <= DUK_LEXER_WINDOW_SIZE))) {
  56336. DUK_D(DUK_DPRINT("invalid count: %ld, should not happen", (long) count));
  56337. DUK_ERROR(lex_ctx->thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_INTERNAL_ERROR);
  56338. return; /* never here */
  56339. }
  56340. if (count == 0) {
  56341. /* allowing zero count makes some special caller flows easier */
  56342. return;
  56343. }
  56344. n = DUK_LEXER_WINDOW_SIZE - count;
  56345. for (i = 0; i < n; i++) {
  56346. lex_ctx->offsets[i] = lex_ctx->offsets[i + count];
  56347. lex_ctx->lines[i] = lex_ctx->lines[i + count];
  56348. lex_ctx->window[i] = lex_ctx->window[i + count];
  56349. }
  56350. for (; i < DUK_LEXER_WINDOW_SIZE; i++) {
  56351. lex_ctx->offsets[i] = lex_ctx->input_offset;
  56352. lex_ctx->lines[i] = lex_ctx->input_line;
  56353. lex_ctx->window[i] = duk__read_char(lex_ctx);
  56354. }
  56355. }
  56356. /*
  56357. * (Re)initialize the temporary byte buffer. May be called extra times
  56358. * with little impact.
  56359. */
  56360. DUK_LOCAL void duk__initbuffer(duk_lexer_ctx *lex_ctx) {
  56361. if (DUK_HBUFFER_DYNAMIC_GET_ALLOC_SIZE(lex_ctx->buf) < DUK_LEXER_TEMP_BUF_LIMIT) {
  56362. /* Resize (zero) without realloc. */
  56363. DUK_HBUFFER_DYNAMIC_SET_SIZE(lex_ctx->buf, 0);
  56364. } else {
  56365. duk_hbuffer_resize(lex_ctx->thr, lex_ctx->buf, 0, DUK_LEXER_TEMP_BUF_LIMIT);
  56366. }
  56367. }
  56368. /*
  56369. * Append a Unicode codepoint to the temporary byte buffer. Performs
  56370. * CESU-8 surrogate pair encoding for codepoints above the BMP.
  56371. * Existing surrogate pairs are allowed and also encoded into CESU-8.
  56372. */
  56373. DUK_LOCAL void duk__appendbuffer(duk_lexer_ctx *lex_ctx, duk_codepoint_t x) {
  56374. /*
  56375. * Since character data is only generated by decoding the source or by
  56376. * the compiler itself, we rely on the input codepoints being correct
  56377. * and avoid a check here.
  56378. *
  56379. * Character data can also come here through decoding of Unicode
  56380. * escapes ("\udead\ubeef") so all 16-but unsigned values can be
  56381. * present, even when the source file itself is strict UTF-8.
  56382. */
  56383. DUK_ASSERT(x >= 0 && x <= 0x10ffff);
  56384. duk_hbuffer_append_cesu8(lex_ctx->thr, lex_ctx->buf, (duk_ucodepoint_t) x);
  56385. }
  56386. /*
  56387. * Intern the temporary byte buffer into a valstack slot
  56388. * (in practice, slot1 or slot2).
  56389. */
  56390. DUK_LOCAL void duk__internbuffer(duk_lexer_ctx *lex_ctx, duk_idx_t valstack_idx) {
  56391. duk_context *ctx = (duk_context *) lex_ctx->thr;
  56392. DUK_ASSERT(valstack_idx == lex_ctx->slot1_idx || valstack_idx == lex_ctx->slot2_idx);
  56393. duk_dup(ctx, lex_ctx->buf_idx);
  56394. duk_to_string(ctx, -1);
  56395. duk_replace(ctx, valstack_idx);
  56396. }
  56397. /*
  56398. * Init lexer context
  56399. */
  56400. DUK_INTERNAL void duk_lexer_initctx(duk_lexer_ctx *lex_ctx) {
  56401. DUK_ASSERT(lex_ctx != NULL);
  56402. DUK_MEMZERO(lex_ctx, sizeof(*lex_ctx));
  56403. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  56404. lex_ctx->thr = NULL;
  56405. lex_ctx->input = NULL;
  56406. lex_ctx->buf = NULL;
  56407. #endif
  56408. }
  56409. /*
  56410. * Set lexer input position and reinitialize lookup window.
  56411. */
  56412. /* NB: duk_lexer_getpoint() is a macro only */
  56413. DUK_INTERNAL void duk_lexer_setpoint(duk_lexer_ctx *lex_ctx, duk_lexer_point *pt) {
  56414. DUK_ASSERT_DISABLE(pt->offset >= 0); /* unsigned */
  56415. DUK_ASSERT(pt->line >= 1);
  56416. lex_ctx->input_offset = pt->offset;
  56417. lex_ctx->input_line = pt->line;
  56418. duk__advance_chars(lex_ctx, DUK_LEXER_WINDOW_SIZE); /* fill window */
  56419. }
  56420. /*
  56421. * Lexing helpers
  56422. */
  56423. /* numeric value of a hex digit (also covers octal and decimal digits) */
  56424. DUK_LOCAL duk_codepoint_t duk__hexval(duk_lexer_ctx *lex_ctx, duk_codepoint_t x) {
  56425. duk_small_int_t t;
  56426. /* Here 'x' is a Unicode codepoint */
  56427. if (DUK_LIKELY(x >= 0 && x <= 0xff)) {
  56428. t = duk_hex_dectab[x];
  56429. if (DUK_LIKELY(t >= 0)) {
  56430. return t;
  56431. }
  56432. }
  56433. /* Throwing an error this deep makes the error rather vague, but
  56434. * saves hundreds of bytes of code.
  56435. */
  56436. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR, "decode error");
  56437. return 0;
  56438. }
  56439. /* having this as a separate function provided a size benefit */
  56440. DUK_LOCAL duk_bool_t duk__is_hex_digit(duk_codepoint_t x) {
  56441. if (DUK_LIKELY(x >= 0 && x <= 0xff)) {
  56442. return (duk_hex_dectab[x] >= 0);
  56443. }
  56444. return 0;
  56445. }
  56446. DUK_LOCAL duk_codepoint_t duk__decode_hexesc_from_window(duk_lexer_ctx *lex_ctx, duk_small_int_t lookup_offset) {
  56447. /* validation performed by duk__hexval */
  56448. return (duk__hexval(lex_ctx, lex_ctx->window[lookup_offset]) << 4) |
  56449. (duk__hexval(lex_ctx, lex_ctx->window[lookup_offset + 1]));
  56450. }
  56451. DUK_LOCAL duk_codepoint_t duk__decode_uniesc_from_window(duk_lexer_ctx *lex_ctx, duk_small_int_t lookup_offset) {
  56452. /* validation performed by duk__hexval */
  56453. return (duk__hexval(lex_ctx, lex_ctx->window[lookup_offset]) << 12) |
  56454. (duk__hexval(lex_ctx, lex_ctx->window[lookup_offset + 1]) << 8) |
  56455. (duk__hexval(lex_ctx, lex_ctx->window[lookup_offset + 2]) << 4) |
  56456. (duk__hexval(lex_ctx, lex_ctx->window[lookup_offset + 3]));
  56457. }
  56458. /*
  56459. * Eat input characters until first character of window is not
  56460. * a white space (may be -1 if EOF encountered).
  56461. */
  56462. DUK_LOCAL void duk__eat_whitespace(duk_lexer_ctx *lex_ctx) {
  56463. /* guaranteed to finish, as EOF (-1) is not a whitespace */
  56464. while (duk_unicode_is_whitespace(DUK__LOOKUP(lex_ctx, 0))) {
  56465. DUK__ADVANCE(lex_ctx, 1);
  56466. }
  56467. }
  56468. /*
  56469. * Parse Ecmascript source InputElementDiv or InputElementRegExp
  56470. * (E5 Section 7).
  56471. *
  56472. * Possible results are:
  56473. * (1) a token
  56474. * (2) a line terminator
  56475. * (3) a comment
  56476. * (4) EOF
  56477. *
  56478. * White space is automatically skipped from the current position (but
  56479. * not after the input element). If input has already ended, returns
  56480. * DUK_TOK_EOF indefinitely. If a parse error occurs, uses an DUK_ERROR()
  56481. * macro call (and hence a longjmp through current heap longjmp context).
  56482. *
  56483. * The input element being matched is determined by regexp_mode; if set,
  56484. * parses a InputElementRegExp, otherwise a InputElementDiv. The
  56485. * difference between these are handling of productions starting with a
  56486. * forward slash.
  56487. *
  56488. * If strict_mode is set, recognizes additional future reserved words
  56489. * specific to strict mode, and refuses to parse octal literals.
  56490. *
  56491. * The matching strategy below is to (currently) use a six character
  56492. * lookup window to quickly determine which production is the -longest-
  56493. * matching one, and then parse that. The top-level if-else clauses
  56494. * match the first character, and the code blocks for each clause
  56495. * handle -all- alternatives for that first character. Ecmascript
  56496. * specification uses the "longest match wins" semantics, so the order
  56497. * of the if-clauses matters.
  56498. *
  56499. * Misc notes:
  56500. *
  56501. * * Ecmascript numeric literals do not accept a sign character.
  56502. * Consequently e.g. "-1.0" is parsed as two tokens: a negative
  56503. * sign and a positive numeric literal. The compiler performs
  56504. * the negation during compilation, so this has no adverse impact.
  56505. *
  56506. * * There is no token for "undefined": it is just a value available
  56507. * from the global object (or simply established by doing a reference
  56508. * to an undefined value).
  56509. *
  56510. * * Some contexts want Identifier tokens, which are IdentifierNames
  56511. * excluding reserved words, while some contexts want IdentifierNames
  56512. * directly. In the latter case e.g. "while" is interpreted as an
  56513. * identifier name, not a DUK_TOK_WHILE token. The solution here is
  56514. * to provide both token types: DUK_TOK_WHILE goes to 't' while
  56515. * DUK_TOK_IDENTIFIER goes to 't_nores', and 'slot1' always contains
  56516. * the identifier / keyword name.
  56517. *
  56518. * * Directive prologue needs to identify string literals such as
  56519. * "use strict" and 'use strict', which are sensitive to line
  56520. * continuations and escape sequences. For instance, "use\u0020strict"
  56521. * is a valid directive but is distinct from "use strict". The solution
  56522. * here is to decode escapes while tokenizing, but to keep track of the
  56523. * number of escapes. Directive detection can then check that the
  56524. * number of escapes is zero.
  56525. *
  56526. * * Comments are expressed as DUK_TOK_COMMENT tokens, with the type
  56527. * (single- or multi-line) and contents of the comments lost.
  56528. * Furthermore, multi-line comments with one or more internal
  56529. * LineTerminator are treated as DUK_TOK_LINETERM to comply with
  56530. * automatic semicolon insertion and to avoid complicating the
  56531. * tokenization process. See E5 Section 7.4.
  56532. */
  56533. DUK_LOCAL
  56534. void duk__parse_input_element_raw(duk_lexer_ctx *lex_ctx,
  56535. duk_token *out_token,
  56536. duk_bool_t strict_mode,
  56537. duk_bool_t regexp_mode) {
  56538. duk_codepoint_t x, y; /* temporaries, must be signed and 32-bit to hold Unicode code points */
  56539. duk_small_uint_t advtok = 0; /* (advance << 8) + token_type, updated at function end,
  56540. * init is unnecessary but suppresses "may be used uninitialized" warnings.
  56541. */
  56542. if (++lex_ctx->token_count >= lex_ctx->token_limit) {
  56543. DUK_ERROR(lex_ctx->thr, DUK_ERR_RANGE_ERROR, "token limit");
  56544. return; /* unreachable */
  56545. }
  56546. duk__eat_whitespace(lex_ctx);
  56547. out_token->t = DUK_TOK_EOF;
  56548. out_token->t_nores = -1; /* marker: copy t if not changed */
  56549. out_token->num = DUK_DOUBLE_NAN;
  56550. out_token->str1 = NULL;
  56551. out_token->str2 = NULL;
  56552. out_token->num_escapes = 0;
  56553. out_token->start_line = lex_ctx->lines[0];
  56554. out_token->start_offset = lex_ctx->offsets[0];
  56555. /* out_token->lineterm set by caller */
  56556. duk_to_undefined((duk_context *) lex_ctx->thr, lex_ctx->slot1_idx);
  56557. duk_to_undefined((duk_context *) lex_ctx->thr, lex_ctx->slot2_idx);
  56558. /* 'advtok' indicates how much to advance and which token id to assign
  56559. * at the end. This shared functionality minimizes code size. All
  56560. * code paths are required to set 'advtok' to some value, so no default
  56561. * init value is used. Code paths calling DUK_ERROR() never return so
  56562. * they don't need to set advtok.
  56563. */
  56564. /*
  56565. * Matching order:
  56566. *
  56567. * Punctuator first chars, also covers comments, regexps
  56568. * LineTerminator
  56569. * Identifier or reserved word, also covers null/true/false literals
  56570. * NumericLiteral
  56571. * StringLiteral
  56572. * EOF
  56573. *
  56574. * The order does not matter as long as the longest match is
  56575. * always correctly identified. There are order dependencies
  56576. * in the clauses, so it's not trivial to convert to a switch.
  56577. *
  56578. * XXX: This is quite inefficient. Maybe change to a switch
  56579. * statement which handles all single character cases and then
  56580. * use a followup if-else chain? Switch matches need to use
  56581. * goto to bypass the if-else chain.
  56582. */
  56583. x = DUK__L0();
  56584. y = DUK__L1();
  56585. if (x == '/') {
  56586. if (y == '/') {
  56587. /*
  56588. * E5 Section 7.4, allow SourceCharacter (which is any 16-bit
  56589. * code point).
  56590. */
  56591. /* DUK__ADVANCE(lex_ctx, 2) would be correct here, but it unnecessary */
  56592. for (;;) {
  56593. x = DUK__L0();
  56594. if (x < 0 || duk_unicode_is_line_terminator(x)) {
  56595. break;
  56596. }
  56597. DUK__ADVANCE(lex_ctx, 1);
  56598. }
  56599. advtok = DUK__ADVTOK(0, DUK_TOK_COMMENT);
  56600. } else if (y == '*') {
  56601. /*
  56602. * E5 Section 7.4. If the multi-line comment contains a newline,
  56603. * it is treated like a single DUK_TOK_LINETERM to facilitate
  56604. * automatic semicolon insertion.
  56605. */
  56606. duk_bool_t last_asterisk = 0;
  56607. advtok = DUK__ADVTOK(0, DUK_TOK_COMMENT);
  56608. DUK__ADVANCE(lex_ctx, 2);
  56609. for (;;) {
  56610. x = DUK__L0();
  56611. if (x < 0) {
  56612. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  56613. "eof while parsing multiline comment");
  56614. }
  56615. DUK__ADVANCE(lex_ctx, 1);
  56616. if (last_asterisk && x == '/') {
  56617. break;
  56618. }
  56619. if (duk_unicode_is_line_terminator(x)) {
  56620. advtok = DUK__ADVTOK(0, DUK_TOK_LINETERM);
  56621. }
  56622. last_asterisk = (x == '*');
  56623. }
  56624. } else if (regexp_mode) {
  56625. #ifdef DUK_USE_REGEXP_SUPPORT
  56626. /*
  56627. * "/" followed by something in regexp mode. See E5 Section 7.8.5.
  56628. *
  56629. * RegExp parsing is a bit complex. First, the regexp body is delimited
  56630. * by forward slashes, but the body may also contain forward slashes as
  56631. * part of an escape sequence or inside a character class (delimited by
  56632. * square brackets). A mini state machine is used to implement these.
  56633. *
  56634. * Further, an early (parse time) error must be thrown if the regexp
  56635. * would cause a run-time error when used in the expression new RegExp(...).
  56636. * Parsing here simply extracts the (candidate) regexp, and also accepts
  56637. * invalid regular expressions (which are delimited properly). The caller
  56638. * (compiler) must perform final validation and regexp compilation.
  56639. *
  56640. * RegExp first char may not be '/' (single line comment) or '*' (multi-
  56641. * line comment). These have already been checked above, so there is no
  56642. * need below for special handling of the first regexp character as in
  56643. * the E5 productions.
  56644. *
  56645. * About unicode escapes within regexp literals:
  56646. *
  56647. * E5 Section 7.8.5 grammar does NOT accept \uHHHH escapes.
  56648. * However, Section 6 states that regexps accept the escapes,
  56649. * see paragraph starting with "In string literals...".
  56650. * The regexp grammar, which sees the decoded regexp literal
  56651. * (after lexical parsing) DOES have a \uHHHH unicode escape.
  56652. * So, for instance:
  56653. *
  56654. * /\u1234/
  56655. *
  56656. * should first be parsed by the lexical grammar as:
  56657. *
  56658. * '\' 'u' RegularExpressionBackslashSequence
  56659. * '1' RegularExpressionNonTerminator
  56660. * '2' RegularExpressionNonTerminator
  56661. * '3' RegularExpressionNonTerminator
  56662. * '4' RegularExpressionNonTerminator
  56663. *
  56664. * and the escape itself is then parsed by the regexp engine.
  56665. * This is the current implementation.
  56666. *
  56667. * Minor spec inconsistency:
  56668. *
  56669. * E5 Section 7.8.5 RegularExpressionBackslashSequence is:
  56670. *
  56671. * \ RegularExpressionNonTerminator
  56672. *
  56673. * while Section A.1 RegularExpressionBackslashSequence is:
  56674. *
  56675. * \ NonTerminator
  56676. *
  56677. * The latter is not normative and a typo.
  56678. *
  56679. */
  56680. /* first, parse regexp body roughly */
  56681. duk_small_int_t state = 0; /* 0=base, 1=esc, 2=class, 3=class+esc */
  56682. DUK__INITBUFFER(lex_ctx);
  56683. for (;;) {
  56684. DUK__ADVANCE(lex_ctx, 1); /* skip opening slash on first loop */
  56685. x = DUK__L0();
  56686. if (x < 0 || duk_unicode_is_line_terminator(x)) {
  56687. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  56688. "eof or line terminator while parsing regexp");
  56689. }
  56690. x = DUK__L0(); /* re-read to avoid spill / fetch */
  56691. if (state == 0) {
  56692. if (x == '/') {
  56693. DUK__ADVANCE(lex_ctx, 1); /* eat closing slash */
  56694. break;
  56695. } else if (x == '\\') {
  56696. state = 1;
  56697. } else if (x == '[') {
  56698. state = 2;
  56699. }
  56700. } else if (state == 1) {
  56701. state = 0;
  56702. } else if (state == 2) {
  56703. if (x == ']') {
  56704. state = 0;
  56705. } else if (x == '\\') {
  56706. state = 3;
  56707. }
  56708. } else { /* state == 3 */
  56709. state = 2;
  56710. }
  56711. DUK__APPENDBUFFER(lex_ctx, x);
  56712. }
  56713. duk__internbuffer(lex_ctx, lex_ctx->slot1_idx);
  56714. out_token->str1 = duk_get_hstring((duk_context *) lex_ctx->thr, lex_ctx->slot1_idx);
  56715. /* second, parse flags */
  56716. DUK__INITBUFFER(lex_ctx);
  56717. for (;;) {
  56718. x = DUK__L0();
  56719. if (!duk_unicode_is_identifier_part(x)) {
  56720. break;
  56721. }
  56722. x = DUK__L0(); /* re-read to avoid spill / fetch */
  56723. DUK__APPENDBUFFER(lex_ctx, x);
  56724. DUK__ADVANCE(lex_ctx, 1);
  56725. }
  56726. duk__internbuffer(lex_ctx, lex_ctx->slot2_idx);
  56727. out_token->str2 = duk_get_hstring((duk_context *) lex_ctx->thr, lex_ctx->slot2_idx);
  56728. DUK__INITBUFFER(lex_ctx); /* free some memory */
  56729. /* validation of the regexp is caller's responsibility */
  56730. advtok = DUK__ADVTOK(0, DUK_TOK_REGEXP);
  56731. #else
  56732. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR, "regexp support disabled");
  56733. #endif
  56734. } else if (y == '=') {
  56735. /* "/=" and not in regexp mode */
  56736. advtok = DUK__ADVTOK(2, DUK_TOK_DIV_EQ);
  56737. } else {
  56738. /* "/" and not in regexp mode */
  56739. advtok = DUK__ADVTOK(1, DUK_TOK_DIV);
  56740. }
  56741. } else if (x == '{') {
  56742. advtok = DUK__ADVTOK(1, DUK_TOK_LCURLY);
  56743. } else if (x == '}') {
  56744. advtok = DUK__ADVTOK(1, DUK_TOK_RCURLY);
  56745. } else if (x == '(') {
  56746. advtok = DUK__ADVTOK(1, DUK_TOK_LPAREN);
  56747. } else if (x == ')') {
  56748. advtok = DUK__ADVTOK(1, DUK_TOK_RPAREN);
  56749. } else if (x == '[') {
  56750. advtok = DUK__ADVTOK(1, DUK_TOK_LBRACKET);
  56751. } else if (x == ']') {
  56752. advtok = DUK__ADVTOK(1, DUK_TOK_RBRACKET);
  56753. } else if (x == '.' && !DUK__ISDIGIT(y)) {
  56754. /* Note: period followed by a digit can only start DecimalLiteral (captured below) */
  56755. advtok = DUK__ADVTOK(1, DUK_TOK_PERIOD);
  56756. } else if (x == ';') {
  56757. advtok = DUK__ADVTOK(1, DUK_TOK_SEMICOLON);
  56758. } else if (x == ',') {
  56759. advtok = DUK__ADVTOK(1, DUK_TOK_COMMA);
  56760. } else if (x == '<') {
  56761. if (y == '<' && DUK__L2() == '=') {
  56762. advtok = DUK__ADVTOK(3, DUK_TOK_ALSHIFT_EQ);
  56763. } else if (y == '=') {
  56764. advtok = DUK__ADVTOK(2, DUK_TOK_LE);
  56765. } else if (y == '<') {
  56766. advtok = DUK__ADVTOK(2, DUK_TOK_ALSHIFT);
  56767. } else {
  56768. advtok = DUK__ADVTOK(1, DUK_TOK_LT);
  56769. }
  56770. } else if (x == '>') {
  56771. if (y == '>' && DUK__L2() == '>' && DUK__L3() == '=') {
  56772. advtok = DUK__ADVTOK(4, DUK_TOK_RSHIFT_EQ);
  56773. } else if (y == '>' && DUK__L2() == '>') {
  56774. advtok = DUK__ADVTOK(3, DUK_TOK_RSHIFT);
  56775. } else if (y == '>' && DUK__L2() == '=') {
  56776. advtok = DUK__ADVTOK(3, DUK_TOK_ARSHIFT_EQ);
  56777. } else if (y == '=') {
  56778. advtok = DUK__ADVTOK(2, DUK_TOK_GE);
  56779. } else if (y == '>') {
  56780. advtok = DUK__ADVTOK(2, DUK_TOK_ARSHIFT);
  56781. } else {
  56782. advtok = DUK__ADVTOK(1, DUK_TOK_GT);
  56783. }
  56784. } else if (x == '=') {
  56785. if (y == '=' && DUK__L2() == '=') {
  56786. advtok = DUK__ADVTOK(3, DUK_TOK_SEQ);
  56787. } else if (y == '=') {
  56788. advtok = DUK__ADVTOK(2, DUK_TOK_EQ);
  56789. } else {
  56790. advtok = DUK__ADVTOK(1, DUK_TOK_EQUALSIGN);
  56791. }
  56792. } else if (x == '!') {
  56793. if (y == '=' && DUK__L2() == '=') {
  56794. advtok = DUK__ADVTOK(3, DUK_TOK_SNEQ);
  56795. } else if (y == '=') {
  56796. advtok = DUK__ADVTOK(2, DUK_TOK_NEQ);
  56797. } else {
  56798. advtok = DUK__ADVTOK(1, DUK_TOK_LNOT);
  56799. }
  56800. } else if (x == '+') {
  56801. if (y == '+') {
  56802. advtok = DUK__ADVTOK(2, DUK_TOK_INCREMENT);
  56803. } else if (y == '=') {
  56804. advtok = DUK__ADVTOK(2, DUK_TOK_ADD_EQ);
  56805. } else {
  56806. advtok = DUK__ADVTOK(1, DUK_TOK_ADD);
  56807. }
  56808. } else if (x == '-') {
  56809. if (y == '-') {
  56810. advtok = DUK__ADVTOK(2, DUK_TOK_DECREMENT);
  56811. } else if (y == '=') {
  56812. advtok = DUK__ADVTOK(2, DUK_TOK_SUB_EQ);
  56813. } else {
  56814. advtok = DUK__ADVTOK(1, DUK_TOK_SUB);
  56815. }
  56816. } else if (x == '*') {
  56817. if (y == '=') {
  56818. advtok = DUK__ADVTOK(2, DUK_TOK_MUL_EQ);
  56819. } else {
  56820. advtok = DUK__ADVTOK(1, DUK_TOK_MUL);
  56821. }
  56822. } else if (x == '%') {
  56823. if (y == '=') {
  56824. advtok = DUK__ADVTOK(2, DUK_TOK_MOD_EQ);
  56825. } else {
  56826. advtok = DUK__ADVTOK(1, DUK_TOK_MOD);
  56827. }
  56828. } else if (x == '&') {
  56829. if (y == '&') {
  56830. advtok = DUK__ADVTOK(2, DUK_TOK_LAND);
  56831. } else if (y == '=') {
  56832. advtok = DUK__ADVTOK(2, DUK_TOK_BAND_EQ);
  56833. } else {
  56834. advtok = DUK__ADVTOK(1, DUK_TOK_BAND);
  56835. }
  56836. } else if (x == '|') {
  56837. if (y == '|') {
  56838. advtok = DUK__ADVTOK(2, DUK_TOK_LOR);
  56839. } else if (y == '=') {
  56840. advtok = DUK__ADVTOK(2, DUK_TOK_BOR_EQ);
  56841. } else {
  56842. advtok = DUK__ADVTOK(1, DUK_TOK_BOR);
  56843. }
  56844. } else if (x == '^') {
  56845. if (y == '=') {
  56846. advtok = DUK__ADVTOK(2, DUK_TOK_BXOR_EQ);
  56847. } else {
  56848. advtok = DUK__ADVTOK(1, DUK_TOK_BXOR);
  56849. }
  56850. } else if (x == '~') {
  56851. advtok = DUK__ADVTOK(1, DUK_TOK_BNOT);
  56852. } else if (x == '?') {
  56853. advtok = DUK__ADVTOK(1, DUK_TOK_QUESTION);
  56854. } else if (x == ':') {
  56855. advtok = DUK__ADVTOK(1, DUK_TOK_COLON);
  56856. } else if (duk_unicode_is_line_terminator(x)) {
  56857. if (x == 0x000d && y == 0x000a) {
  56858. /*
  56859. * E5 Section 7.3: CR LF is detected as a single line terminator for
  56860. * line numbers. Here we also detect it as a single line terminator
  56861. * token.
  56862. */
  56863. advtok = DUK__ADVTOK(2, DUK_TOK_LINETERM);
  56864. } else {
  56865. advtok = DUK__ADVTOK(1, DUK_TOK_LINETERM);
  56866. }
  56867. } else if (duk_unicode_is_identifier_start(x) || x == '\\') {
  56868. /*
  56869. * Parse an identifier and then check whether it is:
  56870. * - reserved word (keyword or other reserved word)
  56871. * - "null" (NullLiteral)
  56872. * - "true" (BooleanLiteral)
  56873. * - "false" (BooleanLiteral)
  56874. * - anything else => identifier
  56875. *
  56876. * This does not follow the E5 productions cleanly, but is
  56877. * useful and compact.
  56878. *
  56879. * Note that identifiers may contain Unicode escapes,
  56880. * see E5 Sections 6 and 7.6. They must be decoded first,
  56881. * and the result checked against allowed characters.
  56882. * The above if-clause accepts an identifier start and an
  56883. * '\' character -- no other token can begin with a '\'.
  56884. *
  56885. * Note that "get" and "set" are not reserved words in E5
  56886. * specification so they are recognized as plain identifiers
  56887. * (the tokens DUK_TOK_GET and DUK_TOK_SET are actually not
  56888. * used now). The compiler needs to work around this.
  56889. *
  56890. * Strictly speaking, following Ecmascript longest match
  56891. * specification, an invalid escape for the first character
  56892. * should cause a syntax error. However, an invalid escape
  56893. * for IdentifierParts should just terminate the identifier
  56894. * early (longest match), and let the next tokenization
  56895. * fail. For instance Rhino croaks with 'foo\z' when
  56896. * parsing the identifier. This has little practical impact.
  56897. */
  56898. duk_small_int_t i, i_end;
  56899. duk_bool_t first = 1;
  56900. duk_hstring *str;
  56901. DUK__INITBUFFER(lex_ctx);
  56902. for (;;) {
  56903. /* re-lookup first char on first loop */
  56904. if (DUK__L0() == '\\') {
  56905. duk_codepoint_t ch;
  56906. if (DUK__L1() != 'u') {
  56907. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  56908. "invalid unicode escape while parsing identifier");
  56909. }
  56910. ch = duk__decode_uniesc_from_window(lex_ctx, 2);
  56911. /* IdentifierStart is stricter than IdentifierPart, so if the first
  56912. * character is escaped, must have a stricter check here.
  56913. */
  56914. if (!(first ? duk_unicode_is_identifier_start(ch) : duk_unicode_is_identifier_part(ch))) {
  56915. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  56916. "invalid unicode escaped character while parsing identifier");
  56917. }
  56918. DUK__APPENDBUFFER(lex_ctx, ch);
  56919. DUK__ADVANCE(lex_ctx, 6);
  56920. /* Track number of escapes: necessary for proper keyword
  56921. * detection.
  56922. */
  56923. out_token->num_escapes++;
  56924. } else {
  56925. /* Note: first character is checked against this. But because
  56926. * IdentifierPart includes all IdentifierStart characters, and
  56927. * the first character (if unescaped) has already been checked
  56928. * in the if condition, this is OK.
  56929. */
  56930. if (!duk_unicode_is_identifier_part(DUK__L0())) {
  56931. break;
  56932. }
  56933. DUK__APPENDBUFFER(lex_ctx, DUK__L0());
  56934. DUK__ADVANCE(lex_ctx, 1);
  56935. }
  56936. first = 0;
  56937. }
  56938. duk__internbuffer(lex_ctx, lex_ctx->slot1_idx);
  56939. out_token->str1 = duk_get_hstring((duk_context *) lex_ctx->thr, lex_ctx->slot1_idx);
  56940. str = out_token->str1;
  56941. DUK_ASSERT(str != NULL);
  56942. out_token->t_nores = DUK_TOK_IDENTIFIER;
  56943. DUK__INITBUFFER(lex_ctx); /* free some memory */
  56944. /*
  56945. * Interned identifier is compared against reserved words, which are
  56946. * currently interned into the heap context. See genstrings.py.
  56947. *
  56948. * Note that an escape in the identifier disables recognition of
  56949. * keywords; e.g. "\u0069f = 1;" is a valid statement (assigns to
  56950. * identifier named "if"). This is not necessarily compliant,
  56951. * see test-dec-escaped-char-in-keyword.js.
  56952. *
  56953. * Note: "get" and "set" are awkward. They are not officially
  56954. * ReservedWords (and indeed e.g. "var set = 1;" is valid), and
  56955. * must come out as DUK_TOK_IDENTIFIER. The compiler needs to
  56956. * work around this a bit.
  56957. */
  56958. /* XXX: optimize by adding the token numbers directly into the
  56959. * always interned duk_hstring objects (there should be enough
  56960. * flag bits free for that)?
  56961. */
  56962. i_end = (strict_mode ? DUK_STRIDX_END_RESERVED : DUK_STRIDX_START_STRICT_RESERVED);
  56963. advtok = DUK__ADVTOK(0, DUK_TOK_IDENTIFIER);
  56964. if (out_token->num_escapes == 0) {
  56965. for (i = DUK_STRIDX_START_RESERVED; i < i_end; i++) {
  56966. DUK_ASSERT(i >= 0 && i < DUK_HEAP_NUM_STRINGS);
  56967. if (DUK_HTHREAD_GET_STRING(lex_ctx->thr, i) == str) {
  56968. advtok = DUK__ADVTOK(0, DUK_STRIDX_TO_TOK(i));
  56969. break;
  56970. }
  56971. }
  56972. }
  56973. } else if (DUK__ISDIGIT(x) || (x == '.')) {
  56974. /* Note: decimal number may start with a period, but must be followed by a digit */
  56975. /*
  56976. * DecimalLiteral, HexIntegerLiteral, OctalIntegerLiteral
  56977. * "pre-parsing", followed by an actual, accurate parser step.
  56978. *
  56979. * Note: the leading sign character ('+' or '-') is -not- part of
  56980. * the production in E5 grammar, and that the a DecimalLiteral
  56981. * starting with a '0' must be followed by a non-digit. Leading
  56982. * zeroes are syntax errors and must be checked for.
  56983. *
  56984. * XXX: the two step parsing process is quite awkward, it would
  56985. * be more straightforward to allow numconv to parse the longest
  56986. * valid prefix (it already does that, it only needs to indicate
  56987. * where the input ended). However, the lexer decodes characters
  56988. * using a lookup window, so this is not a trivial change.
  56989. */
  56990. /* XXX: because of the final check below (that the literal is not
  56991. * followed by a digit), this could maybe be simplified, if we bail
  56992. * out early from a leading zero (and if there are no periods etc).
  56993. * Maybe too complex.
  56994. */
  56995. duk_double_t val;
  56996. duk_bool_t int_only = 0;
  56997. duk_bool_t allow_hex = 0;
  56998. duk_small_int_t state; /* 0=before period/exp,
  56999. * 1=after period, before exp
  57000. * 2=after exp, allow '+' or '-'
  57001. * 3=after exp and exp sign
  57002. */
  57003. duk_small_uint_t s2n_flags;
  57004. DUK__INITBUFFER(lex_ctx);
  57005. if (x == '0' && (y == 'x' || y == 'X')) {
  57006. DUK__APPENDBUFFER(lex_ctx, x);
  57007. DUK__APPENDBUFFER(lex_ctx, y);
  57008. DUK__ADVANCE(lex_ctx, 2);
  57009. int_only = 1;
  57010. allow_hex = 1;
  57011. #ifdef DUK_USE_OCTAL_SUPPORT
  57012. } else if (!strict_mode && x == '0' && DUK__ISDIGIT(y)) {
  57013. /* Note: if DecimalLiteral starts with a '0', it can only be
  57014. * followed by a period or an exponent indicator which starts
  57015. * with 'e' or 'E'. Hence the if-check above ensures that
  57016. * OctalIntegerLiteral is the only valid NumericLiteral
  57017. * alternative at this point (even if y is, say, '9').
  57018. */
  57019. DUK__APPENDBUFFER(lex_ctx, x);
  57020. DUK__ADVANCE(lex_ctx, 1);
  57021. int_only = 1;
  57022. #endif
  57023. }
  57024. state = 0;
  57025. for (;;) {
  57026. x = DUK__L0(); /* re-lookup curr char on first round */
  57027. if (DUK__ISDIGIT(x)) {
  57028. /* Note: intentionally allow leading zeroes here, as the
  57029. * actual parser will check for them.
  57030. */
  57031. if (state == 2) {
  57032. state = 3;
  57033. }
  57034. } else if (allow_hex && DUK__ISHEXDIGIT(x)) {
  57035. /* Note: 'e' and 'E' are also accepted here. */
  57036. ;
  57037. } else if (x == '.') {
  57038. if (state >= 1 || int_only) {
  57039. break;
  57040. } else {
  57041. state = 1;
  57042. }
  57043. } else if (x == 'e' || x == 'E') {
  57044. if (state >= 2 || int_only) {
  57045. break;
  57046. } else {
  57047. state = 2;
  57048. }
  57049. } else if (x == '-' || x == '+') {
  57050. if (state != 2) {
  57051. break;
  57052. } else {
  57053. state = 3;
  57054. }
  57055. } else {
  57056. break;
  57057. }
  57058. DUK__APPENDBUFFER(lex_ctx, x);
  57059. DUK__ADVANCE(lex_ctx, 1);
  57060. }
  57061. /* XXX: better coercion */
  57062. duk__internbuffer(lex_ctx, lex_ctx->slot1_idx);
  57063. s2n_flags = DUK_S2N_FLAG_ALLOW_EXP |
  57064. DUK_S2N_FLAG_ALLOW_FRAC |
  57065. DUK_S2N_FLAG_ALLOW_NAKED_FRAC |
  57066. DUK_S2N_FLAG_ALLOW_EMPTY_FRAC |
  57067. #ifdef DUK_USE_OCTAL_SUPPORT
  57068. (strict_mode ? 0 : DUK_S2N_FLAG_ALLOW_AUTO_OCT_INT) |
  57069. #endif
  57070. DUK_S2N_FLAG_ALLOW_AUTO_HEX_INT;
  57071. duk_dup((duk_context *) lex_ctx->thr, lex_ctx->slot1_idx);
  57072. duk_numconv_parse((duk_context *) lex_ctx->thr, 10 /*radix*/, s2n_flags);
  57073. val = duk_to_number((duk_context *) lex_ctx->thr, -1);
  57074. if (DUK_ISNAN(val)) {
  57075. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR, "invalid numeric literal");
  57076. }
  57077. duk_replace((duk_context *) lex_ctx->thr, lex_ctx->slot1_idx); /* could also just pop? */
  57078. DUK__INITBUFFER(lex_ctx); /* free some memory */
  57079. /* Section 7.8.3 (note): NumericLiteral must be followed by something other than
  57080. * IdentifierStart or DecimalDigit.
  57081. */
  57082. if (DUK__ISDIGIT(DUK__L0()) || duk_unicode_is_identifier_start(DUK__L0())) {
  57083. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR, "invalid numeric literal");
  57084. }
  57085. out_token->num = val;
  57086. advtok = DUK__ADVTOK(0, DUK_TOK_NUMBER);
  57087. } else if (x == '"' || x == '\'') {
  57088. duk_small_int_t quote = x; /* Note: duk_uint8_t type yields larger code */
  57089. duk_small_int_t adv;
  57090. DUK__INITBUFFER(lex_ctx);
  57091. for (;;) {
  57092. DUK__ADVANCE(lex_ctx, 1); /* eat opening quote on first loop */
  57093. x = DUK__L0();
  57094. if (x < 0 || duk_unicode_is_line_terminator(x)) {
  57095. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57096. "eof or line terminator while parsing string literal");
  57097. }
  57098. if (x == quote) {
  57099. DUK__ADVANCE(lex_ctx, 1); /* eat closing quote */
  57100. break;
  57101. }
  57102. if (x == '\\') {
  57103. /* DUK__L0 -> '\' char
  57104. * DUK__L1 ... DUK__L5 -> more lookup
  57105. */
  57106. x = DUK__L1();
  57107. y = DUK__L2();
  57108. /* How much to advance before next loop; note that next loop
  57109. * will advance by 1 anyway, so -1 from the total escape
  57110. * length (e.g. len('\uXXXX') - 1 = 6 - 1). As a default,
  57111. * 1 is good.
  57112. */
  57113. adv = 2 - 1; /* note: long live range */
  57114. if (x < 0) {
  57115. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57116. "eof while parsing string literal");
  57117. }
  57118. if (duk_unicode_is_line_terminator(x)) {
  57119. /* line continuation */
  57120. if (x == 0x000d && y == 0x000a) {
  57121. /* CR LF again a special case */
  57122. adv = 3 - 1;
  57123. }
  57124. } else if (x == '\'') {
  57125. DUK__APPENDBUFFER(lex_ctx, 0x0027);
  57126. } else if (x == '"') {
  57127. DUK__APPENDBUFFER(lex_ctx, 0x0022);
  57128. } else if (x == '\\') {
  57129. DUK__APPENDBUFFER(lex_ctx, 0x005c);
  57130. } else if (x == 'b') {
  57131. DUK__APPENDBUFFER(lex_ctx, 0x0008);
  57132. } else if (x == 'f') {
  57133. DUK__APPENDBUFFER(lex_ctx, 0x000c);
  57134. } else if (x == 'n') {
  57135. DUK__APPENDBUFFER(lex_ctx, 0x000a);
  57136. } else if (x == 'r') {
  57137. DUK__APPENDBUFFER(lex_ctx, 0x000d);
  57138. } else if (x == 't') {
  57139. DUK__APPENDBUFFER(lex_ctx, 0x0009);
  57140. } else if (x == 'v') {
  57141. DUK__APPENDBUFFER(lex_ctx, 0x000b);
  57142. } else if (x == 'x') {
  57143. adv = 4 - 1;
  57144. DUK__APPENDBUFFER(lex_ctx, duk__decode_hexesc_from_window(lex_ctx, 2));
  57145. } else if (x == 'u') {
  57146. adv = 6 - 1;
  57147. DUK__APPENDBUFFER(lex_ctx, duk__decode_uniesc_from_window(lex_ctx, 2));
  57148. } else if (DUK__ISDIGIT(x)) {
  57149. duk_codepoint_t ch = 0; /* initialized to avoid warnings of unused var */
  57150. /*
  57151. * Octal escape or zero escape:
  57152. * \0 (lookahead not DecimalDigit)
  57153. * \1 ... \7 (lookahead not DecimalDigit)
  57154. * \ZeroToThree OctalDigit (lookahead not DecimalDigit)
  57155. * \FourToSeven OctalDigit (no lookahead restrictions)
  57156. * \ZeroToThree OctalDigit OctalDigit (no lookahead restrictions)
  57157. *
  57158. * Zero escape is part of the standard syntax. Octal escapes are
  57159. * defined in E5 Section B.1.2, and are only allowed in non-strict mode.
  57160. * Any other productions starting with a decimal digit are invalid.
  57161. */
  57162. if (x == '0' && !DUK__ISDIGIT(y)) {
  57163. /* Zero escape (also allowed in non-strict mode) */
  57164. ch = 0;
  57165. /* adv = 2 - 1 default OK */
  57166. #ifdef DUK_USE_OCTAL_SUPPORT
  57167. } else if (strict_mode) {
  57168. /* No other escape beginning with a digit in strict mode */
  57169. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57170. "invalid escape while parsing string literal");
  57171. } else if (DUK__ISDIGIT03(x) && DUK__ISOCTDIGIT(y) && DUK__ISOCTDIGIT(DUK__L3())) {
  57172. /* Three digit octal escape, digits validated. */
  57173. adv = 4 - 1;
  57174. ch = (duk__hexval(lex_ctx, x) << 6) +
  57175. (duk__hexval(lex_ctx, y) << 3) +
  57176. duk__hexval(lex_ctx, DUK__L3());
  57177. } else if (((DUK__ISDIGIT03(x) && !DUK__ISDIGIT(DUK__L3())) || DUK__ISDIGIT47(x)) &&
  57178. DUK__ISOCTDIGIT(y)) {
  57179. /* Two digit octal escape, digits validated.
  57180. *
  57181. * The if-condition is a bit tricky. We could catch e.g.
  57182. * '\039' in the three-digit escape and fail it there (by
  57183. * validating the digits), but we want to avoid extra
  57184. * additional validation code.
  57185. */
  57186. adv = 3 - 1;
  57187. ch = (duk__hexval(lex_ctx, x) << 3) +
  57188. duk__hexval(lex_ctx, y);
  57189. } else if (DUK__ISDIGIT(x) && !DUK__ISDIGIT(y)) {
  57190. /* One digit octal escape, digit validated. */
  57191. /* adv = 2 default OK */
  57192. ch = duk__hexval(lex_ctx, x);
  57193. #else
  57194. /* fall through to error */
  57195. #endif
  57196. } else {
  57197. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57198. "invalid escape while parsing string literal");
  57199. }
  57200. DUK__APPENDBUFFER(lex_ctx, ch);
  57201. } else {
  57202. /* escaped NonEscapeCharacter */
  57203. DUK__APPENDBUFFER(lex_ctx, x);
  57204. }
  57205. DUK__ADVANCE(lex_ctx, adv);
  57206. /* Track number of escapes; count not really needed but directive
  57207. * prologues need to detect whether there were any escapes or line
  57208. * continuations or not.
  57209. */
  57210. out_token->num_escapes++;
  57211. } else {
  57212. /* part of string */
  57213. DUK__APPENDBUFFER(lex_ctx, x);
  57214. }
  57215. }
  57216. duk__internbuffer(lex_ctx, lex_ctx->slot1_idx);
  57217. out_token->str1 = duk_get_hstring((duk_context *) lex_ctx->thr, lex_ctx->slot1_idx);
  57218. DUK__INITBUFFER(lex_ctx); /* free some memory */
  57219. advtok = DUK__ADVTOK(0, DUK_TOK_STRING);
  57220. } else if (x < 0) {
  57221. advtok = DUK__ADVTOK(0, DUK_TOK_EOF);
  57222. } else {
  57223. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR, "error parsing token");
  57224. }
  57225. /*
  57226. * Shared exit path
  57227. */
  57228. DUK__ADVANCE(lex_ctx, advtok >> 8);
  57229. out_token->t = advtok & 0xff;
  57230. if (out_token->t_nores < 0) {
  57231. out_token->t_nores = out_token->t;
  57232. }
  57233. }
  57234. /*
  57235. * Tokenize input until a non-whitespace, non-lineterm token is found.
  57236. * Note in the output token whether a lineterm token preceded the starting
  57237. * point (inclusive) and the result token. This information is needed for
  57238. * automatic semicolon insertion.
  57239. *
  57240. * Future work:
  57241. *
  57242. * * Merge with duk__parse_input_element_raw() because only this function is
  57243. * called in practice.
  57244. */
  57245. /* XXX: change mode flags into one flags argument? */
  57246. DUK_INTERNAL
  57247. void duk_lexer_parse_js_input_element(duk_lexer_ctx *lex_ctx,
  57248. duk_token *out_token,
  57249. duk_bool_t strict_mode,
  57250. duk_bool_t regexp_mode) {
  57251. duk_small_int_t tok;
  57252. duk_bool_t got_lineterm = 0; /* got lineterm preceding non-whitespace, non-lineterm token */
  57253. for (;;) {
  57254. duk__parse_input_element_raw(lex_ctx, out_token, strict_mode, regexp_mode);
  57255. tok = out_token->t;
  57256. DUK_DDD(DUK_DDDPRINT("RAWTOKEN: %ld (line %ld)",
  57257. (long) tok, (long) out_token->start_line));
  57258. if (tok == DUK_TOK_COMMENT) {
  57259. /* single-line comment or multi-line comment without an internal lineterm */
  57260. continue;
  57261. } else if (tok == DUK_TOK_LINETERM) {
  57262. /* lineterm or multi-line comment with an internal lineterm */
  57263. got_lineterm = 1;
  57264. continue;
  57265. } else {
  57266. break;
  57267. }
  57268. }
  57269. out_token->lineterm = got_lineterm;
  57270. /* Automatic semicolon insertion is allowed if a token is preceded
  57271. * by line terminator(s), or terminates a statement list (right curly
  57272. * or EOF).
  57273. */
  57274. if (got_lineterm || tok == DUK_TOK_RCURLY || tok == DUK_TOK_EOF) {
  57275. out_token->allow_auto_semi = 1;
  57276. } else {
  57277. out_token->allow_auto_semi = 0;
  57278. }
  57279. }
  57280. #ifdef DUK_USE_REGEXP_SUPPORT
  57281. /*
  57282. * Parse a RegExp token. The grammar is described in E5 Section 15.10.
  57283. * Terminal constructions (such as quantifiers) are parsed directly here.
  57284. *
  57285. * 0xffffffffU is used as a marker for "infinity" in quantifiers. Further,
  57286. * DUK__MAX_RE_QUANT_DIGITS limits the maximum number of digits that
  57287. * will be accepted for a quantifier.
  57288. */
  57289. DUK_INTERNAL void duk_lexer_parse_re_token(duk_lexer_ctx *lex_ctx, duk_re_token *out_token) {
  57290. duk_small_int_t advtok = 0; /* init is unnecessary but suppresses "may be used uninitialized" warnings */
  57291. duk_codepoint_t x, y;
  57292. if (++lex_ctx->token_count >= lex_ctx->token_limit) {
  57293. DUK_ERROR(lex_ctx->thr, DUK_ERR_RANGE_ERROR, "token limit");
  57294. return; /* unreachable */
  57295. }
  57296. DUK_MEMZERO(out_token, sizeof(*out_token));
  57297. x = DUK__L0();
  57298. y = DUK__L1();
  57299. DUK_DDD(DUK_DDDPRINT("parsing regexp token, L0=%ld, L1=%ld", (long) x, (long) y));
  57300. switch (x) {
  57301. case '|': {
  57302. advtok = DUK__ADVTOK(1, DUK_RETOK_DISJUNCTION);
  57303. break;
  57304. }
  57305. case '^': {
  57306. advtok = DUK__ADVTOK(1, DUK_RETOK_ASSERT_START);
  57307. break;
  57308. }
  57309. case '$': {
  57310. advtok = DUK__ADVTOK(1, DUK_RETOK_ASSERT_END);
  57311. break;
  57312. }
  57313. case '?': {
  57314. out_token->qmin = 0;
  57315. out_token->qmax = 1;
  57316. if (y == '?') {
  57317. advtok = DUK__ADVTOK(2, DUK_RETOK_QUANTIFIER);
  57318. out_token->greedy = 0;
  57319. } else {
  57320. advtok = DUK__ADVTOK(1, DUK_RETOK_QUANTIFIER);
  57321. out_token->greedy = 1;
  57322. }
  57323. break;
  57324. }
  57325. case '*': {
  57326. out_token->qmin = 0;
  57327. out_token->qmax = DUK_RE_QUANTIFIER_INFINITE;
  57328. if (y == '?') {
  57329. advtok = DUK__ADVTOK(2, DUK_RETOK_QUANTIFIER);
  57330. out_token->greedy = 0;
  57331. } else {
  57332. advtok = DUK__ADVTOK(1, DUK_RETOK_QUANTIFIER);
  57333. out_token->greedy = 1;
  57334. }
  57335. break;
  57336. }
  57337. case '+': {
  57338. out_token->qmin = 1;
  57339. out_token->qmax = DUK_RE_QUANTIFIER_INFINITE;
  57340. if (y == '?') {
  57341. advtok = DUK__ADVTOK(2, DUK_RETOK_QUANTIFIER);
  57342. out_token->greedy = 0;
  57343. } else {
  57344. advtok = DUK__ADVTOK(1, DUK_RETOK_QUANTIFIER);
  57345. out_token->greedy = 1;
  57346. }
  57347. break;
  57348. }
  57349. case '{': {
  57350. /* Production allows 'DecimalDigits', including leading zeroes */
  57351. duk_uint_fast32_t val1 = 0;
  57352. duk_uint_fast32_t val2 = DUK_RE_QUANTIFIER_INFINITE;
  57353. duk_small_int_t digits = 0;
  57354. for (;;) {
  57355. DUK__ADVANCE(lex_ctx, 1); /* eat '{' on entry */
  57356. x = DUK__L0();
  57357. if (DUK__ISDIGIT(x)) {
  57358. if (digits >= DUK__MAX_RE_QUANT_DIGITS) {
  57359. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57360. "invalid regexp quantifier (too many digits)");
  57361. }
  57362. digits++;
  57363. val1 = val1 * 10 + (duk_uint_fast32_t) duk__hexval(lex_ctx, x);
  57364. } else if (x == ',') {
  57365. if (val2 != DUK_RE_QUANTIFIER_INFINITE) {
  57366. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57367. "invalid regexp quantifier (double comma)");
  57368. }
  57369. if (DUK__L1() == '}') {
  57370. /* form: { DecimalDigits , }, val1 = min count */
  57371. if (digits == 0) {
  57372. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57373. "invalid regexp quantifier (missing digits)");
  57374. }
  57375. out_token->qmin = val1;
  57376. out_token->qmax = DUK_RE_QUANTIFIER_INFINITE;
  57377. DUK__ADVANCE(lex_ctx, 2);
  57378. break;
  57379. }
  57380. val2 = val1;
  57381. val1 = 0;
  57382. digits = 0; /* not strictly necessary because of lookahead '}' above */
  57383. } else if (x == '}') {
  57384. if (digits == 0) {
  57385. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57386. "invalid regexp quantifier (missing digits)");
  57387. }
  57388. if (val2 != DUK_RE_QUANTIFIER_INFINITE) {
  57389. /* val2 = min count, val1 = max count */
  57390. out_token->qmin = val2;
  57391. out_token->qmax = val1;
  57392. } else {
  57393. /* val1 = count */
  57394. out_token->qmin = val1;
  57395. out_token->qmax = val1;
  57396. }
  57397. DUK__ADVANCE(lex_ctx, 1);
  57398. break;
  57399. } else {
  57400. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57401. "invalid regexp quantifier (unknown char)");
  57402. }
  57403. }
  57404. if (DUK__L0() == '?') {
  57405. out_token->greedy = 0;
  57406. DUK__ADVANCE(lex_ctx, 1);
  57407. } else {
  57408. out_token->greedy = 1;
  57409. }
  57410. advtok = DUK__ADVTOK(0, DUK_RETOK_QUANTIFIER);
  57411. break;
  57412. }
  57413. case '.': {
  57414. advtok = DUK__ADVTOK(1, DUK_RETOK_ATOM_PERIOD);
  57415. break;
  57416. }
  57417. case '\\': {
  57418. /* The E5.1 specification does not seem to allow IdentifierPart characters
  57419. * to be used as identity escapes. Unfortunately this includes '$', which
  57420. * cannot be escaped as '\$'; it needs to be escaped e.g. as '\u0024'.
  57421. * Many other implementations (including V8 and Rhino, for instance) do
  57422. * accept '\$' as a valid identity escape, which is quite pragmatic.
  57423. * See: test-regexp-identity-escape-dollar.js.
  57424. */
  57425. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_CHAR); /* default: char escape (two chars) */
  57426. if (y == 'b') {
  57427. advtok = DUK__ADVTOK(2, DUK_RETOK_ASSERT_WORD_BOUNDARY);
  57428. } else if (y == 'B') {
  57429. advtok = DUK__ADVTOK(2, DUK_RETOK_ASSERT_NOT_WORD_BOUNDARY);
  57430. } else if (y == 'f') {
  57431. out_token->num = 0x000c;
  57432. } else if (y == 'n') {
  57433. out_token->num = 0x000a;
  57434. } else if (y == 't') {
  57435. out_token->num = 0x0009;
  57436. } else if (y == 'r') {
  57437. out_token->num = 0x000d;
  57438. } else if (y == 'v') {
  57439. out_token->num = 0x000b;
  57440. } else if (y == 'c') {
  57441. x = DUK__L2();
  57442. if ((x >= 'a' && x <= 'z') ||
  57443. (x >= 'A' && x <= 'Z')) {
  57444. out_token->num = (x % 32);
  57445. advtok = DUK__ADVTOK(3, DUK_RETOK_ATOM_CHAR);
  57446. } else {
  57447. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57448. "invalid regexp control escape");
  57449. }
  57450. } else if (y == 'x') {
  57451. out_token->num = duk__decode_hexesc_from_window(lex_ctx, 2);
  57452. advtok = DUK__ADVTOK(4, DUK_RETOK_ATOM_CHAR);
  57453. } else if (y == 'u') {
  57454. out_token->num = duk__decode_uniesc_from_window(lex_ctx, 2);
  57455. advtok = DUK__ADVTOK(6, DUK_RETOK_ATOM_CHAR);
  57456. } else if (y == 'd') {
  57457. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_DIGIT);
  57458. } else if (y == 'D') {
  57459. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_NOT_DIGIT);
  57460. } else if (y == 's') {
  57461. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_WHITE);
  57462. } else if (y == 'S') {
  57463. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_NOT_WHITE);
  57464. } else if (y == 'w') {
  57465. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_WORD_CHAR);
  57466. } else if (y == 'W') {
  57467. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_NOT_WORD_CHAR);
  57468. } else if (DUK__ISDIGIT(y)) {
  57469. /* E5 Section 15.10.2.11 */
  57470. if (y == '0') {
  57471. if (DUK__ISDIGIT(DUK__L2())) {
  57472. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57473. "invalid regexp escape");
  57474. }
  57475. out_token->num = 0x0000;
  57476. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_CHAR);
  57477. } else {
  57478. /* XXX: shared parsing? */
  57479. duk_uint_fast32_t val = 0;
  57480. duk_small_int_t i;
  57481. for (i = 0; ; i++) {
  57482. if (i >= DUK__MAX_RE_DECESC_DIGITS) {
  57483. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57484. "invalid regexp escape (decimal escape too long)");
  57485. }
  57486. DUK__ADVANCE(lex_ctx, 1); /* eat backslash on entry */
  57487. x = DUK__L0();
  57488. if (!DUK__ISDIGIT(x)) {
  57489. break;
  57490. }
  57491. val = val * 10 + (duk_uint_fast32_t) duk__hexval(lex_ctx, x);
  57492. }
  57493. /* DUK__L0() cannot be a digit, because the loop doesn't terminate if it is */
  57494. advtok = DUK__ADVTOK(0, DUK_RETOK_ATOM_BACKREFERENCE);
  57495. out_token->num = val;
  57496. }
  57497. } else if ((y >= 0 && !duk_unicode_is_identifier_part(y)) ||
  57498. #if defined(DUK_USE_NONSTD_REGEXP_DOLLAR_ESCAPE)
  57499. y == '$' ||
  57500. #endif
  57501. y == DUK_UNICODE_CP_ZWNJ ||
  57502. y == DUK_UNICODE_CP_ZWJ) {
  57503. /* IdentityEscape, with dollar added as a valid additional
  57504. * non-standard escape (see test-regexp-identity-escape-dollar.js).
  57505. * Careful not to match end-of-buffer (<0) here.
  57506. */
  57507. out_token->num = y;
  57508. } else {
  57509. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57510. "invalid regexp escape");
  57511. }
  57512. break;
  57513. }
  57514. case '(': {
  57515. /* XXX: naming is inconsistent: ATOM_END_GROUP ends an ASSERT_START_LOOKAHEAD */
  57516. if (y == '?') {
  57517. if (DUK__L2() == '=') {
  57518. /* (?= */
  57519. advtok = DUK__ADVTOK(3, DUK_RETOK_ASSERT_START_POS_LOOKAHEAD);
  57520. } else if (DUK__L2() == '!') {
  57521. /* (?! */
  57522. advtok = DUK__ADVTOK(3, DUK_RETOK_ASSERT_START_NEG_LOOKAHEAD);
  57523. } else if (DUK__L2() == ':') {
  57524. /* (?: */
  57525. advtok = DUK__ADVTOK(3, DUK_RETOK_ATOM_START_NONCAPTURE_GROUP);
  57526. }
  57527. } else {
  57528. /* ( */
  57529. advtok = DUK__ADVTOK(1, DUK_RETOK_ATOM_START_CAPTURE_GROUP);
  57530. }
  57531. break;
  57532. }
  57533. case ')': {
  57534. advtok = DUK__ADVTOK(1, DUK_RETOK_ATOM_END_GROUP);
  57535. break;
  57536. }
  57537. case '[': {
  57538. /*
  57539. * To avoid creating a heavy intermediate value for the list of ranges,
  57540. * only the start token ('[' or '[^') is parsed here. The regexp
  57541. * compiler parses the ranges itself.
  57542. */
  57543. advtok = DUK__ADVTOK(1, DUK_RETOK_ATOM_START_CHARCLASS);
  57544. if (y == '^') {
  57545. advtok = DUK__ADVTOK(2, DUK_RETOK_ATOM_START_CHARCLASS_INVERTED);
  57546. }
  57547. break;
  57548. }
  57549. case ']':
  57550. case '}': {
  57551. /* Although these could be parsed as PatternCharacters unambiguously (here),
  57552. * E5 Section 15.10.1 grammar explicitly forbids these as PatternCharacters.
  57553. */
  57554. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57555. "invalid regexp character");
  57556. break;
  57557. }
  57558. case -1: {
  57559. /* EOF */
  57560. advtok = DUK__ADVTOK(0, DUK_TOK_EOF);
  57561. break;
  57562. }
  57563. default: {
  57564. /* PatternCharacter, all excluded characters are matched by cases above */
  57565. advtok = DUK__ADVTOK(1, DUK_RETOK_ATOM_CHAR);
  57566. out_token->num = x;
  57567. break;
  57568. }
  57569. }
  57570. /*
  57571. * Shared exit path
  57572. */
  57573. DUK__ADVANCE(lex_ctx, advtok >> 8);
  57574. out_token->t = advtok & 0xff;
  57575. }
  57576. /*
  57577. * Special parser for character classes; calls callback for every
  57578. * range parsed and returns the number of ranges present.
  57579. */
  57580. /* XXX: this duplicates functionality in duk_regexp.c where a similar loop is
  57581. * required anyway. We could use that BUT we need to update the regexp compiler
  57582. * 'nranges' too. Work this out a bit more cleanly to save space.
  57583. */
  57584. /* XXX: the handling of character range detection is a bit convoluted.
  57585. * Try to simplify and make smaller.
  57586. */
  57587. /* XXX: logic for handling character ranges is now incorrect, it will accept
  57588. * e.g. [\d-z] whereas it should croak from it? SMJS accepts this too, though.
  57589. *
  57590. * Needs a read through and a lot of additional tests.
  57591. */
  57592. DUK_LOCAL
  57593. void duk__emit_u16_direct_ranges(duk_lexer_ctx *lex_ctx,
  57594. duk_re_range_callback gen_range,
  57595. void *userdata,
  57596. duk_uint16_t *ranges,
  57597. duk_small_int_t num) {
  57598. duk_uint16_t *ranges_end;
  57599. DUK_UNREF(lex_ctx);
  57600. ranges_end = ranges + num;
  57601. while (ranges < ranges_end) {
  57602. /* mark range 'direct', bypass canonicalization (see Wiki) */
  57603. gen_range(userdata, (duk_codepoint_t) ranges[0], (duk_codepoint_t) ranges[1], 1);
  57604. ranges += 2;
  57605. }
  57606. }
  57607. DUK_INTERNAL void duk_lexer_parse_re_ranges(duk_lexer_ctx *lex_ctx, duk_re_range_callback gen_range, void *userdata) {
  57608. duk_codepoint_t start = -1;
  57609. duk_codepoint_t ch;
  57610. duk_codepoint_t x;
  57611. duk_bool_t dash = 0;
  57612. DUK_DD(DUK_DDPRINT("parsing regexp ranges"));
  57613. for (;;) {
  57614. x = DUK__L0();
  57615. DUK__ADVANCE(lex_ctx, 1);
  57616. ch = -1; /* not strictly necessary, but avoids "uninitialized variable" warnings */
  57617. DUK_UNREF(ch);
  57618. if (x < 0) {
  57619. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57620. "eof while parsing character class");
  57621. } else if (x == ']') {
  57622. DUK_ASSERT(!dash); /* lookup should prevent this */
  57623. if (start >= 0) {
  57624. gen_range(userdata, start, start, 0);
  57625. }
  57626. break;
  57627. } else if (x == '-') {
  57628. if (start >= 0 && !dash && DUK__L0() != ']') {
  57629. /* '-' as a range indicator */
  57630. dash = 1;
  57631. continue;
  57632. } else {
  57633. /* '-' verbatim */
  57634. ch = x;
  57635. }
  57636. } else if (x == '\\') {
  57637. /*
  57638. * The escapes are same as outside a character class, except that \b has a
  57639. * different meaning, and \B and backreferences are prohibited (see E5
  57640. * Section 15.10.2.19). However, it's difficult to share code because we
  57641. * handle e.g. "\n" very differently: here we generate a single character
  57642. * range for it.
  57643. */
  57644. x = DUK__L0();
  57645. DUK__ADVANCE(lex_ctx, 1);
  57646. if (x == 'b') {
  57647. /* Note: '\b' in char class is different than outside (assertion),
  57648. * '\B' is not allowed and is caught by the duk_unicode_is_identifier_part()
  57649. * check below.
  57650. */
  57651. ch = 0x0008;
  57652. } else if (x == 'f') {
  57653. ch = 0x000c;
  57654. } else if (x == 'n') {
  57655. ch = 0x000a;
  57656. } else if (x == 't') {
  57657. ch = 0x0009;
  57658. } else if (x == 'r') {
  57659. ch = 0x000d;
  57660. } else if (x == 'v') {
  57661. ch = 0x000b;
  57662. } else if (x == 'c') {
  57663. x = DUK__L0();
  57664. DUK__ADVANCE(lex_ctx, 1);
  57665. if ((x >= 'a' && x <= 'z') ||
  57666. (x >= 'A' && x <= 'Z')) {
  57667. ch = (x % 32);
  57668. } else {
  57669. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57670. "invalid regexp control escape");
  57671. return; /* never reached, but avoids warnings of
  57672. * potentially unused variables.
  57673. */
  57674. }
  57675. } else if (x == 'x') {
  57676. ch = duk__decode_hexesc_from_window(lex_ctx, 0);
  57677. DUK__ADVANCE(lex_ctx, 2);
  57678. } else if (x == 'u') {
  57679. ch = duk__decode_uniesc_from_window(lex_ctx, 0);
  57680. DUK__ADVANCE(lex_ctx, 4);
  57681. } else if (x == 'd') {
  57682. duk__emit_u16_direct_ranges(lex_ctx,
  57683. gen_range,
  57684. userdata,
  57685. duk_unicode_re_ranges_digit,
  57686. sizeof(duk_unicode_re_ranges_digit) / sizeof(duk_uint16_t));
  57687. ch = -1;
  57688. } else if (x == 'D') {
  57689. duk__emit_u16_direct_ranges(lex_ctx,
  57690. gen_range,
  57691. userdata,
  57692. duk_unicode_re_ranges_not_digit,
  57693. sizeof(duk_unicode_re_ranges_not_digit) / sizeof(duk_uint16_t));
  57694. ch = -1;
  57695. } else if (x == 's') {
  57696. duk__emit_u16_direct_ranges(lex_ctx,
  57697. gen_range,
  57698. userdata,
  57699. duk_unicode_re_ranges_white,
  57700. sizeof(duk_unicode_re_ranges_white) / sizeof(duk_uint16_t));
  57701. ch = -1;
  57702. } else if (x == 'S') {
  57703. duk__emit_u16_direct_ranges(lex_ctx,
  57704. gen_range,
  57705. userdata,
  57706. duk_unicode_re_ranges_not_white,
  57707. sizeof(duk_unicode_re_ranges_not_white) / sizeof(duk_uint16_t));
  57708. ch = -1;
  57709. } else if (x == 'w') {
  57710. duk__emit_u16_direct_ranges(lex_ctx,
  57711. gen_range,
  57712. userdata,
  57713. duk_unicode_re_ranges_wordchar,
  57714. sizeof(duk_unicode_re_ranges_wordchar) / sizeof(duk_uint16_t));
  57715. ch = -1;
  57716. } else if (x == 'W') {
  57717. duk__emit_u16_direct_ranges(lex_ctx,
  57718. gen_range,
  57719. userdata,
  57720. duk_unicode_re_ranges_not_wordchar,
  57721. sizeof(duk_unicode_re_ranges_not_wordchar) / sizeof(duk_uint16_t));
  57722. ch = -1;
  57723. } else if (DUK__ISDIGIT(x)) {
  57724. /* DecimalEscape, only \0 is allowed, no leading zeroes are allowed */
  57725. if (x == '0' && !DUK__ISDIGIT(DUK__L0())) {
  57726. ch = 0x0000;
  57727. } else {
  57728. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57729. "invalid decimal escape");
  57730. }
  57731. } else if (!duk_unicode_is_identifier_part(x)
  57732. #if defined(DUK_USE_NONSTD_REGEXP_DOLLAR_ESCAPE)
  57733. || x == '$'
  57734. #endif
  57735. ) {
  57736. /* IdentityEscape */
  57737. ch = x;
  57738. } else {
  57739. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57740. "invalid regexp escape");
  57741. }
  57742. } else {
  57743. /* character represents itself */
  57744. ch = x;
  57745. }
  57746. /* ch is a literal character here or -1 if parsed entity was
  57747. * an escape such as "\s".
  57748. */
  57749. if (ch < 0) {
  57750. /* multi-character sets not allowed as part of ranges, see
  57751. * E5 Section 15.10.2.15, abstract operation CharacterRange.
  57752. */
  57753. if (start >= 0) {
  57754. if (dash) {
  57755. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57756. "invalid range");
  57757. } else {
  57758. gen_range(userdata, start, start, 0);
  57759. start = -1;
  57760. /* dash is already 0 */
  57761. }
  57762. }
  57763. } else {
  57764. if (start >= 0) {
  57765. if (dash) {
  57766. if (start > ch) {
  57767. DUK_ERROR(lex_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  57768. "invalid range");
  57769. }
  57770. gen_range(userdata, start, ch, 0);
  57771. start = -1;
  57772. dash = 0;
  57773. } else {
  57774. gen_range(userdata, start, start, 0);
  57775. start = ch;
  57776. /* dash is already 0 */
  57777. }
  57778. } else {
  57779. start = ch;
  57780. }
  57781. }
  57782. }
  57783. return;
  57784. }
  57785. #endif /* DUK_USE_REGEXP_SUPPORT */
  57786. #line 1 "duk_numconv.c"
  57787. /*
  57788. * Number-to-string and string-to-number conversions.
  57789. *
  57790. * Slow path number-to-string and string-to-number conversion is based on
  57791. * a Dragon4 variant, with fast paths for small integers. Big integer
  57792. * arithmetic is needed for guaranteeing that the conversion is correct
  57793. * and uses a minimum number of digits. The big number arithmetic has a
  57794. * fixed maximum size and does not require dynamic allocations.
  57795. *
  57796. * See: doc/number-conversion.txt.
  57797. */
  57798. /* include removed: duk_internal.h */
  57799. #define DUK__IEEE_DOUBLE_EXP_BIAS 1023
  57800. #define DUK__IEEE_DOUBLE_EXP_MIN (-1022) /* biased exp == 0 -> denormal, exp -1022 */
  57801. #define DUK__DIGITCHAR(x) duk_lc_digits[(x)]
  57802. /*
  57803. * Tables generated with src/gennumdigits.py.
  57804. *
  57805. * duk__str2num_digits_for_radix indicates, for each radix, how many input
  57806. * digits should be considered significant for string-to-number conversion.
  57807. * The input is also padded to this many digits to give the Dragon4
  57808. * conversion enough (apparent) precision to work with.
  57809. *
  57810. * duk__str2num_exp_limits indicates, for each radix, the radix-specific
  57811. * minimum/maximum exponent values (for a Dragon4 integer mantissa)
  57812. * below and above which the number is guaranteed to underflow to zero
  57813. * or overflow to Infinity. This allows parsing to keep bigint values
  57814. * bounded.
  57815. */
  57816. DUK_LOCAL const duk_uint8_t duk__str2num_digits_for_radix[] = {
  57817. 69, 44, 35, 30, 27, 25, 23, 22, 20, 20, /* 2 to 11 */
  57818. 20, 19, 19, 18, 18, 17, 17, 17, 16, 16, /* 12 to 21 */
  57819. 16, 16, 16, 15, 15, 15, 15, 15, 15, 14, /* 22 to 31 */
  57820. 14, 14, 14, 14, 14 /* 31 to 36 */
  57821. };
  57822. typedef struct {
  57823. duk_int16_t upper;
  57824. duk_int16_t lower;
  57825. } duk__exp_limits;
  57826. DUK_LOCAL const duk__exp_limits duk__str2num_exp_limits[] = {
  57827. { 957, -1147 }, { 605, -725 }, { 479, -575 }, { 414, -496 },
  57828. { 372, -446 }, { 342, -411 }, { 321, -384 }, { 304, -364 },
  57829. { 291, -346 }, { 279, -334 }, { 268, -323 }, { 260, -312 },
  57830. { 252, -304 }, { 247, -296 }, { 240, -289 }, { 236, -283 },
  57831. { 231, -278 }, { 227, -273 }, { 223, -267 }, { 220, -263 },
  57832. { 216, -260 }, { 213, -256 }, { 210, -253 }, { 208, -249 },
  57833. { 205, -246 }, { 203, -244 }, { 201, -241 }, { 198, -239 },
  57834. { 196, -237 }, { 195, -234 }, { 193, -232 }, { 191, -230 },
  57835. { 190, -228 }, { 188, -226 }, { 187, -225 },
  57836. };
  57837. /*
  57838. * Limited functionality bigint implementation.
  57839. *
  57840. * Restricted to non-negative numbers with less than 32 * DUK__BI_MAX_PARTS bits,
  57841. * with the caller responsible for ensuring this is never exceeded. No memory
  57842. * allocation (except stack) is needed for bigint computation. Operations
  57843. * have been tailored for number conversion needs.
  57844. *
  57845. * Argument order is "assignment order", i.e. target first, then arguments:
  57846. * x <- y * z --> duk__bi_mul(x, y, z);
  57847. */
  57848. /* This upper value has been experimentally determined; debug build will check
  57849. * bigint size with assertions.
  57850. */
  57851. #define DUK__BI_MAX_PARTS 37 /* 37x32 = 1184 bits */
  57852. #ifdef DUK_USE_DDDPRINT
  57853. #define DUK__BI_PRINT(name,x) duk__bi_print((name),(x))
  57854. #else
  57855. #define DUK__BI_PRINT(name,x)
  57856. #endif
  57857. /* Current size is about 152 bytes. */
  57858. typedef struct {
  57859. duk_small_int_t n;
  57860. duk_uint32_t v[DUK__BI_MAX_PARTS]; /* low to high */
  57861. } duk__bigint;
  57862. #ifdef DUK_USE_DDDPRINT
  57863. DUK_LOCAL void duk__bi_print(const char *name, duk__bigint *x) {
  57864. /* Overestimate required size; debug code so not critical to be tight. */
  57865. char buf[DUK__BI_MAX_PARTS * 9 + 64];
  57866. char *p = buf;
  57867. duk_small_int_t i;
  57868. /* No NUL term checks in this debug code. */
  57869. p += DUK_SPRINTF(p, "%p n=%ld", (void *) x, (long) x->n);
  57870. if (x->n == 0) {
  57871. p += DUK_SPRINTF(p, " 0");
  57872. }
  57873. for (i = x->n - 1; i >= 0; i--) {
  57874. p += DUK_SPRINTF(p, " %08lx", (unsigned long) x->v[i]);
  57875. }
  57876. DUK_DDD(DUK_DDDPRINT("%s: %s", (const char *) name, (const char *) buf));
  57877. }
  57878. #endif
  57879. #ifdef DUK_USE_ASSERTIONS
  57880. DUK_LOCAL duk_small_int_t duk__bi_is_valid(duk__bigint *x) {
  57881. return (duk_small_int_t)
  57882. ( ((x->n >= 0) && (x->n <= DUK__BI_MAX_PARTS)) /* is valid size */ &&
  57883. ((x->n == 0) || (x->v[x->n - 1] != 0)) /* is normalized */ );
  57884. }
  57885. #endif
  57886. DUK_LOCAL void duk__bi_normalize(duk__bigint *x) {
  57887. duk_small_int_t i;
  57888. for (i = x->n - 1; i >= 0; i--) {
  57889. if (x->v[i] != 0) {
  57890. break;
  57891. }
  57892. }
  57893. /* Note: if 'x' is zero, x->n becomes 0 here */
  57894. x->n = i + 1;
  57895. DUK_ASSERT(duk__bi_is_valid(x));
  57896. }
  57897. /* x <- y */
  57898. DUK_LOCAL void duk__bi_copy(duk__bigint *x, duk__bigint *y) {
  57899. duk_small_int_t n;
  57900. n = y->n;
  57901. x->n = n;
  57902. if (n == 0) {
  57903. return;
  57904. }
  57905. DUK_MEMCPY((void *) x->v, (void *) y->v, (size_t) (sizeof(duk_uint32_t) * n));
  57906. }
  57907. DUK_LOCAL void duk__bi_set_small(duk__bigint *x, duk_uint32_t v) {
  57908. if (v == 0U) {
  57909. x->n = 0;
  57910. } else {
  57911. x->n = 1;
  57912. x->v[0] = v;
  57913. }
  57914. DUK_ASSERT(duk__bi_is_valid(x));
  57915. }
  57916. /* Return value: <0 <=> x < y
  57917. * 0 <=> x == y
  57918. * >0 <=> x > y
  57919. */
  57920. DUK_LOCAL int duk__bi_compare(duk__bigint *x, duk__bigint *y) {
  57921. duk_small_int_t i, nx, ny;
  57922. duk_uint32_t tx, ty;
  57923. DUK_ASSERT(duk__bi_is_valid(x));
  57924. DUK_ASSERT(duk__bi_is_valid(y));
  57925. nx = x->n;
  57926. ny = y->n;
  57927. if (nx > ny) {
  57928. goto ret_gt;
  57929. }
  57930. if (nx < ny) {
  57931. goto ret_lt;
  57932. }
  57933. for (i = nx - 1; i >= 0; i--) {
  57934. tx = x->v[i];
  57935. ty = y->v[i];
  57936. if (tx > ty) {
  57937. goto ret_gt;
  57938. }
  57939. if (tx < ty) {
  57940. goto ret_lt;
  57941. }
  57942. }
  57943. return 0;
  57944. ret_gt:
  57945. return 1;
  57946. ret_lt:
  57947. return -1;
  57948. }
  57949. /* x <- y + z */
  57950. #ifdef DUK_USE_64BIT_OPS
  57951. DUK_LOCAL void duk__bi_add(duk__bigint *x, duk__bigint *y, duk__bigint *z) {
  57952. duk_uint64_t tmp;
  57953. duk_small_int_t i, ny, nz;
  57954. DUK_ASSERT(duk__bi_is_valid(y));
  57955. DUK_ASSERT(duk__bi_is_valid(z));
  57956. if (z->n > y->n) {
  57957. duk__bigint *t;
  57958. t = y; y = z; z = t;
  57959. }
  57960. DUK_ASSERT(y->n >= z->n);
  57961. ny = y->n; nz = z->n;
  57962. tmp = 0U;
  57963. for (i = 0; i < ny; i++) {
  57964. DUK_ASSERT(i < DUK__BI_MAX_PARTS);
  57965. tmp += y->v[i];
  57966. if (i < nz) {
  57967. tmp += z->v[i];
  57968. }
  57969. x->v[i] = (duk_uint32_t) (tmp & 0xffffffffUL);
  57970. tmp = tmp >> 32;
  57971. }
  57972. if (tmp != 0U) {
  57973. DUK_ASSERT(i < DUK__BI_MAX_PARTS);
  57974. x->v[i++] = (duk_uint32_t) tmp;
  57975. }
  57976. x->n = i;
  57977. DUK_ASSERT(x->n <= DUK__BI_MAX_PARTS);
  57978. /* no need to normalize */
  57979. DUK_ASSERT(duk__bi_is_valid(x));
  57980. }
  57981. #else /* DUK_USE_64BIT_OPS */
  57982. DUK_LOCAL void duk__bi_add(duk__bigint *x, duk__bigint *y, duk__bigint *z) {
  57983. duk_uint32_t carry, tmp1, tmp2;
  57984. duk_small_int_t i, ny, nz;
  57985. DUK_ASSERT(duk__bi_is_valid(y));
  57986. DUK_ASSERT(duk__bi_is_valid(z));
  57987. if (z->n > y->n) {
  57988. duk__bigint *t;
  57989. t = y; y = z; z = t;
  57990. }
  57991. DUK_ASSERT(y->n >= z->n);
  57992. ny = y->n; nz = z->n;
  57993. carry = 0U;
  57994. for (i = 0; i < ny; i++) {
  57995. /* Carry is detected based on wrapping which relies on exact 32-bit
  57996. * types.
  57997. */
  57998. DUK_ASSERT(i < DUK__BI_MAX_PARTS);
  57999. tmp1 = y->v[i];
  58000. tmp2 = tmp1;
  58001. if (i < nz) {
  58002. tmp2 += z->v[i];
  58003. }
  58004. /* Careful with carry condition:
  58005. * - If carry not added: 0x12345678 + 0 + 0xffffffff = 0x12345677 (< 0x12345678)
  58006. * - If carry added: 0x12345678 + 1 + 0xffffffff = 0x12345678 (== 0x12345678)
  58007. */
  58008. if (carry) {
  58009. tmp2++;
  58010. carry = (tmp2 <= tmp1 ? 1U : 0U);
  58011. } else {
  58012. carry = (tmp2 < tmp1 ? 1U : 0U);
  58013. }
  58014. x->v[i] = tmp2;
  58015. }
  58016. if (carry) {
  58017. DUK_ASSERT(i < DUK__BI_MAX_PARTS);
  58018. DUK_ASSERT(carry == 1U);
  58019. x->v[i++] = carry;
  58020. }
  58021. x->n = i;
  58022. DUK_ASSERT(x->n <= DUK__BI_MAX_PARTS);
  58023. /* no need to normalize */
  58024. DUK_ASSERT(duk__bi_is_valid(x));
  58025. }
  58026. #endif /* DUK_USE_64BIT_OPS */
  58027. /* x <- y + z */
  58028. DUK_LOCAL void duk__bi_add_small(duk__bigint *x, duk__bigint *y, duk_uint32_t z) {
  58029. duk__bigint tmp;
  58030. DUK_ASSERT(duk__bi_is_valid(y));
  58031. /* XXX: this could be optimized; there is only one call site now though */
  58032. duk__bi_set_small(&tmp, z);
  58033. duk__bi_add(x, y, &tmp);
  58034. DUK_ASSERT(duk__bi_is_valid(x));
  58035. }
  58036. #if 0 /* unused */
  58037. /* x <- x + y, use t as temp */
  58038. DUK_LOCAL void duk__bi_add_copy(duk__bigint *x, duk__bigint *y, duk__bigint *t) {
  58039. duk__bi_add(t, x, y);
  58040. duk__bi_copy(x, t);
  58041. }
  58042. #endif
  58043. /* x <- y - z, require x >= y => z >= 0, i.e. y >= z */
  58044. #ifdef DUK_USE_64BIT_OPS
  58045. DUK_LOCAL void duk__bi_sub(duk__bigint *x, duk__bigint *y, duk__bigint *z) {
  58046. duk_small_int_t i, ny, nz;
  58047. duk_uint32_t ty, tz;
  58048. duk_int64_t tmp;
  58049. DUK_ASSERT(duk__bi_is_valid(y));
  58050. DUK_ASSERT(duk__bi_is_valid(z));
  58051. DUK_ASSERT(duk__bi_compare(y, z) >= 0);
  58052. DUK_ASSERT(y->n >= z->n);
  58053. ny = y->n; nz = z->n;
  58054. tmp = 0;
  58055. for (i = 0; i < ny; i++) {
  58056. ty = y->v[i];
  58057. if (i < nz) {
  58058. tz = z->v[i];
  58059. } else {
  58060. tz = 0;
  58061. }
  58062. tmp = (duk_int64_t) ty - (duk_int64_t) tz + tmp;
  58063. x->v[i] = (duk_uint32_t) (tmp & 0xffffffffUL);
  58064. tmp = tmp >> 32; /* 0 or -1 */
  58065. }
  58066. DUK_ASSERT(tmp == 0);
  58067. x->n = i;
  58068. duk__bi_normalize(x); /* need to normalize, may even cancel to 0 */
  58069. DUK_ASSERT(duk__bi_is_valid(x));
  58070. }
  58071. #else
  58072. DUK_LOCAL void duk__bi_sub(duk__bigint *x, duk__bigint *y, duk__bigint *z) {
  58073. duk_small_int_t i, ny, nz;
  58074. duk_uint32_t tmp1, tmp2, borrow;
  58075. DUK_ASSERT(duk__bi_is_valid(y));
  58076. DUK_ASSERT(duk__bi_is_valid(z));
  58077. DUK_ASSERT(duk__bi_compare(y, z) >= 0);
  58078. DUK_ASSERT(y->n >= z->n);
  58079. ny = y->n; nz = z->n;
  58080. borrow = 0U;
  58081. for (i = 0; i < ny; i++) {
  58082. /* Borrow is detected based on wrapping which relies on exact 32-bit
  58083. * types.
  58084. */
  58085. tmp1 = y->v[i];
  58086. tmp2 = tmp1;
  58087. if (i < nz) {
  58088. tmp2 -= z->v[i];
  58089. }
  58090. /* Careful with borrow condition:
  58091. * - If borrow not subtracted: 0x12345678 - 0 - 0xffffffff = 0x12345679 (> 0x12345678)
  58092. * - If borrow subtracted: 0x12345678 - 1 - 0xffffffff = 0x12345678 (== 0x12345678)
  58093. */
  58094. if (borrow) {
  58095. tmp2--;
  58096. borrow = (tmp2 >= tmp1 ? 1U : 0U);
  58097. } else {
  58098. borrow = (tmp2 > tmp1 ? 1U : 0U);
  58099. }
  58100. x->v[i] = tmp2;
  58101. }
  58102. DUK_ASSERT(borrow == 0U);
  58103. x->n = i;
  58104. duk__bi_normalize(x); /* need to normalize, may even cancel to 0 */
  58105. DUK_ASSERT(duk__bi_is_valid(x));
  58106. }
  58107. #endif
  58108. #if 0 /* unused */
  58109. /* x <- y - z */
  58110. DUK_LOCAL void duk__bi_sub_small(duk__bigint *x, duk__bigint *y, duk_uint32_t z) {
  58111. duk__bigint tmp;
  58112. DUK_ASSERT(duk__bi_is_valid(y));
  58113. /* XXX: this could be optimized */
  58114. duk__bi_set_small(&tmp, z);
  58115. duk__bi_sub(x, y, &tmp);
  58116. DUK_ASSERT(duk__bi_is_valid(x));
  58117. }
  58118. #endif
  58119. /* x <- x - y, use t as temp */
  58120. DUK_LOCAL void duk__bi_sub_copy(duk__bigint *x, duk__bigint *y, duk__bigint *t) {
  58121. duk__bi_sub(t, x, y);
  58122. duk__bi_copy(x, t);
  58123. }
  58124. /* x <- y * z */
  58125. DUK_LOCAL void duk__bi_mul(duk__bigint *x, duk__bigint *y, duk__bigint *z) {
  58126. duk_small_int_t i, j, nx, nz;
  58127. DUK_ASSERT(duk__bi_is_valid(y));
  58128. DUK_ASSERT(duk__bi_is_valid(z));
  58129. nx = y->n + z->n; /* max possible */
  58130. DUK_ASSERT(nx <= DUK__BI_MAX_PARTS);
  58131. if (nx == 0) {
  58132. /* Both inputs are zero; cases where only one is zero can go
  58133. * through main algorithm.
  58134. */
  58135. x->n = 0;
  58136. return;
  58137. }
  58138. DUK_MEMZERO((void *) x->v, (size_t) (sizeof(duk_uint32_t) * nx));
  58139. x->n = nx;
  58140. nz = z->n;
  58141. for (i = 0; i < y->n; i++) {
  58142. #ifdef DUK_USE_64BIT_OPS
  58143. duk_uint64_t tmp = 0U;
  58144. for (j = 0; j < nz; j++) {
  58145. tmp += (duk_uint64_t) y->v[i] * (duk_uint64_t) z->v[j] + x->v[i+j];
  58146. x->v[i+j] = (duk_uint32_t) (tmp & 0xffffffffUL);
  58147. tmp = tmp >> 32;
  58148. }
  58149. if (tmp > 0) {
  58150. DUK_ASSERT(i + j < nx);
  58151. DUK_ASSERT(i + j < DUK__BI_MAX_PARTS);
  58152. DUK_ASSERT(x->v[i+j] == 0U);
  58153. x->v[i+j] = (duk_uint32_t) tmp;
  58154. }
  58155. #else
  58156. /*
  58157. * Multiply + add + carry for 32-bit components using only 16x16->32
  58158. * multiplies and carry detection based on unsigned overflow.
  58159. *
  58160. * 1st mult, 32-bit: (A*2^16 + B)
  58161. * 2nd mult, 32-bit: (C*2^16 + D)
  58162. * 3rd add, 32-bit: E
  58163. * 4th add, 32-bit: F
  58164. *
  58165. * (AC*2^16 + B) * (C*2^16 + D) + E + F
  58166. * = AC*2^32 + AD*2^16 + BC*2^16 + BD + E + F
  58167. * = AC*2^32 + (AD + BC)*2^16 + (BD + E + F)
  58168. * = AC*2^32 + AD*2^16 + BC*2^16 + (BD + E + F)
  58169. */
  58170. duk_uint32_t a, b, c, d, e, f;
  58171. duk_uint32_t r, s, t;
  58172. a = y->v[i]; b = a & 0xffffUL; a = a >> 16;
  58173. f = 0;
  58174. for (j = 0; j < nz; j++) {
  58175. c = z->v[j]; d = c & 0xffffUL; c = c >> 16;
  58176. e = x->v[i+j];
  58177. /* build result as: (r << 32) + s: start with (BD + E + F) */
  58178. r = 0;
  58179. s = b * d;
  58180. /* add E */
  58181. t = s + e;
  58182. if (t < s) { r++; } /* carry */
  58183. s = t;
  58184. /* add F */
  58185. t = s + f;
  58186. if (t < s) { r++; } /* carry */
  58187. s = t;
  58188. /* add BC*2^16 */
  58189. t = b * c;
  58190. r += (t >> 16);
  58191. t = s + ((t & 0xffffUL) << 16);
  58192. if (t < s) { r++; } /* carry */
  58193. s = t;
  58194. /* add AD*2^16 */
  58195. t = a * d;
  58196. r += (t >> 16);
  58197. t = s + ((t & 0xffffUL) << 16);
  58198. if (t < s) { r++; } /* carry */
  58199. s = t;
  58200. /* add AC*2^32 */
  58201. t = a * c;
  58202. r += t;
  58203. DUK_DDD(DUK_DDDPRINT("ab=%08lx cd=%08lx ef=%08lx -> rs=%08lx %08lx",
  58204. (unsigned long) y->v[i], (unsigned long) z->v[j],
  58205. (unsigned long) x->v[i+j], (unsigned long) r,
  58206. (unsigned long) s));
  58207. x->v[i+j] = s;
  58208. f = r;
  58209. }
  58210. if (f > 0U) {
  58211. DUK_ASSERT(i + j < nx);
  58212. DUK_ASSERT(i + j < DUK__BI_MAX_PARTS);
  58213. DUK_ASSERT(x->v[i+j] == 0U);
  58214. x->v[i+j] = (duk_uint32_t) f;
  58215. }
  58216. #endif /* DUK_USE_64BIT_OPS */
  58217. }
  58218. duk__bi_normalize(x);
  58219. DUK_ASSERT(duk__bi_is_valid(x));
  58220. }
  58221. /* x <- y * z */
  58222. DUK_LOCAL void duk__bi_mul_small(duk__bigint *x, duk__bigint *y, duk_uint32_t z) {
  58223. duk__bigint tmp;
  58224. DUK_ASSERT(duk__bi_is_valid(y));
  58225. /* XXX: this could be optimized */
  58226. duk__bi_set_small(&tmp, z);
  58227. duk__bi_mul(x, y, &tmp);
  58228. DUK_ASSERT(duk__bi_is_valid(x));
  58229. }
  58230. /* x <- x * y, use t as temp */
  58231. DUK_LOCAL void duk__bi_mul_copy(duk__bigint *x, duk__bigint *y, duk__bigint *t) {
  58232. duk__bi_mul(t, x, y);
  58233. duk__bi_copy(x, t);
  58234. }
  58235. /* x <- x * y, use t as temp */
  58236. DUK_LOCAL void duk__bi_mul_small_copy(duk__bigint *x, duk_uint32_t y, duk__bigint *t) {
  58237. duk__bi_mul_small(t, x, y);
  58238. duk__bi_copy(x, t);
  58239. }
  58240. DUK_LOCAL int duk__bi_is_even(duk__bigint *x) {
  58241. DUK_ASSERT(duk__bi_is_valid(x));
  58242. return (x->n == 0) || ((x->v[0] & 0x01) == 0);
  58243. }
  58244. DUK_LOCAL int duk__bi_is_zero(duk__bigint *x) {
  58245. DUK_ASSERT(duk__bi_is_valid(x));
  58246. return (x->n == 0); /* this is the case for normalized numbers */
  58247. }
  58248. /* Bigint is 2^52. Used to detect normalized IEEE double mantissa values
  58249. * which are at the lowest edge (next floating point value downwards has
  58250. * a different exponent). The lowest mantissa has the form:
  58251. *
  58252. * 1000........000 (52 zeroes; only "hidden bit" is set)
  58253. */
  58254. DUK_LOCAL duk_small_int_t duk__bi_is_2to52(duk__bigint *x) {
  58255. DUK_ASSERT(duk__bi_is_valid(x));
  58256. return (duk_small_int_t)
  58257. (x->n == 2) && (x->v[0] == 0U) && (x->v[1] == (1U << (52-32)));
  58258. }
  58259. /* x <- (1<<y) */
  58260. DUK_LOCAL void duk__bi_twoexp(duk__bigint *x, duk_small_int_t y) {
  58261. duk_small_int_t n, r;
  58262. n = (y / 32) + 1;
  58263. DUK_ASSERT(n > 0);
  58264. r = y % 32;
  58265. DUK_MEMZERO((void *) x->v, sizeof(duk_uint32_t) * n);
  58266. x->n = n;
  58267. x->v[n - 1] = (((duk_uint32_t) 1) << r);
  58268. }
  58269. /* x <- b^y; use t1 and t2 as temps */
  58270. DUK_LOCAL void duk__bi_exp_small(duk__bigint *x, duk_small_int_t b, duk_small_int_t y, duk__bigint *t1, duk__bigint *t2) {
  58271. /* Fast path the binary case */
  58272. DUK_ASSERT(x != t1 && x != t2 && t1 != t2); /* distinct bignums, easy mistake to make */
  58273. DUK_ASSERT(b >= 0);
  58274. DUK_ASSERT(y >= 0);
  58275. if (b == 2) {
  58276. duk__bi_twoexp(x, y);
  58277. return;
  58278. }
  58279. /* http://en.wikipedia.org/wiki/Exponentiation_by_squaring */
  58280. DUK_DDD(DUK_DDDPRINT("exp_small: b=%ld, y=%ld", (long) b, (long) y));
  58281. duk__bi_set_small(x, 1);
  58282. duk__bi_set_small(t1, b);
  58283. for (;;) {
  58284. /* Loop structure ensures that we don't compute t1^2 unnecessarily
  58285. * on the final round, as that might create a bignum exceeding the
  58286. * current DUK__BI_MAX_PARTS limit.
  58287. */
  58288. if (y & 0x01) {
  58289. duk__bi_mul_copy(x, t1, t2);
  58290. }
  58291. y = y >> 1;
  58292. if (y == 0) {
  58293. break;
  58294. }
  58295. duk__bi_mul_copy(t1, t1, t2);
  58296. }
  58297. DUK__BI_PRINT("exp_small result", x);
  58298. }
  58299. /*
  58300. * A Dragon4 number-to-string variant, based on:
  58301. *
  58302. * Guy L. Steele Jr., Jon L. White: "How to Print Floating-Point Numbers
  58303. * Accurately"
  58304. *
  58305. * Robert G. Burger, R. Kent Dybvig: "Printing Floating-Point Numbers
  58306. * Quickly and Accurately"
  58307. *
  58308. * The current algorithm is based on Figure 1 of the Burger-Dybvig paper,
  58309. * i.e. the base implementation without logarithm estimation speedups
  58310. * (these would increase code footprint considerably). Fixed-format output
  58311. * does not follow the suggestions in the paper; instead, we generate an
  58312. * extra digit and round-with-carry.
  58313. *
  58314. * The same algorithm is used for number parsing (with b=10 and B=2)
  58315. * by generating one extra digit and doing rounding manually.
  58316. *
  58317. * See doc/number-conversion.txt for limitations.
  58318. */
  58319. /* Maximum number of digits generated. */
  58320. #define DUK__MAX_OUTPUT_DIGITS 1040 /* (Number.MAX_VALUE).toString(2).length == 1024, + spare */
  58321. /* Maximum number of characters in formatted value. */
  58322. #define DUK__MAX_FORMATTED_LENGTH 1040 /* (-Number.MAX_VALUE).toString(2).length == 1025, + spare */
  58323. /* Number and (minimum) size of bigints in the nc_ctx structure. */
  58324. #define DUK__NUMCONV_CTX_NUM_BIGINTS 7
  58325. #define DUK__NUMCONV_CTX_BIGINTS_SIZE (sizeof(duk__bigint) * DUK__NUMCONV_CTX_NUM_BIGINTS)
  58326. typedef struct {
  58327. /* Currently about 7*152 = 1064 bytes. The space for these
  58328. * duk__bigints is used also as a temporary buffer for generating
  58329. * the final string. This is a bit awkard; a union would be
  58330. * more correct.
  58331. */
  58332. duk__bigint f, r, s, mp, mm, t1, t2;
  58333. duk_small_int_t is_s2n; /* if 1, doing a string-to-number; else doing a number-to-string */
  58334. duk_small_int_t is_fixed; /* if 1, doing a fixed format output (not free format) */
  58335. duk_small_int_t req_digits; /* requested number of output digits; 0 = free-format */
  58336. duk_small_int_t abs_pos; /* digit position is absolute, not relative */
  58337. duk_small_int_t e; /* exponent for 'f' */
  58338. duk_small_int_t b; /* input radix */
  58339. duk_small_int_t B; /* output radix */
  58340. duk_small_int_t k; /* see algorithm */
  58341. duk_small_int_t low_ok; /* see algorithm */
  58342. duk_small_int_t high_ok; /* see algorithm */
  58343. duk_small_int_t unequal_gaps; /* m+ != m- (very rarely) */
  58344. /* Buffer used for generated digits, values are in the range [0,B-1]. */
  58345. duk_uint8_t digits[DUK__MAX_OUTPUT_DIGITS];
  58346. duk_small_int_t count; /* digit count */
  58347. } duk__numconv_stringify_ctx;
  58348. /* Note: computes with 'idx' in assertions, so caller beware.
  58349. * 'idx' is preincremented, i.e. '1' on first call, because it
  58350. * is more convenient for the caller.
  58351. */
  58352. #define DUK__DRAGON4_OUTPUT_PREINC(nc_ctx,preinc_idx,x) do { \
  58353. DUK_ASSERT((preinc_idx) - 1 >= 0); \
  58354. DUK_ASSERT((preinc_idx) - 1 < DUK__MAX_OUTPUT_DIGITS); \
  58355. ((nc_ctx)->digits[(preinc_idx) - 1]) = (duk_uint8_t) (x); \
  58356. } while (0)
  58357. DUK_LOCAL duk_size_t duk__dragon4_format_uint32(duk_uint8_t *buf, duk_uint32_t x, duk_small_int_t radix) {
  58358. duk_uint8_t *p;
  58359. duk_size_t len;
  58360. duk_small_int_t dig;
  58361. duk_small_int_t t;
  58362. DUK_ASSERT(radix >= 2 && radix <= 36);
  58363. /* A 32-bit unsigned integer formats to at most 32 digits (the
  58364. * worst case happens with radix == 2). Output the digits backwards,
  58365. * and use a memmove() to get them in the right place.
  58366. */
  58367. p = buf + 32;
  58368. for (;;) {
  58369. t = x / radix;
  58370. dig = x - t * radix;
  58371. x = t;
  58372. DUK_ASSERT(dig >= 0 && dig < 36);
  58373. *(--p) = DUK__DIGITCHAR(dig);
  58374. if (x == 0) {
  58375. break;
  58376. }
  58377. }
  58378. len = (duk_size_t) ((buf + 32) - p);
  58379. DUK_MEMMOVE((void *) buf, (void *) p, (size_t) len);
  58380. return len;
  58381. }
  58382. DUK_LOCAL void duk__dragon4_prepare(duk__numconv_stringify_ctx *nc_ctx) {
  58383. duk_small_int_t lowest_mantissa;
  58384. #if 1
  58385. /* Assume IEEE round-to-even, so that shorter encoding can be used
  58386. * when round-to-even would produce correct result. By removing
  58387. * this check (and having low_ok == high_ok == 0) the results would
  58388. * still be accurate but in some cases longer than necessary.
  58389. */
  58390. if (duk__bi_is_even(&nc_ctx->f)) {
  58391. DUK_DDD(DUK_DDDPRINT("f is even"));
  58392. nc_ctx->low_ok = 1;
  58393. nc_ctx->high_ok = 1;
  58394. } else {
  58395. DUK_DDD(DUK_DDDPRINT("f is odd"));
  58396. nc_ctx->low_ok = 0;
  58397. nc_ctx->high_ok = 0;
  58398. }
  58399. #else
  58400. /* Note: not honoring round-to-even should work but now generates incorrect
  58401. * results. For instance, 1e23 serializes to "a000...", i.e. the first digit
  58402. * equals the radix (10). Scaling stops one step too early in this case.
  58403. * Don't know why this is the case, but since this code path is unused, it
  58404. * doesn't matter.
  58405. */
  58406. nc_ctx->low_ok = 0;
  58407. nc_ctx->high_ok = 0;
  58408. #endif
  58409. /* For string-to-number, pretend we never have the lowest mantissa as there
  58410. * is no natural "precision" for inputs. Having lowest_mantissa == 0, we'll
  58411. * fall into the base cases for both e >= 0 and e < 0.
  58412. */
  58413. if (nc_ctx->is_s2n) {
  58414. lowest_mantissa = 0;
  58415. } else {
  58416. lowest_mantissa = duk__bi_is_2to52(&nc_ctx->f);
  58417. }
  58418. nc_ctx->unequal_gaps = 0;
  58419. if (nc_ctx->e >= 0) {
  58420. /* exponent non-negative (and thus not minimum exponent) */
  58421. if (lowest_mantissa) {
  58422. /* (>= e 0) AND (= f (expt b (- p 1)))
  58423. *
  58424. * be <- (expt b e) == b^e
  58425. * be1 <- (* be b) == (expt b (+ e 1)) == b^(e+1)
  58426. * r <- (* f be1 2) == 2 * f * b^(e+1) [if b==2 -> f * b^(e+2)]
  58427. * s <- (* b 2) [if b==2 -> 4]
  58428. * m+ <- be1 == b^(e+1)
  58429. * m- <- be == b^e
  58430. * k <- 0
  58431. * B <- B
  58432. * low_ok <- round
  58433. * high_ok <- round
  58434. */
  58435. DUK_DDD(DUK_DDDPRINT("non-negative exponent (not smallest exponent); "
  58436. "lowest mantissa value for this exponent -> "
  58437. "unequal gaps"));
  58438. duk__bi_exp_small(&nc_ctx->mm, nc_ctx->b, nc_ctx->e, &nc_ctx->t1, &nc_ctx->t2); /* mm <- b^e */
  58439. duk__bi_mul_small(&nc_ctx->mp, &nc_ctx->mm, nc_ctx->b); /* mp <- b^(e+1) */
  58440. duk__bi_mul_small(&nc_ctx->t1, &nc_ctx->f, 2);
  58441. duk__bi_mul(&nc_ctx->r, &nc_ctx->t1, &nc_ctx->mp); /* r <- (2 * f) * b^(e+1) */
  58442. duk__bi_set_small(&nc_ctx->s, nc_ctx->b * 2); /* s <- 2 * b */
  58443. nc_ctx->unequal_gaps = 1;
  58444. } else {
  58445. /* (>= e 0) AND (not (= f (expt b (- p 1))))
  58446. *
  58447. * be <- (expt b e) == b^e
  58448. * r <- (* f be 2) == 2 * f * b^e [if b==2 -> f * b^(e+1)]
  58449. * s <- 2
  58450. * m+ <- be == b^e
  58451. * m- <- be == b^e
  58452. * k <- 0
  58453. * B <- B
  58454. * low_ok <- round
  58455. * high_ok <- round
  58456. */
  58457. DUK_DDD(DUK_DDDPRINT("non-negative exponent (not smallest exponent); "
  58458. "not lowest mantissa for this exponent -> "
  58459. "equal gaps"));
  58460. duk__bi_exp_small(&nc_ctx->mm, nc_ctx->b, nc_ctx->e, &nc_ctx->t1, &nc_ctx->t2); /* mm <- b^e */
  58461. duk__bi_copy(&nc_ctx->mp, &nc_ctx->mm); /* mp <- b^e */
  58462. duk__bi_mul_small(&nc_ctx->t1, &nc_ctx->f, 2);
  58463. duk__bi_mul(&nc_ctx->r, &nc_ctx->t1, &nc_ctx->mp); /* r <- (2 * f) * b^e */
  58464. duk__bi_set_small(&nc_ctx->s, 2); /* s <- 2 */
  58465. }
  58466. } else {
  58467. /* When doing string-to-number, lowest_mantissa is always 0 so
  58468. * the exponent check, while incorrect, won't matter.
  58469. */
  58470. if (nc_ctx->e > DUK__IEEE_DOUBLE_EXP_MIN /*not minimum exponent*/ &&
  58471. lowest_mantissa /* lowest mantissa for this exponent*/) {
  58472. /* r <- (* f b 2) [if b==2 -> (* f 4)]
  58473. * s <- (* (expt b (- 1 e)) 2) == b^(1-e) * 2 [if b==2 -> b^(2-e)]
  58474. * m+ <- b == 2
  58475. * m- <- 1
  58476. * k <- 0
  58477. * B <- B
  58478. * low_ok <- round
  58479. * high_ok <- round
  58480. */
  58481. DUK_DDD(DUK_DDDPRINT("negative exponent; not minimum exponent and "
  58482. "lowest mantissa for this exponent -> "
  58483. "unequal gaps"));
  58484. duk__bi_mul_small(&nc_ctx->r, &nc_ctx->f, nc_ctx->b * 2); /* r <- (2 * b) * f */
  58485. duk__bi_exp_small(&nc_ctx->t1, nc_ctx->b, 1 - nc_ctx->e, &nc_ctx->s, &nc_ctx->t2); /* NB: use 's' as temp on purpose */
  58486. duk__bi_mul_small(&nc_ctx->s, &nc_ctx->t1, 2); /* s <- b^(1-e) * 2 */
  58487. duk__bi_set_small(&nc_ctx->mp, 2);
  58488. duk__bi_set_small(&nc_ctx->mm, 1);
  58489. nc_ctx->unequal_gaps = 1;
  58490. } else {
  58491. /* r <- (* f 2)
  58492. * s <- (* (expt b (- e)) 2) == b^(-e) * 2 [if b==2 -> b^(1-e)]
  58493. * m+ <- 1
  58494. * m- <- 1
  58495. * k <- 0
  58496. * B <- B
  58497. * low_ok <- round
  58498. * high_ok <- round
  58499. */
  58500. DUK_DDD(DUK_DDDPRINT("negative exponent; minimum exponent or not "
  58501. "lowest mantissa for this exponent -> "
  58502. "equal gaps"));
  58503. duk__bi_mul_small(&nc_ctx->r, &nc_ctx->f, 2); /* r <- 2 * f */
  58504. duk__bi_exp_small(&nc_ctx->t1, nc_ctx->b, -nc_ctx->e, &nc_ctx->s, &nc_ctx->t2); /* NB: use 's' as temp on purpose */
  58505. duk__bi_mul_small(&nc_ctx->s, &nc_ctx->t1, 2); /* s <- b^(-e) * 2 */
  58506. duk__bi_set_small(&nc_ctx->mp, 1);
  58507. duk__bi_set_small(&nc_ctx->mm, 1);
  58508. }
  58509. }
  58510. }
  58511. DUK_LOCAL void duk__dragon4_scale(duk__numconv_stringify_ctx *nc_ctx) {
  58512. duk_small_int_t k = 0;
  58513. /* This is essentially the 'scale' algorithm, with recursion removed.
  58514. * Note that 'k' is either correct immediately, or will move in one
  58515. * direction in the loop. There's no need to do the low/high checks
  58516. * on every round (like the Scheme algorithm does).
  58517. *
  58518. * The scheme algorithm finds 'k' and updates 's' simultaneously,
  58519. * while the logical algorithm finds 'k' with 's' having its initial
  58520. * value, after which 's' is updated separately (see the Burger-Dybvig
  58521. * paper, Section 3.1, steps 2 and 3).
  58522. *
  58523. * The case where m+ == m- (almost always) is optimized for, because
  58524. * it reduces the bigint operations considerably and almost always
  58525. * applies. The scale loop only needs to work with m+, so this works.
  58526. */
  58527. /* XXX: this algorithm could be optimized quite a lot by using e.g.
  58528. * a logarithm based estimator for 'k' and performing B^n multiplication
  58529. * using a lookup table or using some bit-representation based exp
  58530. * algorithm. Currently we just loop, with significant performance
  58531. * impact for very large and very small numbers.
  58532. */
  58533. DUK_DDD(DUK_DDDPRINT("scale: B=%ld, low_ok=%ld, high_ok=%ld",
  58534. (long) nc_ctx->B, (long) nc_ctx->low_ok, (long) nc_ctx->high_ok));
  58535. DUK__BI_PRINT("r(init)", &nc_ctx->r);
  58536. DUK__BI_PRINT("s(init)", &nc_ctx->s);
  58537. DUK__BI_PRINT("mp(init)", &nc_ctx->mp);
  58538. DUK__BI_PRINT("mm(init)", &nc_ctx->mm);
  58539. for (;;) {
  58540. DUK_DDD(DUK_DDDPRINT("scale loop (inc k), k=%ld", (long) k));
  58541. DUK__BI_PRINT("r", &nc_ctx->r);
  58542. DUK__BI_PRINT("s", &nc_ctx->s);
  58543. DUK__BI_PRINT("m+", &nc_ctx->mp);
  58544. DUK__BI_PRINT("m-", &nc_ctx->mm);
  58545. duk__bi_add(&nc_ctx->t1, &nc_ctx->r, &nc_ctx->mp); /* t1 = (+ r m+) */
  58546. if (duk__bi_compare(&nc_ctx->t1, &nc_ctx->s) >= (nc_ctx->high_ok ? 0 : 1)) {
  58547. DUK_DDD(DUK_DDDPRINT("k is too low"));
  58548. /* r <- r
  58549. * s <- (* s B)
  58550. * m+ <- m+
  58551. * m- <- m-
  58552. * k <- (+ k 1)
  58553. */
  58554. duk__bi_mul_small_copy(&nc_ctx->s, nc_ctx->B, &nc_ctx->t1);
  58555. k++;
  58556. } else {
  58557. break;
  58558. }
  58559. }
  58560. /* k > 0 -> k was too low, and cannot be too high */
  58561. if (k > 0) {
  58562. goto skip_dec_k;
  58563. }
  58564. for (;;) {
  58565. DUK_DDD(DUK_DDDPRINT("scale loop (dec k), k=%ld", (long) k));
  58566. DUK__BI_PRINT("r", &nc_ctx->r);
  58567. DUK__BI_PRINT("s", &nc_ctx->s);
  58568. DUK__BI_PRINT("m+", &nc_ctx->mp);
  58569. DUK__BI_PRINT("m-", &nc_ctx->mm);
  58570. duk__bi_add(&nc_ctx->t1, &nc_ctx->r, &nc_ctx->mp); /* t1 = (+ r m+) */
  58571. duk__bi_mul_small(&nc_ctx->t2, &nc_ctx->t1, nc_ctx->B); /* t2 = (* (+ r m+) B) */
  58572. if (duk__bi_compare(&nc_ctx->t2, &nc_ctx->s) <= (nc_ctx->high_ok ? -1 : 0)) {
  58573. DUK_DDD(DUK_DDDPRINT("k is too high"));
  58574. /* r <- (* r B)
  58575. * s <- s
  58576. * m+ <- (* m+ B)
  58577. * m- <- (* m- B)
  58578. * k <- (- k 1)
  58579. */
  58580. duk__bi_mul_small_copy(&nc_ctx->r, nc_ctx->B, &nc_ctx->t1);
  58581. duk__bi_mul_small_copy(&nc_ctx->mp, nc_ctx->B, &nc_ctx->t1);
  58582. if (nc_ctx->unequal_gaps) {
  58583. DUK_DDD(DUK_DDDPRINT("m+ != m- -> need to update m- too"));
  58584. duk__bi_mul_small_copy(&nc_ctx->mm, nc_ctx->B, &nc_ctx->t1);
  58585. }
  58586. k--;
  58587. } else {
  58588. break;
  58589. }
  58590. }
  58591. skip_dec_k:
  58592. if (!nc_ctx->unequal_gaps) {
  58593. DUK_DDD(DUK_DDDPRINT("equal gaps, copy m- from m+"));
  58594. duk__bi_copy(&nc_ctx->mm, &nc_ctx->mp); /* mm <- mp */
  58595. }
  58596. nc_ctx->k = k;
  58597. DUK_DDD(DUK_DDDPRINT("final k: %ld", (long) k));
  58598. DUK__BI_PRINT("r(final)", &nc_ctx->r);
  58599. DUK__BI_PRINT("s(final)", &nc_ctx->s);
  58600. DUK__BI_PRINT("mp(final)", &nc_ctx->mp);
  58601. DUK__BI_PRINT("mm(final)", &nc_ctx->mm);
  58602. }
  58603. DUK_LOCAL void duk__dragon4_generate(duk__numconv_stringify_ctx *nc_ctx) {
  58604. duk_small_int_t tc1, tc2; /* terminating conditions */
  58605. duk_small_int_t d; /* current digit */
  58606. duk_small_int_t count = 0; /* digit count */
  58607. /*
  58608. * Digit generation loop.
  58609. *
  58610. * Different termination conditions:
  58611. *
  58612. * 1. Free format output. Terminate when shortest accurate
  58613. * representation found.
  58614. *
  58615. * 2. Fixed format output, with specific number of digits.
  58616. * Ignore termination conditions, terminate when digits
  58617. * generated. Caller requests an extra digit and rounds.
  58618. *
  58619. * 3. Fixed format output, with a specific absolute cut-off
  58620. * position (e.g. 10 digits after decimal point). Note
  58621. * that we always generate at least one digit, even if
  58622. * the digit is below the cut-off point already.
  58623. */
  58624. for (;;) {
  58625. DUK_DDD(DUK_DDDPRINT("generate loop, count=%ld, k=%ld, B=%ld, low_ok=%ld, high_ok=%ld",
  58626. (long) count, (long) nc_ctx->k, (long) nc_ctx->B,
  58627. (long) nc_ctx->low_ok, (long) nc_ctx->high_ok));
  58628. DUK__BI_PRINT("r", &nc_ctx->r);
  58629. DUK__BI_PRINT("s", &nc_ctx->s);
  58630. DUK__BI_PRINT("m+", &nc_ctx->mp);
  58631. DUK__BI_PRINT("m-", &nc_ctx->mm);
  58632. /* (quotient-remainder (* r B) s) using a dummy subtraction loop */
  58633. duk__bi_mul_small(&nc_ctx->t1, &nc_ctx->r, nc_ctx->B); /* t1 <- (* r B) */
  58634. d = 0;
  58635. for (;;) {
  58636. if (duk__bi_compare(&nc_ctx->t1, &nc_ctx->s) < 0) {
  58637. break;
  58638. }
  58639. duk__bi_sub_copy(&nc_ctx->t1, &nc_ctx->s, &nc_ctx->t2); /* t1 <- t1 - s */
  58640. d++;
  58641. }
  58642. duk__bi_copy(&nc_ctx->r, &nc_ctx->t1); /* r <- (remainder (* r B) s) */
  58643. /* d <- (quotient (* r B) s) (in range 0...B-1) */
  58644. DUK_DDD(DUK_DDDPRINT("-> d(quot)=%ld", (long) d));
  58645. DUK__BI_PRINT("r(rem)", &nc_ctx->r);
  58646. duk__bi_mul_small_copy(&nc_ctx->mp, nc_ctx->B, &nc_ctx->t2); /* m+ <- (* m+ B) */
  58647. duk__bi_mul_small_copy(&nc_ctx->mm, nc_ctx->B, &nc_ctx->t2); /* m- <- (* m- B) */
  58648. DUK__BI_PRINT("mp(upd)", &nc_ctx->mp);
  58649. DUK__BI_PRINT("mm(upd)", &nc_ctx->mm);
  58650. /* Terminating conditions. For fixed width output, we just ignore the
  58651. * terminating conditions (and pretend that tc1 == tc2 == false). The
  58652. * the current shortcut for fixed-format output is to generate a few
  58653. * extra digits and use rounding (with carry) to finish the output.
  58654. */
  58655. if (nc_ctx->is_fixed == 0) {
  58656. /* free-form */
  58657. tc1 = (duk__bi_compare(&nc_ctx->r, &nc_ctx->mm) <= (nc_ctx->low_ok ? 0 : -1));
  58658. duk__bi_add(&nc_ctx->t1, &nc_ctx->r, &nc_ctx->mp); /* t1 <- (+ r m+) */
  58659. tc2 = (duk__bi_compare(&nc_ctx->t1, &nc_ctx->s) >= (&nc_ctx->high_ok ? 0 : 1));
  58660. DUK_DDD(DUK_DDDPRINT("tc1=%ld, tc2=%ld", (long) tc1, (long) tc2));
  58661. } else {
  58662. /* fixed-format */
  58663. tc1 = 0;
  58664. tc2 = 0;
  58665. }
  58666. /* Count is incremented before DUK__DRAGON4_OUTPUT_PREINC() call
  58667. * on purpose, which is taken into account by the macro.
  58668. */
  58669. count++;
  58670. if (tc1) {
  58671. if (tc2) {
  58672. /* tc1 = true, tc2 = true */
  58673. duk__bi_mul_small(&nc_ctx->t1, &nc_ctx->r, 2);
  58674. if (duk__bi_compare(&nc_ctx->t1, &nc_ctx->s) < 0) { /* (< (* r 2) s) */
  58675. DUK_DDD(DUK_DDDPRINT("tc1=true, tc2=true, 2r > s: output d --> %ld (k=%ld)",
  58676. (long) d, (long) nc_ctx->k));
  58677. DUK__DRAGON4_OUTPUT_PREINC(nc_ctx, count, d);
  58678. } else {
  58679. DUK_DDD(DUK_DDDPRINT("tc1=true, tc2=true, 2r <= s: output d+1 --> %ld (k=%ld)",
  58680. (long) (d + 1), (long) nc_ctx->k));
  58681. DUK__DRAGON4_OUTPUT_PREINC(nc_ctx, count, d + 1);
  58682. }
  58683. break;
  58684. } else {
  58685. /* tc1 = true, tc2 = false */
  58686. DUK_DDD(DUK_DDDPRINT("tc1=true, tc2=false: output d --> %ld (k=%ld)",
  58687. (long) d, (long) nc_ctx->k));
  58688. DUK__DRAGON4_OUTPUT_PREINC(nc_ctx, count, d);
  58689. break;
  58690. }
  58691. } else {
  58692. if (tc2) {
  58693. /* tc1 = false, tc2 = true */
  58694. DUK_DDD(DUK_DDDPRINT("tc1=false, tc2=true: output d+1 --> %ld (k=%ld)",
  58695. (long) (d + 1), (long) nc_ctx->k));
  58696. DUK__DRAGON4_OUTPUT_PREINC(nc_ctx, count, d + 1);
  58697. break;
  58698. } else {
  58699. /* tc1 = false, tc2 = false */
  58700. DUK_DDD(DUK_DDDPRINT("tc1=false, tc2=false: output d --> %ld (k=%ld)",
  58701. (long) d, (long) nc_ctx->k));
  58702. DUK__DRAGON4_OUTPUT_PREINC(nc_ctx, count, d);
  58703. /* r <- r (updated above: r <- (remainder (* r B) s)
  58704. * s <- s
  58705. * m+ <- m+ (updated above: m+ <- (* m+ B)
  58706. * m- <- m- (updated above: m- <- (* m- B)
  58707. * B, low_ok, high_ok are fixed
  58708. */
  58709. /* fall through and continue for-loop */
  58710. }
  58711. }
  58712. /* fixed-format termination conditions */
  58713. if (nc_ctx->is_fixed) {
  58714. if (nc_ctx->abs_pos) {
  58715. int pos = nc_ctx->k - count + 1; /* count is already incremented, take into account */
  58716. DUK_DDD(DUK_DDDPRINT("fixed format, absolute: abs pos=%ld, k=%ld, count=%ld, req=%ld",
  58717. (long) pos, (long) nc_ctx->k, (long) count, (long) nc_ctx->req_digits));
  58718. if (pos <= nc_ctx->req_digits) {
  58719. DUK_DDD(DUK_DDDPRINT("digit position reached req_digits, end generate loop"));
  58720. break;
  58721. }
  58722. } else {
  58723. DUK_DDD(DUK_DDDPRINT("fixed format, relative: k=%ld, count=%ld, req=%ld",
  58724. (long) nc_ctx->k, (long) count, (long) nc_ctx->req_digits));
  58725. if (count >= nc_ctx->req_digits) {
  58726. DUK_DDD(DUK_DDDPRINT("digit count reached req_digits, end generate loop"));
  58727. break;
  58728. }
  58729. }
  58730. }
  58731. } /* for */
  58732. nc_ctx->count = count;
  58733. DUK_DDD(DUK_DDDPRINT("generate finished"));
  58734. #ifdef DUK_USE_DDDPRINT
  58735. {
  58736. duk_uint8_t buf[2048];
  58737. duk_small_int_t i, t;
  58738. DUK_MEMZERO(buf, sizeof(buf));
  58739. for (i = 0; i < nc_ctx->count; i++) {
  58740. t = nc_ctx->digits[i];
  58741. if (t < 0 || t > 36) {
  58742. buf[i] = (duk_uint8_t) '?';
  58743. } else {
  58744. buf[i] = (duk_uint8_t) DUK__DIGITCHAR(t);
  58745. }
  58746. }
  58747. DUK_DDD(DUK_DDDPRINT("-> generated digits; k=%ld, digits='%s'",
  58748. (long) nc_ctx->k, (const char *) buf));
  58749. }
  58750. #endif
  58751. }
  58752. /* Round up digits to a given position. If position is out-of-bounds,
  58753. * does nothing. If carry propagates over the first digit, a '1' is
  58754. * prepended to digits and 'k' will be updated. Return value indicates
  58755. * whether carry propagated over the first digit.
  58756. *
  58757. * Note that nc_ctx->count is NOT updated based on the rounding position
  58758. * (it is updated only if carry overflows over the first digit and an
  58759. * extra digit is prepended).
  58760. */
  58761. DUK_LOCAL duk_small_int_t duk__dragon4_fixed_format_round(duk__numconv_stringify_ctx *nc_ctx, duk_small_int_t round_idx) {
  58762. duk_small_int_t t;
  58763. duk_uint8_t *p;
  58764. duk_uint8_t roundup_limit;
  58765. duk_small_int_t ret = 0;
  58766. /*
  58767. * round_idx points to the digit which is considered for rounding; the
  58768. * digit to its left is the final digit of the rounded value. If round_idx
  58769. * is zero, rounding will be performed; the result will either be an empty
  58770. * rounded value or if carry happens a '1' digit is generated.
  58771. */
  58772. if (round_idx >= nc_ctx->count) {
  58773. DUK_DDD(DUK_DDDPRINT("round_idx out of bounds (%ld >= %ld (count)) -> no rounding",
  58774. (long) round_idx, (long) nc_ctx->count));
  58775. return 0;
  58776. } else if (round_idx < 0) {
  58777. DUK_DDD(DUK_DDDPRINT("round_idx out of bounds (%ld < 0) -> no rounding",
  58778. (long) round_idx));
  58779. return 0;
  58780. }
  58781. /*
  58782. * Round-up limit.
  58783. *
  58784. * For even values, divides evenly, e.g. 10 -> roundup_limit=5.
  58785. *
  58786. * For odd values, rounds up, e.g. 3 -> roundup_limit=2.
  58787. * If radix is 3, 0/3 -> down, 1/3 -> down, 2/3 -> up.
  58788. */
  58789. roundup_limit = (duk_uint8_t) ((nc_ctx->B + 1) / 2);
  58790. p = &nc_ctx->digits[round_idx];
  58791. if (*p >= roundup_limit) {
  58792. DUK_DDD(DUK_DDDPRINT("fixed-format rounding carry required"));
  58793. /* carry */
  58794. for (;;) {
  58795. *p = 0;
  58796. if (p == &nc_ctx->digits[0]) {
  58797. DUK_DDD(DUK_DDDPRINT("carry propagated to first digit -> special case handling"));
  58798. DUK_MEMMOVE((void *) (&nc_ctx->digits[1]),
  58799. (void *) (&nc_ctx->digits[0]),
  58800. (size_t) (sizeof(char) * nc_ctx->count));
  58801. nc_ctx->digits[0] = 1; /* don't increase 'count' */
  58802. nc_ctx->k++; /* position of highest digit changed */
  58803. nc_ctx->count++; /* number of digits changed */
  58804. ret = 1;
  58805. break;
  58806. }
  58807. DUK_DDD(DUK_DDDPRINT("fixed-format rounding carry: B=%ld, roundup_limit=%ld, p=%p, digits=%p",
  58808. (long) nc_ctx->B, (long) roundup_limit, (void *) p, (void *) nc_ctx->digits));
  58809. p--;
  58810. t = *p;
  58811. DUK_DDD(DUK_DDDPRINT("digit before carry: %ld", (long) t));
  58812. if (++t < nc_ctx->B) {
  58813. DUK_DDD(DUK_DDDPRINT("rounding carry terminated"));
  58814. *p = t;
  58815. break;
  58816. }
  58817. DUK_DDD(DUK_DDDPRINT("wraps, carry to next digit"));
  58818. }
  58819. }
  58820. return ret;
  58821. }
  58822. #define DUK__NO_EXP (65536) /* arbitrary marker, outside valid exp range */
  58823. DUK_LOCAL void duk__dragon4_convert_and_push(duk__numconv_stringify_ctx *nc_ctx,
  58824. duk_context *ctx,
  58825. duk_small_int_t radix,
  58826. duk_small_int_t digits,
  58827. duk_small_uint_t flags,
  58828. duk_small_int_t neg) {
  58829. duk_small_int_t k;
  58830. duk_small_int_t pos, pos_end;
  58831. duk_small_int_t expt;
  58832. duk_small_int_t dig;
  58833. duk_uint8_t *q;
  58834. duk_uint8_t *buf;
  58835. /*
  58836. * The string conversion here incorporates all the necessary Ecmascript
  58837. * semantics without attempting to be generic. nc_ctx->digits contains
  58838. * nc_ctx->count digits (>= 1), with the topmost digit's 'position'
  58839. * indicated by nc_ctx->k as follows:
  58840. *
  58841. * digits="123" count=3 k=0 --> 0.123
  58842. * digits="123" count=3 k=1 --> 1.23
  58843. * digits="123" count=3 k=5 --> 12300
  58844. * digits="123" count=3 k=-1 --> 0.0123
  58845. *
  58846. * Note that the identifier names used for format selection are different
  58847. * in Burger-Dybvig paper and Ecmascript specification (quite confusingly
  58848. * so, because e.g. 'k' has a totally different meaning in each). See
  58849. * documentation for discussion.
  58850. *
  58851. * Ecmascript doesn't specify any specific behavior for format selection
  58852. * (e.g. when to use exponent notation) for non-base-10 numbers.
  58853. *
  58854. * The bigint space in the context is reused for string output, as there
  58855. * is more than enough space for that (>1kB at the moment), and we avoid
  58856. * allocating even more stack.
  58857. */
  58858. DUK_ASSERT(DUK__NUMCONV_CTX_BIGINTS_SIZE >= DUK__MAX_FORMATTED_LENGTH);
  58859. DUK_ASSERT(nc_ctx->count >= 1);
  58860. k = nc_ctx->k;
  58861. buf = (duk_uint8_t *) &nc_ctx->f; /* XXX: union would be more correct */
  58862. q = buf;
  58863. /* Exponent handling: if exponent format is used, record exponent value and
  58864. * fake k such that one leading digit is generated (e.g. digits=123 -> "1.23").
  58865. *
  58866. * toFixed() prevents exponent use; otherwise apply a set of criteria to
  58867. * match the other API calls (toString(), toPrecision, etc).
  58868. */
  58869. expt = DUK__NO_EXP;
  58870. if (!nc_ctx->abs_pos /* toFixed() */) {
  58871. if ((flags & DUK_N2S_FLAG_FORCE_EXP) || /* exponential notation forced */
  58872. ((flags & DUK_N2S_FLAG_NO_ZERO_PAD) && /* fixed precision and zero padding would be required */
  58873. (k - digits >= 1)) || /* (e.g. k=3, digits=2 -> "12X") */
  58874. ((k > 21 || k <= -6) && (radix == 10))) { /* toString() conditions */
  58875. DUK_DDD(DUK_DDDPRINT("use exponential notation: k=%ld -> expt=%ld",
  58876. (long) k, (long) (k - 1)));
  58877. expt = k - 1; /* e.g. 12.3 -> digits="123" k=2 -> 1.23e1 */
  58878. k = 1; /* generate mantissa with a single leading whole number digit */
  58879. }
  58880. }
  58881. if (neg) {
  58882. *q++ = '-';
  58883. }
  58884. /* Start position (inclusive) and end position (exclusive) */
  58885. pos = (k >= 1 ? k : 1);
  58886. if (nc_ctx->is_fixed) {
  58887. if (nc_ctx->abs_pos) {
  58888. /* toFixed() */
  58889. pos_end = -digits;
  58890. } else {
  58891. pos_end = k - digits;
  58892. }
  58893. } else {
  58894. pos_end = k - nc_ctx->count;
  58895. }
  58896. if (pos_end > 0) {
  58897. pos_end = 0;
  58898. }
  58899. DUK_DDD(DUK_DDDPRINT("expt=%ld, k=%ld, count=%ld, pos=%ld, pos_end=%ld, is_fixed=%ld, "
  58900. "digits=%ld, abs_pos=%ld",
  58901. (long) expt, (long) k, (long) nc_ctx->count, (long) pos, (long) pos_end,
  58902. (long) nc_ctx->is_fixed, (long) digits, (long) nc_ctx->abs_pos));
  58903. /* Digit generation */
  58904. while (pos > pos_end) {
  58905. DUK_DDD(DUK_DDDPRINT("digit generation: pos=%ld, pos_end=%ld",
  58906. (long) pos, (long) pos_end));
  58907. if (pos == 0) {
  58908. *q++ = (duk_uint8_t) '.';
  58909. }
  58910. if (pos > k) {
  58911. *q++ = (duk_uint8_t) '0';
  58912. } else if (pos <= k - nc_ctx->count) {
  58913. *q++ = (duk_uint8_t) '0';
  58914. } else {
  58915. dig = nc_ctx->digits[k - pos];
  58916. DUK_ASSERT(dig >= 0 && dig < nc_ctx->B);
  58917. *q++ = (duk_uint8_t) DUK__DIGITCHAR(dig);
  58918. }
  58919. pos--;
  58920. }
  58921. DUK_ASSERT(pos <= 1);
  58922. /* Exponent */
  58923. if (expt != DUK__NO_EXP) {
  58924. /*
  58925. * Exponent notation for non-base-10 numbers isn't specified in Ecmascript
  58926. * specification, as it never explicitly turns up: non-decimal numbers can
  58927. * only be formatted with Number.prototype.toString([radix]) and for that,
  58928. * behavior is not explicitly specified.
  58929. *
  58930. * Logical choices include formatting the exponent as decimal (e.g. binary
  58931. * 100000 as 1e+5) or in current radix (e.g. binary 100000 as 1e+101).
  58932. * The Dragon4 algorithm (in the original paper) prints the exponent value
  58933. * in the target radix B. However, for radix values 15 and above, the
  58934. * exponent separator 'e' is no longer easily parseable. Consider, for
  58935. * instance, the number "1.faecee+1c".
  58936. */
  58937. duk_size_t len;
  58938. char expt_sign;
  58939. *q++ = 'e';
  58940. if (expt >= 0) {
  58941. expt_sign = '+';
  58942. } else {
  58943. expt_sign = '-';
  58944. expt = -expt;
  58945. }
  58946. *q++ = (duk_uint8_t) expt_sign;
  58947. len = duk__dragon4_format_uint32(q, (duk_uint32_t) expt, radix);
  58948. q += len;
  58949. }
  58950. duk_push_lstring(ctx, (const char *) buf, (size_t) (q - buf));
  58951. }
  58952. /*
  58953. * Conversion helpers
  58954. */
  58955. DUK_LOCAL void duk__dragon4_double_to_ctx(duk__numconv_stringify_ctx *nc_ctx, duk_double_t x) {
  58956. duk_double_union u;
  58957. duk_uint32_t tmp;
  58958. duk_small_int_t expt;
  58959. /*
  58960. * seeeeeee eeeeffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
  58961. * A B C D E F G H
  58962. *
  58963. * s sign bit
  58964. * eee... exponent field
  58965. * fff... fraction
  58966. *
  58967. * ieee value = 1.ffff... * 2^(e - 1023) (normal)
  58968. * = 0.ffff... * 2^(-1022) (denormal)
  58969. *
  58970. * algorithm v = f * b^e
  58971. */
  58972. DUK_DBLUNION_SET_DOUBLE(&u, x);
  58973. nc_ctx->f.n = 2;
  58974. tmp = DUK_DBLUNION_GET_LOW32(&u);
  58975. nc_ctx->f.v[0] = tmp;
  58976. tmp = DUK_DBLUNION_GET_HIGH32(&u);
  58977. nc_ctx->f.v[1] = tmp & 0x000fffffUL;
  58978. expt = (duk_small_int_t) ((tmp >> 20) & 0x07ffUL);
  58979. if (expt == 0) {
  58980. /* denormal */
  58981. expt = DUK__IEEE_DOUBLE_EXP_MIN - 52;
  58982. duk__bi_normalize(&nc_ctx->f);
  58983. } else {
  58984. /* normal: implicit leading 1-bit */
  58985. nc_ctx->f.v[1] |= 0x00100000UL;
  58986. expt = expt - DUK__IEEE_DOUBLE_EXP_BIAS - 52;
  58987. DUK_ASSERT(duk__bi_is_valid(&nc_ctx->f)); /* true, because v[1] has at least one bit set */
  58988. }
  58989. DUK_ASSERT(duk__bi_is_valid(&nc_ctx->f));
  58990. nc_ctx->e = expt;
  58991. }
  58992. DUK_LOCAL void duk__dragon4_ctx_to_double(duk__numconv_stringify_ctx *nc_ctx, duk_double_t *x) {
  58993. duk_double_union u;
  58994. duk_small_int_t expt;
  58995. duk_small_int_t i;
  58996. duk_small_int_t bitstart;
  58997. duk_small_int_t bitround;
  58998. duk_small_int_t bitidx;
  58999. duk_small_int_t skip_round;
  59000. duk_uint32_t t, v;
  59001. DUK_ASSERT(nc_ctx->count == 53 + 1);
  59002. /* Sometimes this assert is not true right now; it will be true after
  59003. * rounding. See: test-bug-numconv-mantissa-assert.js.
  59004. */
  59005. DUK_ASSERT_DISABLE(nc_ctx->digits[0] == 1); /* zero handled by caller */
  59006. /* Should not be required because the code below always sets both high
  59007. * and low parts, but at least gcc-4.4.5 fails to deduce this correctly
  59008. * (perhaps because the low part is set (seemingly) conditionally in a
  59009. * loop), so this is here to avoid the bogus warning.
  59010. */
  59011. DUK_MEMZERO((void *) &u, sizeof(u));
  59012. /*
  59013. * Figure out how generated digits match up with the mantissa,
  59014. * and then perform rounding. If mantissa overflows, need to
  59015. * recompute the exponent (it is bumped and may overflow to
  59016. * infinity).
  59017. *
  59018. * For normal numbers the leading '1' is hidden and ignored,
  59019. * and the last bit is used for rounding:
  59020. *
  59021. * rounding pt
  59022. * <--------52------->|
  59023. * 1 x x x x ... x x x x|y ==> x x x x ... x x x x
  59024. *
  59025. * For denormals, the leading '1' is included in the number,
  59026. * and the rounding point is different:
  59027. *
  59028. * rounding pt
  59029. * <--52 or less--->|
  59030. * 1 x x x x ... x x|x x y ==> 0 0 ... 1 x x ... x x
  59031. *
  59032. * The largest denormals will have a mantissa beginning with
  59033. * a '1' (the explicit leading bit); smaller denormals will
  59034. * have leading zero bits.
  59035. *
  59036. * If the exponent would become too high, the result becomes
  59037. * Infinity. If the exponent is so small that the entire
  59038. * mantissa becomes zero, the result becomes zero.
  59039. *
  59040. * Note: the Dragon4 'k' is off-by-one with respect to the IEEE
  59041. * exponent. For instance, k==0 indicates that the leading '1'
  59042. * digit is at the first binary fraction position (0.1xxx...);
  59043. * the corresponding IEEE exponent would be -1.
  59044. */
  59045. skip_round = 0;
  59046. recheck_exp:
  59047. expt = nc_ctx->k - 1; /* IEEE exp without bias */
  59048. if (expt > 1023) {
  59049. /* Infinity */
  59050. bitstart = -255; /* needed for inf: causes mantissa to become zero,
  59051. * and rounding to be skipped.
  59052. */
  59053. expt = 2047;
  59054. } else if (expt >= -1022) {
  59055. /* normal */
  59056. bitstart = 1; /* skip leading digit */
  59057. expt += DUK__IEEE_DOUBLE_EXP_BIAS;
  59058. DUK_ASSERT(expt >= 1 && expt <= 2046);
  59059. } else {
  59060. /* denormal or zero */
  59061. bitstart = 1023 + expt; /* expt==-1023 -> bitstart=0 (leading 1);
  59062. * expt==-1024 -> bitstart=-1 (one left of leading 1), etc
  59063. */
  59064. expt = 0;
  59065. }
  59066. bitround = bitstart + 52;
  59067. DUK_DDD(DUK_DDDPRINT("ieee expt=%ld, bitstart=%ld, bitround=%ld",
  59068. (long) expt, (long) bitstart, (long) bitround));
  59069. if (!skip_round) {
  59070. if (duk__dragon4_fixed_format_round(nc_ctx, bitround)) {
  59071. /* Corner case: see test-numconv-parse-mant-carry.js. We could
  59072. * just bump the exponent and update bitstart, but it's more robust
  59073. * to recompute (but avoid rounding twice).
  59074. */
  59075. DUK_DDD(DUK_DDDPRINT("rounding caused exponent to be bumped, recheck exponent"));
  59076. skip_round = 1;
  59077. goto recheck_exp;
  59078. }
  59079. }
  59080. /*
  59081. * Create mantissa
  59082. */
  59083. t = 0;
  59084. for (i = 0; i < 52; i++) {
  59085. bitidx = bitstart + 52 - 1 - i;
  59086. if (bitidx >= nc_ctx->count) {
  59087. v = 0;
  59088. } else if (bitidx < 0) {
  59089. v = 0;
  59090. } else {
  59091. v = nc_ctx->digits[bitidx];
  59092. }
  59093. DUK_ASSERT(v == 0 || v == 1);
  59094. t += v << (i % 32);
  59095. if (i == 31) {
  59096. /* low 32 bits is complete */
  59097. DUK_DBLUNION_SET_LOW32(&u, t);
  59098. t = 0;
  59099. }
  59100. }
  59101. /* t has high mantissa */
  59102. DUK_DDD(DUK_DDDPRINT("mantissa is complete: %08lx %08lx",
  59103. (unsigned long) t,
  59104. (unsigned long) DUK_DBLUNION_GET_LOW32(&u)));
  59105. DUK_ASSERT(expt >= 0 && expt <= 0x7ffL);
  59106. t += expt << 20;
  59107. #if 0 /* caller handles sign change */
  59108. if (negative) {
  59109. t |= 0x80000000U;
  59110. }
  59111. #endif
  59112. DUK_DBLUNION_SET_HIGH32(&u, t);
  59113. DUK_DDD(DUK_DDDPRINT("number is complete: %08lx %08lx",
  59114. (unsigned long) DUK_DBLUNION_GET_HIGH32(&u),
  59115. (unsigned long) DUK_DBLUNION_GET_LOW32(&u)));
  59116. *x = DUK_DBLUNION_GET_DOUBLE(&u);
  59117. }
  59118. /*
  59119. * Exposed number-to-string API
  59120. *
  59121. * Input: [ number ]
  59122. * Output: [ string ]
  59123. */
  59124. DUK_INTERNAL void duk_numconv_stringify(duk_context *ctx, duk_small_int_t radix, duk_small_int_t digits, duk_small_uint_t flags) {
  59125. duk_double_t x;
  59126. duk_small_int_t c;
  59127. duk_small_int_t neg;
  59128. duk_uint32_t uval;
  59129. duk__numconv_stringify_ctx nc_ctx_alloc; /* large context; around 2kB now */
  59130. duk__numconv_stringify_ctx *nc_ctx = &nc_ctx_alloc;
  59131. x = (duk_double_t) duk_require_number(ctx, -1);
  59132. duk_pop(ctx);
  59133. /*
  59134. * Handle special cases (NaN, infinity, zero).
  59135. */
  59136. c = (duk_small_int_t) DUK_FPCLASSIFY(x);
  59137. if (DUK_SIGNBIT((double) x)) {
  59138. x = -x;
  59139. neg = 1;
  59140. } else {
  59141. neg = 0;
  59142. }
  59143. /* NaN sign bit is platform specific with unpacked, un-normalized NaNs */
  59144. DUK_ASSERT(c == DUK_FP_NAN || DUK_SIGNBIT((double) x) == 0);
  59145. if (c == DUK_FP_NAN) {
  59146. duk_push_hstring_stridx(ctx, DUK_STRIDX_NAN);
  59147. return;
  59148. } else if (c == DUK_FP_INFINITE) {
  59149. if (neg) {
  59150. /* -Infinity */
  59151. duk_push_hstring_stridx(ctx, DUK_STRIDX_MINUS_INFINITY);
  59152. } else {
  59153. /* Infinity */
  59154. duk_push_hstring_stridx(ctx, DUK_STRIDX_INFINITY);
  59155. }
  59156. return;
  59157. } else if (c == DUK_FP_ZERO) {
  59158. /* We can't shortcut zero here if it goes through special formatting
  59159. * (such as forced exponential notation).
  59160. */
  59161. ;
  59162. }
  59163. /*
  59164. * Handle integers in 32-bit range (that is, [-(2**32-1),2**32-1])
  59165. * specially, as they're very likely for embedded programs. This
  59166. * is now done for all radix values. We must be careful not to use
  59167. * the fast path when special formatting (e.g. forced exponential)
  59168. * is in force.
  59169. *
  59170. * XXX: could save space by supporting radix 10 only and using
  59171. * sprintf "%lu" for the fast path and for exponent formatting.
  59172. */
  59173. uval = (unsigned int) x;
  59174. if (((double) uval) == x && /* integer number in range */
  59175. flags == 0) { /* no special formatting */
  59176. /* use bigint area as a temp */
  59177. duk_uint8_t *buf = (duk_uint8_t *) (&nc_ctx->f);
  59178. duk_uint8_t *p = buf;
  59179. DUK_ASSERT(DUK__NUMCONV_CTX_BIGINTS_SIZE >= 32 + 1); /* max size: radix=2 + sign */
  59180. if (neg && uval != 0) {
  59181. /* no negative sign for zero */
  59182. *p++ = (duk_uint8_t) '-';
  59183. }
  59184. p += duk__dragon4_format_uint32(p, uval, radix);
  59185. duk_push_lstring(ctx, (const char *) buf, (duk_size_t) (p - buf));
  59186. return;
  59187. }
  59188. /*
  59189. * Dragon4 setup.
  59190. *
  59191. * Convert double from IEEE representation for conversion;
  59192. * normal finite values have an implicit leading 1-bit. The
  59193. * slow path algorithm doesn't handle zero, so zero is special
  59194. * cased here but still creates a valid nc_ctx, and goes
  59195. * through normal formatting in case special formatting has
  59196. * been requested (e.g. forced exponential format: 0 -> "0e+0").
  59197. */
  59198. /* Would be nice to bulk clear the allocation, but the context
  59199. * is 1-2 kilobytes and nothing should rely on it being zeroed.
  59200. */
  59201. #if 0
  59202. DUK_MEMZERO((void *) nc_ctx, sizeof(*nc_ctx)); /* slow init, do only for slow path cases */
  59203. #endif
  59204. nc_ctx->is_s2n = 0;
  59205. nc_ctx->b = 2;
  59206. nc_ctx->B = radix;
  59207. nc_ctx->abs_pos = 0;
  59208. if (flags & DUK_N2S_FLAG_FIXED_FORMAT) {
  59209. nc_ctx->is_fixed = 1;
  59210. if (flags & DUK_N2S_FLAG_FRACTION_DIGITS) {
  59211. /* absolute req_digits; e.g. digits = 1 -> last digit is 0,
  59212. * but add an extra digit for rounding.
  59213. */
  59214. nc_ctx->abs_pos = 1;
  59215. nc_ctx->req_digits = (-digits + 1) - 1;
  59216. } else {
  59217. nc_ctx->req_digits = digits + 1;
  59218. }
  59219. } else {
  59220. nc_ctx->is_fixed = 0;
  59221. nc_ctx->req_digits = 0;
  59222. }
  59223. if (c == DUK_FP_ZERO) {
  59224. /* Zero special case: fake requested number of zero digits; ensure
  59225. * no sign bit is printed. Relative and absolute fixed format
  59226. * require separate handling.
  59227. */
  59228. duk_small_int_t count;
  59229. if (nc_ctx->is_fixed) {
  59230. if (nc_ctx->abs_pos) {
  59231. count = digits + 2; /* lead zero + 'digits' fractions + 1 for rounding */
  59232. } else {
  59233. count = digits + 1; /* + 1 for rounding */
  59234. }
  59235. } else {
  59236. count = 1;
  59237. }
  59238. DUK_DDD(DUK_DDDPRINT("count=%ld", (long) count));
  59239. DUK_ASSERT(count >= 1);
  59240. DUK_MEMZERO((void *) nc_ctx->digits, count);
  59241. nc_ctx->count = count;
  59242. nc_ctx->k = 1; /* 0.000... */
  59243. neg = 0;
  59244. goto zero_skip;
  59245. }
  59246. duk__dragon4_double_to_ctx(nc_ctx, x); /* -> sets 'f' and 'e' */
  59247. DUK__BI_PRINT("f", &nc_ctx->f);
  59248. DUK_DDD(DUK_DDDPRINT("e=%ld", (long) nc_ctx->e));
  59249. /*
  59250. * Dragon4 slow path digit generation.
  59251. */
  59252. duk__dragon4_prepare(nc_ctx); /* setup many variables in nc_ctx */
  59253. DUK_DDD(DUK_DDDPRINT("after prepare:"));
  59254. DUK__BI_PRINT("r", &nc_ctx->r);
  59255. DUK__BI_PRINT("s", &nc_ctx->s);
  59256. DUK__BI_PRINT("mp", &nc_ctx->mp);
  59257. DUK__BI_PRINT("mm", &nc_ctx->mm);
  59258. duk__dragon4_scale(nc_ctx);
  59259. DUK_DDD(DUK_DDDPRINT("after scale; k=%ld", (long) nc_ctx->k));
  59260. DUK__BI_PRINT("r", &nc_ctx->r);
  59261. DUK__BI_PRINT("s", &nc_ctx->s);
  59262. DUK__BI_PRINT("mp", &nc_ctx->mp);
  59263. DUK__BI_PRINT("mm", &nc_ctx->mm);
  59264. duk__dragon4_generate(nc_ctx);
  59265. /*
  59266. * Convert and push final string.
  59267. */
  59268. zero_skip:
  59269. if (flags & DUK_N2S_FLAG_FIXED_FORMAT) {
  59270. /* Perform fixed-format rounding. */
  59271. duk_small_int_t roundpos;
  59272. if (flags & DUK_N2S_FLAG_FRACTION_DIGITS) {
  59273. /* 'roundpos' is relative to nc_ctx->k and increases to the right
  59274. * (opposite of how 'k' changes).
  59275. */
  59276. roundpos = -digits; /* absolute position for digit considered for rounding */
  59277. roundpos = nc_ctx->k - roundpos;
  59278. } else {
  59279. roundpos = digits;
  59280. }
  59281. DUK_DDD(DUK_DDDPRINT("rounding: k=%ld, count=%ld, digits=%ld, roundpos=%ld",
  59282. (long) nc_ctx->k, (long) nc_ctx->count, (long) digits, (long) roundpos));
  59283. (void) duk__dragon4_fixed_format_round(nc_ctx, roundpos);
  59284. /* Note: 'count' is currently not adjusted by rounding (i.e. the
  59285. * digits are not "chopped off". That shouldn't matter because
  59286. * the digit position (absolute or relative) is passed on to the
  59287. * convert-and-push function.
  59288. */
  59289. }
  59290. duk__dragon4_convert_and_push(nc_ctx, ctx, radix, digits, flags, neg);
  59291. }
  59292. /*
  59293. * Exposed string-to-number API
  59294. *
  59295. * Input: [ string ]
  59296. * Output: [ number ]
  59297. *
  59298. * If number parsing fails, a NaN is pushed as the result. If number parsing
  59299. * fails due to an internal error, an InternalError is thrown.
  59300. */
  59301. DUK_INTERNAL void duk_numconv_parse(duk_context *ctx, duk_small_int_t radix, duk_small_uint_t flags) {
  59302. duk_hthread *thr = (duk_hthread *) ctx;
  59303. duk__numconv_stringify_ctx nc_ctx_alloc; /* large context; around 2kB now */
  59304. duk__numconv_stringify_ctx *nc_ctx = &nc_ctx_alloc;
  59305. duk_double_t res;
  59306. duk_hstring *h_str;
  59307. duk_small_int_t expt;
  59308. duk_small_int_t expt_neg;
  59309. duk_small_int_t expt_adj;
  59310. duk_small_int_t neg;
  59311. duk_small_int_t dig;
  59312. duk_small_int_t dig_whole;
  59313. duk_small_int_t dig_lzero;
  59314. duk_small_int_t dig_frac;
  59315. duk_small_int_t dig_expt;
  59316. duk_small_int_t dig_prec;
  59317. const duk__exp_limits *explim;
  59318. const duk_uint8_t *p;
  59319. duk_small_int_t ch;
  59320. /* This seems to waste a lot of stack frame entries, but good compilers
  59321. * will compute these as needed below. Some of these initial flags are
  59322. * also modified in the code below, so they can't all be removed.
  59323. */
  59324. duk_small_int_t trim_white = (flags & DUK_S2N_FLAG_TRIM_WHITE);
  59325. duk_small_int_t allow_expt = (flags & DUK_S2N_FLAG_ALLOW_EXP);
  59326. duk_small_int_t allow_garbage = (flags & DUK_S2N_FLAG_ALLOW_GARBAGE);
  59327. duk_small_int_t allow_plus = (flags & DUK_S2N_FLAG_ALLOW_PLUS);
  59328. duk_small_int_t allow_minus = (flags & DUK_S2N_FLAG_ALLOW_MINUS);
  59329. duk_small_int_t allow_infinity = (flags & DUK_S2N_FLAG_ALLOW_INF);
  59330. duk_small_int_t allow_frac = (flags & DUK_S2N_FLAG_ALLOW_FRAC);
  59331. duk_small_int_t allow_naked_frac = (flags & DUK_S2N_FLAG_ALLOW_NAKED_FRAC);
  59332. duk_small_int_t allow_empty_frac = (flags & DUK_S2N_FLAG_ALLOW_EMPTY_FRAC);
  59333. duk_small_int_t allow_empty = (flags & DUK_S2N_FLAG_ALLOW_EMPTY_AS_ZERO);
  59334. duk_small_int_t allow_leading_zero = (flags & DUK_S2N_FLAG_ALLOW_LEADING_ZERO);
  59335. duk_small_int_t allow_auto_hex_int = (flags & DUK_S2N_FLAG_ALLOW_AUTO_HEX_INT);
  59336. duk_small_int_t allow_auto_oct_int = (flags & DUK_S2N_FLAG_ALLOW_AUTO_OCT_INT);
  59337. DUK_DDD(DUK_DDDPRINT("parse number: %!T, radix=%ld, flags=0x%08lx",
  59338. (duk_tval *) duk_get_tval(ctx, -1),
  59339. (long) radix, (unsigned long) flags));
  59340. DUK_ASSERT(radix >= 2 && radix <= 36);
  59341. DUK_ASSERT(radix - 2 < (duk_small_int_t) sizeof(duk__str2num_digits_for_radix));
  59342. /*
  59343. * Preliminaries: trim, sign, Infinity check
  59344. *
  59345. * We rely on the interned string having a NUL terminator, which will
  59346. * cause a parse failure wherever it is encountered. As a result, we
  59347. * don't need separate pointer checks.
  59348. *
  59349. * There is no special parsing for 'NaN' in the specification although
  59350. * 'Infinity' (with an optional sign) is allowed in some contexts.
  59351. * Some contexts allow plus/minus sign, while others only allow the
  59352. * minus sign (like JSON.parse()).
  59353. *
  59354. * Automatic hex number detection (leading '0x' or '0X') and octal
  59355. * number detection (leading '0' followed by at least one octal digit)
  59356. * is done here too.
  59357. */
  59358. if (trim_white) {
  59359. /* Leading / trailing whitespace is sometimes accepted and
  59360. * sometimes not. After white space trimming, all valid input
  59361. * characters are pure ASCII.
  59362. */
  59363. duk_trim(ctx, -1);
  59364. }
  59365. h_str = duk_require_hstring(ctx, -1);
  59366. DUK_ASSERT(h_str != NULL);
  59367. p = (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h_str);
  59368. neg = 0;
  59369. ch = *p;
  59370. if (ch == (duk_small_int_t) '+') {
  59371. if (!allow_plus) {
  59372. DUK_DDD(DUK_DDDPRINT("parse failed: leading plus sign not allowed"));
  59373. goto parse_fail;
  59374. }
  59375. p++;
  59376. } else if (ch == (duk_small_int_t) '-') {
  59377. if (!allow_minus) {
  59378. DUK_DDD(DUK_DDDPRINT("parse failed: leading minus sign not allowed"));
  59379. goto parse_fail;
  59380. }
  59381. p++;
  59382. neg = 1;
  59383. }
  59384. ch = *p;
  59385. if (allow_infinity && ch == (duk_small_int_t) 'I') {
  59386. /* Don't check for Infinity unless the context allows it.
  59387. * 'Infinity' is a valid integer literal in e.g. base-36:
  59388. *
  59389. * parseInt('Infinity', 36)
  59390. * 1461559270678
  59391. */
  59392. const duk_uint8_t *q;
  59393. /* borrow literal Infinity from builtin string */
  59394. q = (const duk_uint8_t *) DUK_HSTRING_GET_DATA(DUK_HTHREAD_STRING_INFINITY(thr));
  59395. if (DUK_STRNCMP((const char *) p, (const char *) q, 8) == 0) {
  59396. if (!allow_garbage && (p[8] != (duk_uint8_t) 0)) {
  59397. DUK_DDD(DUK_DDDPRINT("parse failed: trailing garbage after matching 'Infinity' not allowed"));
  59398. goto parse_fail;
  59399. } else {
  59400. res = DUK_DOUBLE_INFINITY;
  59401. goto negcheck_and_ret;
  59402. }
  59403. }
  59404. }
  59405. if (ch == (duk_small_int_t) '0') {
  59406. duk_small_int_t detect_radix = 0;
  59407. ch = p[1];
  59408. if (allow_auto_hex_int && (ch == (duk_small_int_t) 'x' || ch == (duk_small_int_t) 'X')) {
  59409. DUK_DDD(DUK_DDDPRINT("detected 0x/0X hex prefix, changing radix and preventing fractions and exponent"));
  59410. detect_radix = 16;
  59411. allow_empty = 0; /* interpret e.g. '0x' and '0xg' as a NaN (= parse error) */
  59412. p += 2;
  59413. } else if (allow_auto_oct_int && (ch >= (duk_small_int_t) '0' && ch <= (duk_small_int_t) '9')) {
  59414. DUK_DDD(DUK_DDDPRINT("detected 0n oct prefix, changing radix and preventing fractions and exponent"));
  59415. detect_radix = 8;
  59416. allow_empty = 1; /* interpret e.g. '09' as '0', not NaN */
  59417. p += 1;
  59418. }
  59419. if (detect_radix > 0) {
  59420. radix = detect_radix;
  59421. allow_expt = 0;
  59422. allow_frac = 0;
  59423. allow_naked_frac = 0;
  59424. allow_empty_frac = 0;
  59425. allow_leading_zero = 1; /* allow e.g. '0x0009' and '00077' */
  59426. }
  59427. }
  59428. /*
  59429. * Scan number and setup for Dragon4.
  59430. *
  59431. * The fast path case is detected during setup: an integer which
  59432. * can be converted without rounding, no net exponent. The fast
  59433. * path could be implemented as a separate scan, but may not really
  59434. * be worth it: the multiplications for building 'f' are not
  59435. * expensive when 'f' is small.
  59436. *
  59437. * The significand ('f') must contain enough bits of (apparent)
  59438. * accuracy, so that Dragon4 will generate enough binary output digits.
  59439. * For decimal numbers, this means generating a 20-digit significand,
  59440. * which should yield enough practical accuracy to parse IEEE doubles.
  59441. * In fact, the Ecmascript specification explicitly allows an
  59442. * implementation to treat digits beyond 20 as zeroes (and even
  59443. * to round the 20th digit upwards). For non-decimal numbers, the
  59444. * appropriate number of digits has been precomputed for comparable
  59445. * accuracy.
  59446. *
  59447. * Digit counts:
  59448. *
  59449. * [ dig_lzero ]
  59450. * |
  59451. * .+-..---[ dig_prec ]----.
  59452. * | || |
  59453. * 0000123.456789012345678901234567890e+123456
  59454. * | | | | | |
  59455. * `--+--' `------[ dig_frac ]-------' `-+--'
  59456. * | |
  59457. * [ dig_whole ] [ dig_expt ]
  59458. *
  59459. * dig_frac and dig_expt are -1 if not present
  59460. * dig_lzero is only computed for whole number part
  59461. *
  59462. * Parsing state
  59463. *
  59464. * Parsing whole part dig_frac < 0 AND dig_expt < 0
  59465. * Parsing fraction part dig_frac >= 0 AND dig_expt < 0
  59466. * Parsing exponent part dig_expt >= 0 (dig_frac may be < 0 or >= 0)
  59467. *
  59468. * Note: in case we hit an implementation limit (like exponent range),
  59469. * we should throw an error, NOT return NaN or Infinity. Even with
  59470. * very large exponent (or significand) values the final result may be
  59471. * finite, so NaN/Infinity would be incorrect.
  59472. */
  59473. duk__bi_set_small(&nc_ctx->f, 0);
  59474. dig_prec = 0;
  59475. dig_lzero = 0;
  59476. dig_whole = 0;
  59477. dig_frac = -1;
  59478. dig_expt = -1;
  59479. expt = 0;
  59480. expt_adj = 0; /* essentially tracks digit position of lowest 'f' digit */
  59481. expt_neg = 0;
  59482. for (;;) {
  59483. ch = *p++;
  59484. DUK_DDD(DUK_DDDPRINT("parse digits: p=%p, ch='%c' (%ld), expt=%ld, expt_adj=%ld, "
  59485. "dig_whole=%ld, dig_frac=%ld, dig_expt=%ld, dig_lzero=%ld, dig_prec=%ld",
  59486. (void *) p, (int) ((ch >= 0x20 && ch <= 0x7e) ? ch : '?'), (long) ch,
  59487. (long) expt, (long) expt_adj, (long) dig_whole, (long) dig_frac,
  59488. (long) dig_expt, (long) dig_lzero, (long) dig_prec));
  59489. DUK__BI_PRINT("f", &nc_ctx->f);
  59490. /* Most common cases first. */
  59491. if (ch >= (duk_small_int_t) '0' && ch <= (duk_small_int_t) '9') {
  59492. dig = (int) ch - '0' + 0;
  59493. } else if (ch == (duk_small_int_t) '.') {
  59494. /* A leading digit is not required in some cases, e.g. accept ".123".
  59495. * In other cases (JSON.parse()) a leading digit is required. This
  59496. * is checked for after the loop.
  59497. */
  59498. if (dig_frac >= 0 || dig_expt >= 0) {
  59499. if (allow_garbage) {
  59500. DUK_DDD(DUK_DDDPRINT("garbage termination (invalid period)"));
  59501. break;
  59502. } else {
  59503. DUK_DDD(DUK_DDDPRINT("parse failed: period not allowed"));
  59504. goto parse_fail;
  59505. }
  59506. }
  59507. if (!allow_frac) {
  59508. /* Some contexts don't allow fractions at all; this can't be a
  59509. * post-check because the state ('f' and expt) would be incorrect.
  59510. */
  59511. if (allow_garbage) {
  59512. DUK_DDD(DUK_DDDPRINT("garbage termination (invalid first period)"));
  59513. break;
  59514. } else {
  59515. DUK_DDD(DUK_DDDPRINT("parse failed: fraction part not allowed"));
  59516. }
  59517. }
  59518. DUK_DDD(DUK_DDDPRINT("start fraction part"));
  59519. dig_frac = 0;
  59520. continue;
  59521. } else if (ch == (duk_small_int_t) 0) {
  59522. DUK_DDD(DUK_DDDPRINT("NUL termination"));
  59523. break;
  59524. } else if (allow_expt && dig_expt < 0 && (ch == (duk_small_int_t) 'e' || ch == (duk_small_int_t) 'E')) {
  59525. /* Note: we don't parse back exponent notation for anything else
  59526. * than radix 10, so this is not an ambiguous check (e.g. hex
  59527. * exponent values may have 'e' either as a significand digit
  59528. * or as an exponent separator).
  59529. *
  59530. * If the exponent separator occurs twice, 'e' will be interpreted
  59531. * as a digit (= 14) and will be rejected as an invalid decimal
  59532. * digit.
  59533. */
  59534. DUK_DDD(DUK_DDDPRINT("start exponent part"));
  59535. /* Exponent without a sign or with a +/- sign is accepted
  59536. * by all call sites (even JSON.parse()).
  59537. */
  59538. ch = *p;
  59539. if (ch == (duk_small_int_t) '-') {
  59540. expt_neg = 1;
  59541. p++;
  59542. } else if (ch == (duk_small_int_t) '+') {
  59543. p++;
  59544. }
  59545. dig_expt = 0;
  59546. continue;
  59547. } else if (ch >= (duk_small_int_t) 'a' && ch <= (duk_small_int_t) 'z') {
  59548. dig = (duk_small_int_t) (ch - (duk_small_int_t) 'a' + 0x0a);
  59549. } else if (ch >= (duk_small_int_t) 'A' && ch <= (duk_small_int_t) 'Z') {
  59550. dig = (duk_small_int_t) (ch - (duk_small_int_t) 'A' + 0x0a);
  59551. } else {
  59552. dig = 255; /* triggers garbage digit check below */
  59553. }
  59554. DUK_ASSERT((dig >= 0 && dig <= 35) || dig == 255);
  59555. if (dig >= radix) {
  59556. if (allow_garbage) {
  59557. DUK_DDD(DUK_DDDPRINT("garbage termination"));
  59558. break;
  59559. } else {
  59560. DUK_DDD(DUK_DDDPRINT("parse failed: trailing garbage or invalid digit"));
  59561. goto parse_fail;
  59562. }
  59563. }
  59564. if (dig_expt < 0) {
  59565. /* whole or fraction digit */
  59566. if (dig_prec < duk__str2num_digits_for_radix[radix - 2]) {
  59567. /* significant from precision perspective */
  59568. duk_small_int_t f_zero = duk__bi_is_zero(&nc_ctx->f);
  59569. if (f_zero && dig == 0) {
  59570. /* Leading zero is not counted towards precision digits; not
  59571. * in the integer part, nor in the fraction part.
  59572. */
  59573. if (dig_frac < 0) {
  59574. dig_lzero++;
  59575. }
  59576. } else {
  59577. /* XXX: join these ops (multiply-accumulate), but only if
  59578. * code footprint decreases.
  59579. */
  59580. duk__bi_mul_small(&nc_ctx->t1, &nc_ctx->f, radix);
  59581. duk__bi_add_small(&nc_ctx->f, &nc_ctx->t1, dig);
  59582. dig_prec++;
  59583. }
  59584. } else {
  59585. /* Ignore digits beyond a radix-specific limit, but note them
  59586. * in expt_adj.
  59587. */
  59588. expt_adj++;
  59589. }
  59590. if (dig_frac >= 0) {
  59591. dig_frac++;
  59592. expt_adj--;
  59593. } else {
  59594. dig_whole++;
  59595. }
  59596. } else {
  59597. /* exponent digit */
  59598. expt = expt * radix + dig;
  59599. if (expt > DUK_S2N_MAX_EXPONENT) {
  59600. /* impose a reasonable exponent limit, so that exp
  59601. * doesn't need to get tracked using a bigint.
  59602. */
  59603. DUK_DDD(DUK_DDDPRINT("parse failed: exponent too large"));
  59604. goto parse_int_error;
  59605. }
  59606. dig_expt++;
  59607. }
  59608. }
  59609. /* Leading zero. */
  59610. if (dig_lzero > 0 && dig_whole > 1) {
  59611. if (!allow_leading_zero) {
  59612. DUK_DDD(DUK_DDDPRINT("parse failed: leading zeroes not allowed in integer part"));
  59613. goto parse_fail;
  59614. }
  59615. }
  59616. /* Validity checks for various fraction formats ("0.1", ".1", "1.", "."). */
  59617. if (dig_whole == 0) {
  59618. if (dig_frac == 0) {
  59619. /* "." is not accepted in any format */
  59620. DUK_DDD(DUK_DDDPRINT("parse failed: plain period without leading or trailing digits"));
  59621. goto parse_fail;
  59622. } else if (dig_frac > 0) {
  59623. /* ".123" */
  59624. if (!allow_naked_frac) {
  59625. DUK_DDD(DUK_DDDPRINT("parse failed: fraction part not allowed without "
  59626. "leading integer digit(s)"));
  59627. goto parse_fail;
  59628. }
  59629. } else {
  59630. /* empty ("") is allowed in some formats (e.g. Number(''), as zero */
  59631. if (!allow_empty) {
  59632. DUK_DDD(DUK_DDDPRINT("parse failed: empty string not allowed (as zero)"));
  59633. goto parse_fail;
  59634. }
  59635. }
  59636. } else {
  59637. if (dig_frac == 0) {
  59638. /* "123." is allowed in some formats */
  59639. if (!allow_empty_frac) {
  59640. DUK_DDD(DUK_DDDPRINT("parse failed: empty fractions"));
  59641. goto parse_fail;
  59642. }
  59643. } else if (dig_frac > 0) {
  59644. /* "123.456" */
  59645. ;
  59646. } else {
  59647. /* "123" */
  59648. ;
  59649. }
  59650. }
  59651. /* Exponent without digits (e.g. "1e" or "1e+"). If trailing garbage is
  59652. * allowed, ignore exponent part as garbage (= parse as "1", i.e. exp 0).
  59653. */
  59654. if (dig_expt == 0) {
  59655. if (!allow_garbage) {
  59656. DUK_DDD(DUK_DDDPRINT("parse failed: empty exponent"));
  59657. goto parse_fail;
  59658. }
  59659. DUK_ASSERT(expt == 0);
  59660. }
  59661. if (expt_neg) {
  59662. expt = -expt;
  59663. }
  59664. DUK_DDD(DUK_DDDPRINT("expt=%ld, expt_adj=%ld, net exponent -> %ld",
  59665. (long) expt, (long) expt_adj, (long) (expt + expt_adj)));
  59666. expt += expt_adj;
  59667. /* Fast path check. */
  59668. if (nc_ctx->f.n <= 1 && /* 32-bit value */
  59669. expt == 0 /* no net exponent */) {
  59670. /* Fast path is triggered for no exponent and also for balanced exponent
  59671. * and fraction parts, e.g. for "1.23e2" == "123". Remember to respect
  59672. * zero sign.
  59673. */
  59674. /* XXX: could accept numbers larger than 32 bits, e.g. up to 53 bits? */
  59675. DUK_DDD(DUK_DDDPRINT("fast path number parse"));
  59676. if (nc_ctx->f.n == 1) {
  59677. res = (double) nc_ctx->f.v[0];
  59678. } else {
  59679. res = 0.0;
  59680. }
  59681. goto negcheck_and_ret;
  59682. }
  59683. /* Significand ('f') padding. */
  59684. while (dig_prec < duk__str2num_digits_for_radix[radix - 2]) {
  59685. /* Pad significand with "virtual" zero digits so that Dragon4 will
  59686. * have enough (apparent) precision to work with.
  59687. */
  59688. DUK_DDD(DUK_DDDPRINT("dig_prec=%ld, pad significand with zero", (long) dig_prec));
  59689. duk__bi_mul_small_copy(&nc_ctx->f, radix, &nc_ctx->t1);
  59690. DUK__BI_PRINT("f", &nc_ctx->f);
  59691. expt--;
  59692. dig_prec++;
  59693. }
  59694. DUK_DDD(DUK_DDDPRINT("final exponent: %ld", (long) expt));
  59695. /* Detect zero special case. */
  59696. if (nc_ctx->f.n == 0) {
  59697. /* This may happen even after the fast path check, if exponent is
  59698. * not balanced (e.g. "0e1"). Remember to respect zero sign.
  59699. */
  59700. DUK_DDD(DUK_DDDPRINT("significand is zero"));
  59701. res = 0.0;
  59702. goto negcheck_and_ret;
  59703. }
  59704. /* Quick reject of too large or too small exponents. This check
  59705. * would be incorrect for zero (e.g. "0e1000" is zero, not Infinity)
  59706. * so zero check must be above.
  59707. */
  59708. explim = &duk__str2num_exp_limits[radix - 2];
  59709. if (expt > explim->upper) {
  59710. DUK_DDD(DUK_DDDPRINT("exponent too large -> infinite"));
  59711. res = (duk_double_t) DUK_DOUBLE_INFINITY;
  59712. goto negcheck_and_ret;
  59713. } else if (expt < explim->lower) {
  59714. DUK_DDD(DUK_DDDPRINT("exponent too small -> zero"));
  59715. res = (duk_double_t) 0.0;
  59716. goto negcheck_and_ret;
  59717. }
  59718. nc_ctx->is_s2n = 1;
  59719. nc_ctx->e = expt;
  59720. nc_ctx->b = radix;
  59721. nc_ctx->B = 2;
  59722. nc_ctx->is_fixed = 1;
  59723. nc_ctx->abs_pos = 0;
  59724. nc_ctx->req_digits = 53 + 1;
  59725. DUK__BI_PRINT("f", &nc_ctx->f);
  59726. DUK_DDD(DUK_DDDPRINT("e=%ld", (long) nc_ctx->e));
  59727. /*
  59728. * Dragon4 slow path (binary) digit generation.
  59729. * An extra digit is generated for rounding.
  59730. */
  59731. duk__dragon4_prepare(nc_ctx); /* setup many variables in nc_ctx */
  59732. DUK_DDD(DUK_DDDPRINT("after prepare:"));
  59733. DUK__BI_PRINT("r", &nc_ctx->r);
  59734. DUK__BI_PRINT("s", &nc_ctx->s);
  59735. DUK__BI_PRINT("mp", &nc_ctx->mp);
  59736. DUK__BI_PRINT("mm", &nc_ctx->mm);
  59737. duk__dragon4_scale(nc_ctx);
  59738. DUK_DDD(DUK_DDDPRINT("after scale; k=%ld", (long) nc_ctx->k));
  59739. DUK__BI_PRINT("r", &nc_ctx->r);
  59740. DUK__BI_PRINT("s", &nc_ctx->s);
  59741. DUK__BI_PRINT("mp", &nc_ctx->mp);
  59742. DUK__BI_PRINT("mm", &nc_ctx->mm);
  59743. duk__dragon4_generate(nc_ctx);
  59744. DUK_ASSERT(nc_ctx->count == 53 + 1);
  59745. /*
  59746. * Convert binary digits into an IEEE double. Need to handle
  59747. * denormals and rounding correctly.
  59748. */
  59749. duk__dragon4_ctx_to_double(nc_ctx, &res);
  59750. goto negcheck_and_ret;
  59751. negcheck_and_ret:
  59752. if (neg) {
  59753. res = -res;
  59754. }
  59755. duk_pop(ctx);
  59756. duk_push_number(ctx, (double) res);
  59757. DUK_DDD(DUK_DDDPRINT("result: %!T", (duk_tval *) duk_get_tval(ctx, -1)));
  59758. return;
  59759. parse_fail:
  59760. DUK_DDD(DUK_DDDPRINT("parse failed"));
  59761. duk_pop(ctx);
  59762. duk_push_nan(ctx);
  59763. return;
  59764. parse_int_error:
  59765. DUK_DDD(DUK_DDDPRINT("parse failed, internal error, can't return a value"));
  59766. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, "number parse error");
  59767. return;
  59768. }
  59769. #line 1 "duk_regexp_compiler.c"
  59770. /*
  59771. * Regexp compilation.
  59772. *
  59773. * See doc/regexp.txt for a discussion of the compilation approach and
  59774. * current limitations.
  59775. *
  59776. * Regexp bytecode assumes jumps can be expressed with signed 32-bit
  59777. * integers. Consequently the bytecode size must not exceed 0x7fffffffL.
  59778. * The implementation casts duk_size_t (buffer size) to duk_(u)int32_t
  59779. * in many places. Although this could be changed, the bytecode format
  59780. * limit would still prevent regexps exceeding the signed 32-bit limit
  59781. * from working.
  59782. *
  59783. * XXX: The implementation does not prevent bytecode from exceeding the
  59784. * maximum supported size. This could be done by limiting the maximum
  59785. * input string size (assuming an upper bound can be computed for number
  59786. * of bytecode bytes emitted per input byte) or checking buffer maximum
  59787. * size when emitting bytecode (slower).
  59788. */
  59789. /* include removed: duk_internal.h */
  59790. #ifdef DUK_USE_REGEXP_SUPPORT
  59791. /*
  59792. * Helper macros
  59793. */
  59794. #ifdef DUK__BUFLEN
  59795. #undef DUK__BUFLEN
  59796. #endif
  59797. #define DUK__BUFLEN(re_ctx) DUK_HBUFFER_GET_SIZE((duk_hbuffer *) re_ctx->buf)
  59798. /*
  59799. * Disjunction struct: result of parsing a disjunction
  59800. */
  59801. typedef struct {
  59802. /* Number of characters that the atom matches (e.g. 3 for 'abc'),
  59803. * -1 if atom is complex and number of matched characters either
  59804. * varies or is not known.
  59805. */
  59806. duk_int32_t charlen;
  59807. #if 0
  59808. /* These are not needed to implement quantifier capture handling,
  59809. * but might be needed at some point.
  59810. */
  59811. /* re_ctx->captures at start and end of atom parsing.
  59812. * Since 'captures' indicates highest capture number emitted
  59813. * so far in a DUK_REOP_SAVE, the captures numbers saved by
  59814. * the atom are: ]start_captures,end_captures].
  59815. */
  59816. duk_uint32_t start_captures;
  59817. duk_uint32_t end_captures;
  59818. #endif
  59819. } duk__re_disjunction_info;
  59820. /*
  59821. * Encoding helpers
  59822. *
  59823. * Some of the typing is bytecode based, e.g. slice sizes are unsigned 32-bit
  59824. * even though the buffer operations will use duk_size_t.
  59825. */
  59826. /* XXX: the insert helpers should ensure that the bytecode result is not
  59827. * larger than expected (or at least assert for it). Many things in the
  59828. * bytecode, like skip offsets, won't work correctly if the bytecode is
  59829. * larger than say 2G.
  59830. */
  59831. DUK_LOCAL duk_uint32_t duk__encode_i32(duk_int32_t x) {
  59832. if (x < 0) {
  59833. return ((duk_uint32_t) (-x)) * 2 + 1;
  59834. } else {
  59835. return ((duk_uint32_t) x) * 2;
  59836. }
  59837. }
  59838. /* XXX: return type should probably be duk_size_t, or explicit checks are needed for
  59839. * maximum size.
  59840. */
  59841. DUK_LOCAL duk_uint32_t duk__insert_u32(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_uint32_t x) {
  59842. return (duk_uint32_t) duk_hbuffer_insert_xutf8(re_ctx->thr, re_ctx->buf, offset, x);
  59843. }
  59844. DUK_LOCAL duk_uint32_t duk__append_u32(duk_re_compiler_ctx *re_ctx, duk_uint32_t x) {
  59845. return (duk_uint32_t) duk_hbuffer_append_xutf8(re_ctx->thr, re_ctx->buf, x);
  59846. }
  59847. DUK_LOCAL duk_uint32_t duk__insert_i32(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_int32_t x) {
  59848. return (duk_uint32_t) duk_hbuffer_insert_xutf8(re_ctx->thr, re_ctx->buf, offset, duk__encode_i32(x));
  59849. }
  59850. #if 0 /* unused */
  59851. DUK_LOCAL duk_uint32_t duk__append_i32(duk_re_compiler_ctx *re_ctx, duk_int32_t x) {
  59852. return duk_hbuffer_append_xutf8(re_ctx->thr, re_ctx->buf, duk__encode_i32(x));
  59853. }
  59854. #endif
  59855. /* special helper for emitting u16 lists (used for character ranges for built-in char classes) */
  59856. DUK_LOCAL void duk__append_u16_list(duk_re_compiler_ctx *re_ctx, duk_uint16_t *values, duk_uint32_t count) {
  59857. /* Call sites don't need the result length so it's not accumulated. */
  59858. while (count > 0) {
  59859. (void) duk__append_u32(re_ctx, (duk_uint32_t) (*values++));
  59860. count--;
  59861. }
  59862. }
  59863. DUK_LOCAL void duk__insert_slice(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_uint32_t data_offset, duk_uint32_t data_length) {
  59864. duk_hbuffer_insert_slice(re_ctx->thr, re_ctx->buf, offset, data_offset, (duk_size_t) data_length);
  59865. }
  59866. DUK_LOCAL void duk__append_slice(duk_re_compiler_ctx *re_ctx, duk_uint32_t data_offset, duk_uint32_t data_length) {
  59867. duk_hbuffer_append_slice(re_ctx->thr, re_ctx->buf, data_offset, (duk_size_t) data_length);
  59868. }
  59869. DUK_LOCAL void duk__remove_slice(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_uint32_t length) {
  59870. duk_hbuffer_remove_slice(re_ctx->thr, re_ctx->buf, offset, (duk_size_t) length);
  59871. }
  59872. /*
  59873. * Insert a jump offset at 'offset' to complete an instruction
  59874. * (the jump offset is always the last component of an instruction).
  59875. * The 'skip' argument must be computed relative to 'offset',
  59876. * -without- taking into account the skip field being inserted.
  59877. *
  59878. * ... A B C ins X Y Z ... (ins may be a JUMP, SPLIT1/SPLIT2, etc)
  59879. * => ... A B C ins SKIP X Y Z
  59880. *
  59881. * Computing the final (adjusted) skip value, which is relative to the
  59882. * first byte of the next instruction, is a bit tricky because of the
  59883. * variable length UTF-8 encoding. See doc/regexp.txt for discussion.
  59884. */
  59885. DUK_LOCAL duk_uint32_t duk__insert_jump_offset(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_int32_t skip) {
  59886. duk_small_int_t len;
  59887. /* XXX: solve into closed form (smaller code) */
  59888. if (skip < 0) {
  59889. /* two encoding attempts suffices */
  59890. len = duk_unicode_get_xutf8_length((duk_codepoint_t) duk__encode_i32(skip));
  59891. len = duk_unicode_get_xutf8_length((duk_codepoint_t) duk__encode_i32(skip - (duk_int32_t) len));
  59892. DUK_ASSERT(duk_unicode_get_xutf8_length(duk__encode_i32(skip - (duk_int32_t) len)) == len); /* no change */
  59893. skip -= (duk_int32_t) len;
  59894. }
  59895. return duk__insert_i32(re_ctx, offset, skip);
  59896. }
  59897. DUK_LOCAL duk_uint32_t duk__append_jump_offset(duk_re_compiler_ctx *re_ctx, duk_int32_t skip) {
  59898. return (duk_uint32_t) duk__insert_jump_offset(re_ctx, (duk_uint32_t) DUK__BUFLEN(re_ctx), skip);
  59899. }
  59900. /*
  59901. * duk_re_range_callback for generating character class ranges.
  59902. *
  59903. * When ignoreCase is false, the range is simply emitted as is.
  59904. * We don't, for instance, eliminate duplicates or overlapping
  59905. * ranges in a character class.
  59906. *
  59907. * When ignoreCase is true, the range needs to be normalized through
  59908. * canonicalization. Unfortunately a canonicalized version of a
  59909. * continuous range is not necessarily continuous (e.g. [x-{] is
  59910. * continuous but [X-{] is not). The current algorithm creates the
  59911. * canonicalized range(s) space efficiently at the cost of compile
  59912. * time execution time (see doc/regexp.txt for discussion).
  59913. *
  59914. * Note that the ctx->nranges is a context-wide temporary value
  59915. * (this is OK because there cannot be multiple character classes
  59916. * being parsed simultaneously).
  59917. */
  59918. DUK_LOCAL void duk__generate_ranges(void *userdata, duk_codepoint_t r1, duk_codepoint_t r2, duk_bool_t direct) {
  59919. duk_re_compiler_ctx *re_ctx = (duk_re_compiler_ctx *) userdata;
  59920. DUK_DD(DUK_DDPRINT("duk__generate_ranges(): re_ctx=%p, range=[%ld,%ld] direct=%ld",
  59921. (void *) re_ctx, (long) r1, (long) r2, (long) direct));
  59922. if (!direct && (re_ctx->re_flags & DUK_RE_FLAG_IGNORE_CASE)) {
  59923. /*
  59924. * Canonicalize a range, generating result ranges as necessary.
  59925. * Needs to exhaustively scan the entire range (at most 65536
  59926. * code points). If 'direct' is set, caller (lexer) has ensured
  59927. * that the range is already canonicalization compatible (this
  59928. * is used to avoid unnecessary canonicalization of built-in
  59929. * ranges like \W, which are not affected by canonicalization).
  59930. *
  59931. * NOTE: here is one place where we don't want to support chars
  59932. * outside the BMP, because the exhaustive search would be
  59933. * massively larger.
  59934. */
  59935. duk_codepoint_t i;
  59936. duk_codepoint_t t;
  59937. duk_codepoint_t r_start, r_end;
  59938. r_start = duk_unicode_re_canonicalize_char(re_ctx->thr, r1);
  59939. r_end = r_start;
  59940. for (i = r1 + 1; i <= r2; i++) {
  59941. t = duk_unicode_re_canonicalize_char(re_ctx->thr, i);
  59942. if (t == r_end + 1) {
  59943. r_end = t;
  59944. } else {
  59945. DUK_DD(DUK_DDPRINT("canonicalized, emit range: [%ld,%ld]", (long) r_start, (long) r_end));
  59946. duk__append_u32(re_ctx, (duk_uint32_t) r_start);
  59947. duk__append_u32(re_ctx, (duk_uint32_t) r_end);
  59948. re_ctx->nranges++;
  59949. r_start = t;
  59950. r_end = t;
  59951. }
  59952. }
  59953. DUK_DD(DUK_DDPRINT("canonicalized, emit range: [%ld,%ld]", (long) r_start, (long) r_end));
  59954. duk__append_u32(re_ctx, (duk_uint32_t) r_start);
  59955. duk__append_u32(re_ctx, (duk_uint32_t) r_end);
  59956. re_ctx->nranges++;
  59957. } else {
  59958. DUK_DD(DUK_DDPRINT("direct, emit range: [%ld,%ld]", (long) r1, (long) r2));
  59959. duk__append_u32(re_ctx, (duk_uint32_t) r1);
  59960. duk__append_u32(re_ctx, (duk_uint32_t) r2);
  59961. re_ctx->nranges++;
  59962. }
  59963. }
  59964. /*
  59965. * Parse regexp Disjunction. Most of regexp compilation happens here.
  59966. *
  59967. * Handles Disjunction, Alternative, and Term productions directly without
  59968. * recursion. The only constructs requiring recursion are positive/negative
  59969. * lookaheads, capturing parentheses, and non-capturing parentheses.
  59970. *
  59971. * The function determines whether the entire disjunction is a 'simple atom'
  59972. * (see doc/regexp.txt discussion on 'simple quantifiers') and if so,
  59973. * returns the atom character length which is needed by the caller to keep
  59974. * track of its own atom character length. A disjunction with more than one
  59975. * alternative is never considered a simple atom (although in some cases
  59976. * that might be the case).
  59977. *
  59978. * Return value: simple atom character length or < 0 if not a simple atom.
  59979. * Appends the bytecode for the disjunction matcher to the end of the temp
  59980. * buffer.
  59981. *
  59982. * Regexp top level structure is:
  59983. *
  59984. * Disjunction = Term*
  59985. * | Term* | Disjunction
  59986. *
  59987. * Term = Assertion
  59988. * | Atom
  59989. * | Atom Quantifier
  59990. *
  59991. * An empty Term sequence is a valid disjunction alternative (e.g. /|||c||/).
  59992. *
  59993. * Notes:
  59994. *
  59995. * * Tracking of the 'simple-ness' of the current atom vs. the entire
  59996. * disjunction are separate matters. For instance, the disjunction
  59997. * may be complex, but individual atoms may be simple. Furthermore,
  59998. * simple quantifiers are used whenever possible, even if the
  59999. * disjunction as a whole is complex.
  60000. *
  60001. * * The estimate of whether an atom is simple is conservative now,
  60002. * and it would be possible to expand it. For instance, captures
  60003. * cause the disjunction to be marked complex, even though captures
  60004. * -can- be handled by simple quantifiers with some minor modifications.
  60005. *
  60006. * * Disjunction 'tainting' as 'complex' is handled at the end of the
  60007. * main for loop collectively for atoms. Assertions, quantifiers,
  60008. * and '|' tokens need to taint the result manually if necessary.
  60009. * Assertions cannot add to result char length, only atoms (and
  60010. * quantifiers) can; currently quantifiers will taint the result
  60011. * as complex though.
  60012. */
  60013. DUK_LOCAL void duk__parse_disjunction(duk_re_compiler_ctx *re_ctx, duk_bool_t expect_eof, duk__re_disjunction_info *out_atom_info) {
  60014. duk_int32_t atom_start_offset = -1; /* negative -> no atom matched on previous round */
  60015. duk_int32_t atom_char_length = 0; /* negative -> complex atom */
  60016. duk_uint32_t atom_start_captures = re_ctx->captures; /* value of re_ctx->captures at start of atom */
  60017. duk_int32_t unpatched_disjunction_split = -1;
  60018. duk_int32_t unpatched_disjunction_jump = -1;
  60019. duk_uint32_t entry_offset = (duk_uint32_t) DUK__BUFLEN(re_ctx);
  60020. duk_int32_t res_charlen = 0; /* -1 if disjunction is complex, char length if simple */
  60021. duk__re_disjunction_info tmp_disj;
  60022. DUK_ASSERT(out_atom_info != NULL);
  60023. if (re_ctx->recursion_depth >= re_ctx->recursion_limit) {
  60024. DUK_ERROR(re_ctx->thr, DUK_ERR_RANGE_ERROR,
  60025. DUK_STR_REGEXP_COMPILER_RECURSION_LIMIT);
  60026. }
  60027. re_ctx->recursion_depth++;
  60028. #if 0
  60029. out_atom_info->start_captures = re_ctx->captures;
  60030. #endif
  60031. for (;;) {
  60032. /* atom_char_length, atom_start_offset, atom_start_offset reflect the
  60033. * atom matched on the previous loop. If a quantifier is encountered
  60034. * on this loop, these are needed to handle the quantifier correctly.
  60035. * new_atom_char_length etc are for the atom parsed on this round;
  60036. * they're written to atom_char_length etc at the end of the round.
  60037. */
  60038. duk_int32_t new_atom_char_length; /* char length of the atom parsed in this loop */
  60039. duk_int32_t new_atom_start_offset; /* bytecode start offset of the atom parsed in this loop
  60040. * (allows quantifiers to copy the atom bytecode)
  60041. */
  60042. duk_uint32_t new_atom_start_captures; /* re_ctx->captures at the start of the atom parsed in this loop */
  60043. duk_lexer_parse_re_token(&re_ctx->lex, &re_ctx->curr_token);
  60044. DUK_DD(DUK_DDPRINT("re token: %ld (num=%ld, char=%c)",
  60045. (long) re_ctx->curr_token.t,
  60046. (long) re_ctx->curr_token.num,
  60047. (re_ctx->curr_token.num >= 0x20 && re_ctx->curr_token.num <= 0x7e) ?
  60048. (int) re_ctx->curr_token.num : (int) '?'));
  60049. /* set by atom case clauses */
  60050. new_atom_start_offset = -1;
  60051. new_atom_char_length = -1;
  60052. new_atom_start_captures = re_ctx->captures;
  60053. switch (re_ctx->curr_token.t) {
  60054. case DUK_RETOK_DISJUNCTION: {
  60055. /*
  60056. * The handling here is a bit tricky. If a previous '|' has been processed,
  60057. * we have a pending split1 and a pending jump (for a previous match). These
  60058. * need to be back-patched carefully. See docs for a detailed example.
  60059. */
  60060. /* patch pending jump and split */
  60061. if (unpatched_disjunction_jump >= 0) {
  60062. duk_uint32_t offset;
  60063. DUK_ASSERT(unpatched_disjunction_split >= 0);
  60064. offset = unpatched_disjunction_jump;
  60065. offset += duk__insert_jump_offset(re_ctx,
  60066. offset,
  60067. (duk_int32_t) (DUK__BUFLEN(re_ctx) - offset));
  60068. /* offset is now target of the pending split (right after jump) */
  60069. duk__insert_jump_offset(re_ctx,
  60070. unpatched_disjunction_split,
  60071. offset - unpatched_disjunction_split);
  60072. }
  60073. /* add a new pending split to the beginning of the entire disjunction */
  60074. (void) duk__insert_u32(re_ctx,
  60075. entry_offset,
  60076. DUK_REOP_SPLIT1); /* prefer direct execution */
  60077. unpatched_disjunction_split = entry_offset + 1; /* +1 for opcode */
  60078. /* add a new pending match jump for latest finished alternative */
  60079. duk__append_u32(re_ctx, DUK_REOP_JUMP);
  60080. unpatched_disjunction_jump = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60081. /* 'taint' result as complex */
  60082. res_charlen = -1;
  60083. break;
  60084. }
  60085. case DUK_RETOK_QUANTIFIER: {
  60086. if (atom_start_offset < 0) {
  60087. DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  60088. DUK_STR_INVALID_QUANTIFIER_NO_ATOM);
  60089. }
  60090. if (re_ctx->curr_token.qmin > re_ctx->curr_token.qmax) {
  60091. DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  60092. DUK_STR_INVALID_QUANTIFIER_VALUES);
  60093. }
  60094. if (atom_char_length >= 0) {
  60095. /*
  60096. * Simple atom
  60097. *
  60098. * If atom_char_length is zero, we'll have unbounded execution time for e.g.
  60099. * /()*x/.exec('x'). We can't just skip the match because it might have some
  60100. * side effects (for instance, if we allowed captures in simple atoms, the
  60101. * capture needs to happen). The simple solution below is to force the
  60102. * quantifier to match at most once, since the additional matches have no effect.
  60103. *
  60104. * With a simple atom there can be no capture groups, so no captures need
  60105. * to be reset.
  60106. */
  60107. duk_int32_t atom_code_length;
  60108. duk_uint32_t offset;
  60109. duk_uint32_t qmin, qmax;
  60110. qmin = re_ctx->curr_token.qmin;
  60111. qmax = re_ctx->curr_token.qmax;
  60112. if (atom_char_length == 0) {
  60113. /* qmin and qmax will be 0 or 1 */
  60114. if (qmin > 1) {
  60115. qmin = 1;
  60116. }
  60117. if (qmax > 1) {
  60118. qmax = 1;
  60119. }
  60120. }
  60121. duk__append_u32(re_ctx, DUK_REOP_MATCH); /* complete 'sub atom' */
  60122. atom_code_length = (duk_int32_t) (DUK__BUFLEN(re_ctx) - atom_start_offset);
  60123. offset = atom_start_offset;
  60124. if (re_ctx->curr_token.greedy) {
  60125. offset += duk__insert_u32(re_ctx, offset, DUK_REOP_SQGREEDY);
  60126. offset += duk__insert_u32(re_ctx, offset, qmin);
  60127. offset += duk__insert_u32(re_ctx, offset, qmax);
  60128. offset += duk__insert_u32(re_ctx, offset, atom_char_length);
  60129. offset += duk__insert_jump_offset(re_ctx, offset, atom_code_length);
  60130. } else {
  60131. offset += duk__insert_u32(re_ctx, offset, DUK_REOP_SQMINIMAL);
  60132. offset += duk__insert_u32(re_ctx, offset, qmin);
  60133. offset += duk__insert_u32(re_ctx, offset, qmax);
  60134. offset += duk__insert_jump_offset(re_ctx, offset, atom_code_length);
  60135. }
  60136. DUK_UNREF(offset); /* silence scan-build warning */
  60137. } else {
  60138. /*
  60139. * Complex atom
  60140. *
  60141. * The original code is used as a template, and removed at the end
  60142. * (this differs from the handling of simple quantifiers).
  60143. *
  60144. * NOTE: there is no current solution for empty atoms in complex
  60145. * quantifiers. This would need some sort of a 'progress' instruction.
  60146. *
  60147. * XXX: impose limit on maximum result size, i.e. atom_code_len * atom_copies?
  60148. */
  60149. duk_int32_t atom_code_length;
  60150. duk_uint32_t atom_copies;
  60151. duk_uint32_t tmp_qmin, tmp_qmax;
  60152. /* pre-check how many atom copies we're willing to make (atom_copies not needed below) */
  60153. atom_copies = (re_ctx->curr_token.qmax == DUK_RE_QUANTIFIER_INFINITE) ?
  60154. re_ctx->curr_token.qmin : re_ctx->curr_token.qmax;
  60155. if (atom_copies > DUK_RE_MAX_ATOM_COPIES) {
  60156. DUK_ERROR(re_ctx->thr, DUK_ERR_RANGE_ERROR,
  60157. DUK_STR_QUANTIFIER_TOO_MANY_COPIES);
  60158. }
  60159. /* wipe the capture range made by the atom (if any) */
  60160. DUK_ASSERT(atom_start_captures <= re_ctx->captures);
  60161. if (atom_start_captures != re_ctx->captures) {
  60162. DUK_ASSERT(atom_start_captures < re_ctx->captures);
  60163. DUK_DDD(DUK_DDDPRINT("must wipe ]atom_start_captures,re_ctx->captures]: ]%ld,%ld]",
  60164. (long) atom_start_captures, (long) re_ctx->captures));
  60165. /* insert (DUK_REOP_WIPERANGE, start, count) in reverse order so the order ends up right */
  60166. duk__insert_u32(re_ctx, atom_start_offset, (re_ctx->captures - atom_start_captures) * 2);
  60167. duk__insert_u32(re_ctx, atom_start_offset, (atom_start_captures + 1) * 2);
  60168. duk__insert_u32(re_ctx, atom_start_offset, DUK_REOP_WIPERANGE);
  60169. } else {
  60170. DUK_DDD(DUK_DDDPRINT("no need to wipe captures: atom_start_captures == re_ctx->captures == %ld",
  60171. (long) atom_start_captures));
  60172. }
  60173. atom_code_length = (duk_int32_t) DUK__BUFLEN(re_ctx) - atom_start_offset;
  60174. /* insert the required matches (qmin) by copying the atom */
  60175. tmp_qmin = re_ctx->curr_token.qmin;
  60176. tmp_qmax = re_ctx->curr_token.qmax;
  60177. while (tmp_qmin > 0) {
  60178. duk__append_slice(re_ctx, atom_start_offset, atom_code_length);
  60179. tmp_qmin--;
  60180. if (tmp_qmax != DUK_RE_QUANTIFIER_INFINITE) {
  60181. tmp_qmax--;
  60182. }
  60183. }
  60184. DUK_ASSERT(tmp_qmin == 0);
  60185. /* insert code for matching the remainder - infinite or finite */
  60186. if (tmp_qmax == DUK_RE_QUANTIFIER_INFINITE) {
  60187. /* reuse last emitted atom for remaining 'infinite' quantifier */
  60188. if (re_ctx->curr_token.qmin == 0) {
  60189. /* Special case: original qmin was zero so there is nothing
  60190. * to repeat. Emit an atom copy but jump over it here.
  60191. */
  60192. duk__append_u32(re_ctx, DUK_REOP_JUMP);
  60193. duk__append_jump_offset(re_ctx, atom_code_length);
  60194. duk__append_slice(re_ctx, atom_start_offset, atom_code_length);
  60195. }
  60196. if (re_ctx->curr_token.greedy) {
  60197. duk__append_u32(re_ctx, DUK_REOP_SPLIT2); /* prefer jump */
  60198. } else {
  60199. duk__append_u32(re_ctx, DUK_REOP_SPLIT1); /* prefer direct */
  60200. }
  60201. duk__append_jump_offset(re_ctx, -atom_code_length - 1); /* -1 for opcode */
  60202. } else {
  60203. /*
  60204. * The remaining matches are emitted as sequence of SPLITs and atom
  60205. * copies; the SPLITs skip the remaining copies and match the sequel.
  60206. * This sequence needs to be emitted starting from the last copy
  60207. * because the SPLITs are variable length due to the variable length
  60208. * skip offset. This causes a lot of memory copying now.
  60209. *
  60210. * Example structure (greedy, match maximum # atoms):
  60211. *
  60212. * SPLIT1 LSEQ
  60213. * (atom)
  60214. * SPLIT1 LSEQ ; <- the byte length of this instruction is needed
  60215. * (atom) ; to encode the above SPLIT1 correctly
  60216. * ...
  60217. * LSEQ:
  60218. */
  60219. duk_uint32_t offset = (duk_uint32_t) DUK__BUFLEN(re_ctx);
  60220. while (tmp_qmax > 0) {
  60221. duk__insert_slice(re_ctx, offset, atom_start_offset, atom_code_length);
  60222. if (re_ctx->curr_token.greedy) {
  60223. duk__insert_u32(re_ctx, offset, DUK_REOP_SPLIT1); /* prefer direct */
  60224. } else {
  60225. duk__insert_u32(re_ctx, offset, DUK_REOP_SPLIT2); /* prefer jump */
  60226. }
  60227. duk__insert_jump_offset(re_ctx,
  60228. offset + 1, /* +1 for opcode */
  60229. (duk_int32_t) (DUK__BUFLEN(re_ctx) - (offset + 1)));
  60230. tmp_qmax--;
  60231. }
  60232. }
  60233. /* remove the original 'template' atom */
  60234. duk__remove_slice(re_ctx, atom_start_offset, atom_code_length);
  60235. }
  60236. /* 'taint' result as complex */
  60237. res_charlen = -1;
  60238. break;
  60239. }
  60240. case DUK_RETOK_ASSERT_START: {
  60241. duk__append_u32(re_ctx, DUK_REOP_ASSERT_START);
  60242. break;
  60243. }
  60244. case DUK_RETOK_ASSERT_END: {
  60245. duk__append_u32(re_ctx, DUK_REOP_ASSERT_END);
  60246. break;
  60247. }
  60248. case DUK_RETOK_ASSERT_WORD_BOUNDARY: {
  60249. duk__append_u32(re_ctx, DUK_REOP_ASSERT_WORD_BOUNDARY);
  60250. break;
  60251. }
  60252. case DUK_RETOK_ASSERT_NOT_WORD_BOUNDARY: {
  60253. duk__append_u32(re_ctx, DUK_REOP_ASSERT_NOT_WORD_BOUNDARY);
  60254. break;
  60255. }
  60256. case DUK_RETOK_ASSERT_START_POS_LOOKAHEAD:
  60257. case DUK_RETOK_ASSERT_START_NEG_LOOKAHEAD: {
  60258. duk_uint32_t offset;
  60259. duk_uint32_t opcode = (re_ctx->curr_token.t == DUK_RETOK_ASSERT_START_POS_LOOKAHEAD) ?
  60260. DUK_REOP_LOOKPOS : DUK_REOP_LOOKNEG;
  60261. offset = (duk_uint32_t) DUK__BUFLEN(re_ctx);
  60262. duk__parse_disjunction(re_ctx, 0, &tmp_disj);
  60263. duk__append_u32(re_ctx, DUK_REOP_MATCH);
  60264. (void) duk__insert_u32(re_ctx, offset, opcode);
  60265. (void) duk__insert_jump_offset(re_ctx,
  60266. offset + 1, /* +1 for opcode */
  60267. (duk_int32_t) (DUK__BUFLEN(re_ctx) - (offset + 1)));
  60268. /* 'taint' result as complex -- this is conservative,
  60269. * as lookaheads do not backtrack.
  60270. */
  60271. res_charlen = -1;
  60272. break;
  60273. }
  60274. case DUK_RETOK_ATOM_PERIOD: {
  60275. new_atom_char_length = 1;
  60276. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60277. duk__append_u32(re_ctx, DUK_REOP_PERIOD);
  60278. break;
  60279. }
  60280. case DUK_RETOK_ATOM_CHAR: {
  60281. /* Note: successive characters could be joined into string matches
  60282. * but this is not trivial (consider e.g. '/xyz+/); see docs for
  60283. * more discussion.
  60284. */
  60285. duk_uint32_t ch;
  60286. new_atom_char_length = 1;
  60287. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60288. duk__append_u32(re_ctx, DUK_REOP_CHAR);
  60289. ch = re_ctx->curr_token.num;
  60290. if (re_ctx->re_flags & DUK_RE_FLAG_IGNORE_CASE) {
  60291. ch = duk_unicode_re_canonicalize_char(re_ctx->thr, ch);
  60292. }
  60293. duk__append_u32(re_ctx, ch);
  60294. break;
  60295. }
  60296. case DUK_RETOK_ATOM_DIGIT:
  60297. case DUK_RETOK_ATOM_NOT_DIGIT: {
  60298. new_atom_char_length = 1;
  60299. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60300. duk__append_u32(re_ctx,
  60301. (re_ctx->curr_token.t == DUK_RETOK_ATOM_DIGIT) ?
  60302. DUK_REOP_RANGES : DUK_REOP_INVRANGES);
  60303. duk__append_u32(re_ctx, sizeof(duk_unicode_re_ranges_digit) / (2 * sizeof(duk_uint16_t)));
  60304. duk__append_u16_list(re_ctx, duk_unicode_re_ranges_digit, sizeof(duk_unicode_re_ranges_digit) / sizeof(duk_uint16_t));
  60305. break;
  60306. }
  60307. case DUK_RETOK_ATOM_WHITE:
  60308. case DUK_RETOK_ATOM_NOT_WHITE: {
  60309. new_atom_char_length = 1;
  60310. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60311. duk__append_u32(re_ctx,
  60312. (re_ctx->curr_token.t == DUK_RETOK_ATOM_WHITE) ?
  60313. DUK_REOP_RANGES : DUK_REOP_INVRANGES);
  60314. duk__append_u32(re_ctx, sizeof(duk_unicode_re_ranges_white) / (2 * sizeof(duk_uint16_t)));
  60315. duk__append_u16_list(re_ctx, duk_unicode_re_ranges_white, sizeof(duk_unicode_re_ranges_white) / sizeof(duk_uint16_t));
  60316. break;
  60317. }
  60318. case DUK_RETOK_ATOM_WORD_CHAR:
  60319. case DUK_RETOK_ATOM_NOT_WORD_CHAR: {
  60320. new_atom_char_length = 1;
  60321. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60322. duk__append_u32(re_ctx,
  60323. (re_ctx->curr_token.t == DUK_RETOK_ATOM_WORD_CHAR) ?
  60324. DUK_REOP_RANGES : DUK_REOP_INVRANGES);
  60325. duk__append_u32(re_ctx, sizeof(duk_unicode_re_ranges_wordchar) / (2 * sizeof(duk_uint16_t)));
  60326. duk__append_u16_list(re_ctx, duk_unicode_re_ranges_wordchar, sizeof(duk_unicode_re_ranges_wordchar) / sizeof(duk_uint16_t));
  60327. break;
  60328. }
  60329. case DUK_RETOK_ATOM_BACKREFERENCE: {
  60330. duk_uint32_t backref = (duk_uint32_t) re_ctx->curr_token.num;
  60331. if (backref > re_ctx->highest_backref) {
  60332. re_ctx->highest_backref = backref;
  60333. }
  60334. new_atom_char_length = -1; /* mark as complex */
  60335. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60336. duk__append_u32(re_ctx, DUK_REOP_BACKREFERENCE);
  60337. duk__append_u32(re_ctx, backref);
  60338. break;
  60339. }
  60340. case DUK_RETOK_ATOM_START_CAPTURE_GROUP: {
  60341. duk_uint32_t cap;
  60342. new_atom_char_length = -1; /* mark as complex (capture handling) */
  60343. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60344. cap = ++re_ctx->captures;
  60345. duk__append_u32(re_ctx, DUK_REOP_SAVE);
  60346. duk__append_u32(re_ctx, cap * 2);
  60347. duk__parse_disjunction(re_ctx, 0, &tmp_disj); /* retval (sub-atom char length) unused, tainted as complex above */
  60348. duk__append_u32(re_ctx, DUK_REOP_SAVE);
  60349. duk__append_u32(re_ctx, cap * 2 + 1);
  60350. break;
  60351. }
  60352. case DUK_RETOK_ATOM_START_NONCAPTURE_GROUP: {
  60353. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60354. duk__parse_disjunction(re_ctx, 0, &tmp_disj);
  60355. new_atom_char_length = tmp_disj.charlen;
  60356. break;
  60357. }
  60358. case DUK_RETOK_ATOM_START_CHARCLASS:
  60359. case DUK_RETOK_ATOM_START_CHARCLASS_INVERTED: {
  60360. /*
  60361. * Range parsing is done with a special lexer function which calls
  60362. * us for every range parsed. This is different from how rest of
  60363. * the parsing works, but avoids a heavy, arbitrary size intermediate
  60364. * value type to hold the ranges.
  60365. *
  60366. * Another complication is the handling of character ranges when
  60367. * case insensitive matching is used (see docs for discussion).
  60368. * The range handler callback given to the lexer takes care of this
  60369. * as well.
  60370. *
  60371. * Note that duplicate ranges are not eliminated when parsing character
  60372. * classes, so that canonicalization of
  60373. *
  60374. * [0-9a-fA-Fx-{]
  60375. *
  60376. * creates the result (note the duplicate ranges):
  60377. *
  60378. * [0-9A-FA-FX-Z{-{]
  60379. *
  60380. * where [x-{] is split as a result of canonicalization. The duplicate
  60381. * ranges are not a semantics issue: they work correctly.
  60382. */
  60383. duk_uint32_t offset;
  60384. DUK_DD(DUK_DDPRINT("character class"));
  60385. /* insert ranges instruction, range count patched in later */
  60386. new_atom_char_length = 1;
  60387. new_atom_start_offset = (duk_int32_t) DUK__BUFLEN(re_ctx);
  60388. duk__append_u32(re_ctx,
  60389. (re_ctx->curr_token.t == DUK_RETOK_ATOM_START_CHARCLASS) ?
  60390. DUK_REOP_RANGES : DUK_REOP_INVRANGES);
  60391. offset = (duk_uint32_t) DUK__BUFLEN(re_ctx); /* patch in range count later */
  60392. /* parse ranges until character class ends */
  60393. re_ctx->nranges = 0; /* note: ctx-wide temporary */
  60394. duk_lexer_parse_re_ranges(&re_ctx->lex, duk__generate_ranges, (void *) re_ctx);
  60395. /* insert range count */
  60396. duk__insert_u32(re_ctx, offset, re_ctx->nranges);
  60397. break;
  60398. }
  60399. case DUK_RETOK_ATOM_END_GROUP: {
  60400. if (expect_eof) {
  60401. DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  60402. DUK_STR_UNEXPECTED_CLOSING_PAREN);
  60403. }
  60404. goto done;
  60405. }
  60406. case DUK_RETOK_EOF: {
  60407. if (!expect_eof) {
  60408. DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  60409. DUK_STR_UNEXPECTED_END_OF_PATTERN);
  60410. }
  60411. goto done;
  60412. }
  60413. default: {
  60414. DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
  60415. DUK_STR_UNEXPECTED_REGEXP_TOKEN);
  60416. }
  60417. }
  60418. /* a complex (new) atom taints the result */
  60419. if (new_atom_start_offset >= 0) {
  60420. if (new_atom_char_length < 0) {
  60421. res_charlen = -1;
  60422. } else if (res_charlen >= 0) {
  60423. /* only advance if not tainted */
  60424. res_charlen += new_atom_char_length;
  60425. }
  60426. }
  60427. /* record previous atom info in case next token is a quantifier */
  60428. atom_start_offset = new_atom_start_offset;
  60429. atom_char_length = new_atom_char_length;
  60430. atom_start_captures = new_atom_start_captures;
  60431. }
  60432. done:
  60433. /* finish up pending jump and split for last alternative */
  60434. if (unpatched_disjunction_jump >= 0) {
  60435. duk_uint32_t offset;
  60436. DUK_ASSERT(unpatched_disjunction_split >= 0);
  60437. offset = unpatched_disjunction_jump;
  60438. offset += duk__insert_jump_offset(re_ctx,
  60439. offset,
  60440. (duk_int32_t) (DUK__BUFLEN(re_ctx) - offset));
  60441. /* offset is now target of the pending split (right after jump) */
  60442. duk__insert_jump_offset(re_ctx,
  60443. unpatched_disjunction_split,
  60444. offset - unpatched_disjunction_split);
  60445. }
  60446. #if 0
  60447. out_atom_info->end_captures = re_ctx->captures;
  60448. #endif
  60449. out_atom_info->charlen = res_charlen;
  60450. DUK_DDD(DUK_DDDPRINT("parse disjunction finished: charlen=%ld",
  60451. (long) out_atom_info->charlen));
  60452. re_ctx->recursion_depth--;
  60453. }
  60454. /*
  60455. * Flags parsing (see E5 Section 15.10.4.1).
  60456. */
  60457. DUK_LOCAL duk_uint32_t duk__parse_regexp_flags(duk_hthread *thr, duk_hstring *h) {
  60458. const duk_uint8_t *p;
  60459. const duk_uint8_t *p_end;
  60460. duk_uint32_t flags = 0;
  60461. p = DUK_HSTRING_GET_DATA(h);
  60462. p_end = p + DUK_HSTRING_GET_BYTELEN(h);
  60463. /* Note: can be safely scanned as bytes (undecoded) */
  60464. while (p < p_end) {
  60465. duk_uint8_t c = *p++;
  60466. switch ((int) c) {
  60467. case (int) 'g': {
  60468. if (flags & DUK_RE_FLAG_GLOBAL) {
  60469. goto error;
  60470. }
  60471. flags |= DUK_RE_FLAG_GLOBAL;
  60472. break;
  60473. }
  60474. case (int) 'i': {
  60475. if (flags & DUK_RE_FLAG_IGNORE_CASE) {
  60476. goto error;
  60477. }
  60478. flags |= DUK_RE_FLAG_IGNORE_CASE;
  60479. break;
  60480. }
  60481. case (int) 'm': {
  60482. if (flags & DUK_RE_FLAG_MULTILINE) {
  60483. goto error;
  60484. }
  60485. flags |= DUK_RE_FLAG_MULTILINE;
  60486. break;
  60487. }
  60488. default: {
  60489. goto error;
  60490. }
  60491. }
  60492. }
  60493. return flags;
  60494. error:
  60495. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_REGEXP_FLAGS);
  60496. return 0; /* never here */
  60497. }
  60498. /*
  60499. * Create escaped RegExp source (E5 Section 15.10.3).
  60500. *
  60501. * The current approach is to special case the empty RegExp
  60502. * ('' -> '(?:)') and otherwise replace unescaped '/' characters
  60503. * with '\/' regardless of where they occur in the regexp.
  60504. *
  60505. * Note that normalization does not seem to be necessary for
  60506. * RegExp literals (e.g. '/foo/') because to be acceptable as
  60507. * a RegExp literal, the text between forward slashes must
  60508. * already match the escaping requirements (e.g. must not contain
  60509. * unescaped forward slashes or be empty). Escaping IS needed
  60510. * for expressions like 'new Regexp("...", "")' however.
  60511. * Currently, we re-escape in either case.
  60512. *
  60513. * Also note that we process the source here in UTF-8 encoded
  60514. * form. This is correct, because any non-ASCII characters are
  60515. * passed through without change.
  60516. */
  60517. DUK_LOCAL void duk__create_escaped_source(duk_hthread *thr, int idx_pattern) {
  60518. duk_context *ctx = (duk_context *) thr;
  60519. duk_hstring *h;
  60520. duk_hbuffer_dynamic *buf;
  60521. const duk_uint8_t *p;
  60522. duk_size_t i, n;
  60523. duk_uint_fast8_t c_prev, c;
  60524. h = duk_get_hstring(ctx, idx_pattern);
  60525. DUK_ASSERT(h != NULL);
  60526. p = (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h);
  60527. n = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h);
  60528. if (n == 0) {
  60529. /* return '(?:)' */
  60530. duk_push_hstring_stridx(ctx, DUK_STRIDX_ESCAPED_EMPTY_REGEXP);
  60531. return;
  60532. }
  60533. duk_push_dynamic_buffer(ctx, 0);
  60534. buf = (duk_hbuffer_dynamic *) duk_get_hbuffer(ctx, -1);
  60535. DUK_ASSERT(buf != NULL);
  60536. c_prev = (duk_uint_fast8_t) 0;
  60537. for (i = 0; i < n; i++) {
  60538. c = p[i];
  60539. if (c == (duk_uint_fast8_t) '/' && c_prev != (duk_uint_fast8_t) '\\') {
  60540. /* Unescaped '/' ANYWHERE in the regexp (in disjunction,
  60541. * inside a character class, ...) => same escape works.
  60542. */
  60543. duk_hbuffer_append_byte(thr, buf, (duk_uint8_t) '\\');
  60544. }
  60545. duk_hbuffer_append_byte(thr, buf, (duk_uint8_t) c);
  60546. c_prev = c;
  60547. }
  60548. duk_to_string(ctx, -1); /* -> [ ... escaped_source ] */
  60549. }
  60550. /*
  60551. * Exposed regexp compilation primitive.
  60552. *
  60553. * Sets up a regexp compilation context, and calls duk__parse_disjunction() to do the
  60554. * actual parsing. Handles generation of the compiled regexp header and the
  60555. * "boilerplate" capture of the matching substring (save 0 and 1). Also does some
  60556. * global level regexp checks after recursive compilation has finished.
  60557. *
  60558. * An escaped version of the regexp source, suitable for use as a RegExp instance
  60559. * 'source' property (see E5 Section 15.10.3), is also left on the stack.
  60560. *
  60561. * Input stack: [ pattern flags ]
  60562. * Output stack: [ bytecode escaped_source ] (both as strings)
  60563. */
  60564. DUK_INTERNAL void duk_regexp_compile(duk_hthread *thr) {
  60565. duk_context *ctx = (duk_context *) thr;
  60566. duk_re_compiler_ctx re_ctx;
  60567. duk_lexer_point lex_point;
  60568. duk_hstring *h_pattern;
  60569. duk_hstring *h_flags;
  60570. duk_hbuffer_dynamic *h_buffer;
  60571. duk__re_disjunction_info ign_disj;
  60572. DUK_ASSERT(thr != NULL);
  60573. DUK_ASSERT(ctx != NULL);
  60574. /*
  60575. * Args validation
  60576. */
  60577. /* TypeError if fails */
  60578. h_pattern = duk_require_hstring(ctx, -2);
  60579. h_flags = duk_require_hstring(ctx, -1);
  60580. /*
  60581. * Create normalized 'source' property (E5 Section 15.10.3).
  60582. */
  60583. /* [ ... pattern flags ] */
  60584. duk__create_escaped_source(thr, -2);
  60585. /* [ ... pattern flags escaped_source ] */
  60586. /*
  60587. * Init compilation context
  60588. */
  60589. duk_push_dynamic_buffer(ctx, 0);
  60590. h_buffer = (duk_hbuffer_dynamic *) duk_require_hbuffer(ctx, -1);
  60591. DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(h_buffer));
  60592. /* [ ... pattern flags escaped_source buffer ] */
  60593. DUK_MEMZERO(&re_ctx, sizeof(re_ctx));
  60594. DUK_LEXER_INITCTX(&re_ctx.lex); /* duplicate zeroing, expect for (possible) NULL inits */
  60595. re_ctx.thr = thr;
  60596. re_ctx.lex.thr = thr;
  60597. re_ctx.lex.input = DUK_HSTRING_GET_DATA(h_pattern);
  60598. re_ctx.lex.input_length = DUK_HSTRING_GET_BYTELEN(h_pattern);
  60599. re_ctx.lex.token_limit = DUK_RE_COMPILE_TOKEN_LIMIT;
  60600. re_ctx.buf = h_buffer;
  60601. re_ctx.recursion_limit = DUK_RE_COMPILE_RECURSION_LIMIT;
  60602. re_ctx.re_flags = duk__parse_regexp_flags(thr, h_flags);
  60603. DUK_DD(DUK_DDPRINT("regexp compiler ctx initialized, flags=0x%08lx, recursion_limit=%ld",
  60604. (unsigned long) re_ctx.re_flags, (long) re_ctx.recursion_limit));
  60605. /*
  60606. * Init lexer
  60607. */
  60608. lex_point.offset = 0; /* expensive init, just want to fill window */
  60609. lex_point.line = 1;
  60610. DUK_LEXER_SETPOINT(&re_ctx.lex, &lex_point);
  60611. /*
  60612. * Compilation
  60613. */
  60614. DUK_D(DUK_DPRINT("starting regexp compilation"));
  60615. duk__append_u32(&re_ctx, DUK_REOP_SAVE);
  60616. duk__append_u32(&re_ctx, 0);
  60617. duk__parse_disjunction(&re_ctx, 1 /*expect_eof*/, &ign_disj);
  60618. duk__append_u32(&re_ctx, DUK_REOP_SAVE);
  60619. duk__append_u32(&re_ctx, 1);
  60620. duk__append_u32(&re_ctx, DUK_REOP_MATCH);
  60621. DUK_D(DUK_DPRINT("regexp bytecode size (before header) is %ld bytes",
  60622. (long) DUK_HBUFFER_GET_SIZE(re_ctx.buf)));
  60623. /*
  60624. * Check for invalid backreferences; note that it is NOT an error
  60625. * to back-reference a capture group which has not yet been introduced
  60626. * in the pattern (as in /\1(foo)/); in fact, the backreference will
  60627. * always match! It IS an error to back-reference a capture group
  60628. * which will never be introduced in the pattern. Thus, we can check
  60629. * for such references only after parsing is complete.
  60630. */
  60631. if (re_ctx.highest_backref > re_ctx.captures) {
  60632. DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_BACKREFS);
  60633. }
  60634. /*
  60635. * Emit compiled regexp header: flags, ncaptures
  60636. * (insertion order inverted on purpose)
  60637. */
  60638. duk__insert_u32(&re_ctx, 0, (re_ctx.captures + 1) * 2);
  60639. duk__insert_u32(&re_ctx, 0, re_ctx.re_flags);
  60640. DUK_D(DUK_DPRINT("regexp bytecode size (after header) is %ld bytes",
  60641. (long) DUK_HBUFFER_GET_SIZE(re_ctx.buf)));
  60642. DUK_DDD(DUK_DDDPRINT("compiled regexp: %!xO", (duk_heaphdr *) re_ctx.buf));
  60643. /* [ ... pattern flags escaped_source buffer ] */
  60644. duk_to_string(ctx, -1); /* coerce to string */
  60645. /* [ ... pattern flags escaped_source bytecode ] */
  60646. /*
  60647. * Finalize stack
  60648. */
  60649. duk_remove(ctx, -4); /* -> [ ... flags escaped_source bytecode ] */
  60650. duk_remove(ctx, -3); /* -> [ ... escaped_source bytecode ] */
  60651. DUK_D(DUK_DPRINT("regexp compilation successful, bytecode: %!T, escaped source: %!T",
  60652. (duk_tval *) duk_get_tval(ctx, -1), (duk_tval *) duk_get_tval(ctx, -2)));
  60653. }
  60654. /*
  60655. * Create a RegExp instance (E5 Section 15.10.7).
  60656. *
  60657. * Note: the output stack left by duk_regexp_compile() is directly compatible
  60658. * with the input here.
  60659. *
  60660. * Input stack: [ escaped_source bytecode ] (both as strings)
  60661. * Output stack: [ RegExp ]
  60662. */
  60663. DUK_INTERNAL void duk_regexp_create_instance(duk_hthread *thr) {
  60664. duk_context *ctx = (duk_context *) thr;
  60665. duk_hobject *h;
  60666. duk_hstring *h_bc;
  60667. duk_small_int_t re_flags;
  60668. /* [ ... escape_source bytecode ] */
  60669. h_bc = duk_get_hstring(ctx, -1);
  60670. DUK_ASSERT(h_bc != NULL);
  60671. DUK_ASSERT(DUK_HSTRING_GET_BYTELEN(h_bc) >= 1); /* always at least the header */
  60672. DUK_ASSERT(DUK_HSTRING_GET_CHARLEN(h_bc) >= 1);
  60673. DUK_ASSERT((duk_small_int_t) DUK_HSTRING_GET_DATA(h_bc)[0] < 0x80); /* flags always encodes to 1 byte */
  60674. re_flags = (duk_small_int_t) DUK_HSTRING_GET_DATA(h_bc)[0];
  60675. /* [ ... escaped_source bytecode ] */
  60676. duk_push_object(ctx);
  60677. h = duk_get_hobject(ctx, -1);
  60678. DUK_ASSERT(h != NULL);
  60679. duk_insert(ctx, -3);
  60680. /* [ ... regexp_object escaped_source bytecode ] */
  60681. DUK_HOBJECT_SET_CLASS_NUMBER(h, DUK_HOBJECT_CLASS_REGEXP);
  60682. DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, h, thr->builtins[DUK_BIDX_REGEXP_PROTOTYPE]);
  60683. duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_INT_BYTECODE, DUK_PROPDESC_FLAGS_NONE);
  60684. /* [ ... regexp_object escaped_source ] */
  60685. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_SOURCE, DUK_PROPDESC_FLAGS_NONE);
  60686. /* [ ... regexp_object ] */
  60687. duk_push_boolean(ctx, (re_flags & DUK_RE_FLAG_GLOBAL));
  60688. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_GLOBAL, DUK_PROPDESC_FLAGS_NONE);
  60689. duk_push_boolean(ctx, (re_flags & DUK_RE_FLAG_IGNORE_CASE));
  60690. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_IGNORE_CASE, DUK_PROPDESC_FLAGS_NONE);
  60691. duk_push_boolean(ctx, (re_flags & DUK_RE_FLAG_MULTILINE));
  60692. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_MULTILINE, DUK_PROPDESC_FLAGS_NONE);
  60693. duk_push_int(ctx, 0);
  60694. duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LAST_INDEX, DUK_PROPDESC_FLAGS_W);
  60695. /* [ ... regexp_object ] */
  60696. }
  60697. #undef DUK__BUFLEN
  60698. #else /* DUK_USE_REGEXP_SUPPORT */
  60699. /* regexp support disabled */
  60700. #endif /* DUK_USE_REGEXP_SUPPORT */
  60701. #line 1 "duk_regexp_executor.c"
  60702. /*
  60703. * Regexp executor.
  60704. *
  60705. * Safety: the Ecmascript executor should prevent user from reading and
  60706. * replacing regexp bytecode. Even so, the executor must validate all
  60707. * memory accesses etc. When an invalid access is detected (e.g. a 'save'
  60708. * opcode to invalid, unallocated index) it should fail with an internal
  60709. * error but not cause a segmentation fault.
  60710. *
  60711. * Notes:
  60712. *
  60713. * - Backtrack counts are limited to unsigned 32 bits but should
  60714. * technically be duk_size_t for strings longer than 4G chars.
  60715. * This also requires a regexp bytecode change.
  60716. */
  60717. /* include removed: duk_internal.h */
  60718. #ifdef DUK_USE_REGEXP_SUPPORT
  60719. /*
  60720. * Helpers for UTF-8 handling
  60721. *
  60722. * For bytecode readers the duk_uint32_t and duk_int32_t types are correct
  60723. * because they're used for more than just codepoints.
  60724. */
  60725. DUK_LOCAL duk_uint32_t duk__bc_get_u32(duk_re_matcher_ctx *re_ctx, const duk_uint8_t **pc) {
  60726. return (duk_uint32_t) duk_unicode_decode_xutf8_checked(re_ctx->thr, pc, re_ctx->bytecode, re_ctx->bytecode_end);
  60727. }
  60728. DUK_LOCAL duk_int32_t duk__bc_get_i32(duk_re_matcher_ctx *re_ctx, const duk_uint8_t **pc) {
  60729. duk_uint32_t t;
  60730. /* signed integer encoding needed to work with UTF-8 */
  60731. t = (duk_uint32_t) duk_unicode_decode_xutf8_checked(re_ctx->thr, pc, re_ctx->bytecode, re_ctx->bytecode_end);
  60732. if (t & 1) {
  60733. return -((duk_int32_t) (t >> 1));
  60734. } else {
  60735. return (duk_int32_t) (t >> 1);
  60736. }
  60737. }
  60738. DUK_LOCAL const duk_uint8_t *duk__utf8_backtrack(duk_hthread *thr, const duk_uint8_t **ptr, const duk_uint8_t *ptr_start, const duk_uint8_t *ptr_end, duk_uint_fast32_t count) {
  60739. const duk_uint8_t *p;
  60740. /* Note: allow backtracking from p == ptr_end */
  60741. p = *ptr;
  60742. if (p < ptr_start || p > ptr_end) {
  60743. goto fail;
  60744. }
  60745. while (count > 0) {
  60746. for (;;) {
  60747. p--;
  60748. if (p < ptr_start) {
  60749. goto fail;
  60750. }
  60751. if ((*p & 0xc0) != 0x80) {
  60752. /* utf-8 continuation bytes have the form 10xx xxxx */
  60753. break;
  60754. }
  60755. }
  60756. count--;
  60757. }
  60758. *ptr = p;
  60759. return p;
  60760. fail:
  60761. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_REGEXP_BACKTRACK_FAILED);
  60762. return NULL; /* never here */
  60763. }
  60764. DUK_LOCAL const duk_uint8_t *duk__utf8_advance(duk_hthread *thr, const duk_uint8_t **ptr, const duk_uint8_t *ptr_start, const duk_uint8_t *ptr_end, duk_uint_fast32_t count) {
  60765. const duk_uint8_t *p;
  60766. p = *ptr;
  60767. if (p < ptr_start || p >= ptr_end) {
  60768. goto fail;
  60769. }
  60770. while (count > 0) {
  60771. for (;;) {
  60772. p++;
  60773. /* Note: if encoding ends by hitting end of input, we don't check that
  60774. * the encoding is valid, we just assume it is.
  60775. */
  60776. if (p >= ptr_end || ((*p & 0xc0) != 0x80)) {
  60777. /* utf-8 continuation bytes have the form 10xx xxxx */
  60778. break;
  60779. }
  60780. }
  60781. count--;
  60782. }
  60783. *ptr = p;
  60784. return p;
  60785. fail:
  60786. DUK_ERROR(thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_REGEXP_ADVANCE_FAILED);
  60787. return NULL; /* never here */
  60788. }
  60789. /*
  60790. * Helpers for dealing with the input string
  60791. */
  60792. /* Get a (possibly canonicalized) input character from current sp. The input
  60793. * itself is never modified, and captures always record non-canonicalized
  60794. * characters even in case-insensitive matching.
  60795. */
  60796. DUK_LOCAL duk_codepoint_t duk__inp_get_cp(duk_re_matcher_ctx *re_ctx, const duk_uint8_t **sp) {
  60797. duk_codepoint_t res = (duk_codepoint_t) duk_unicode_decode_xutf8_checked(re_ctx->thr, sp, re_ctx->input, re_ctx->input_end);
  60798. if (re_ctx->re_flags & DUK_RE_FLAG_IGNORE_CASE) {
  60799. res = duk_unicode_re_canonicalize_char(re_ctx->thr, res);
  60800. }
  60801. return res;
  60802. }
  60803. DUK_LOCAL const duk_uint8_t *duk__inp_backtrack(duk_re_matcher_ctx *re_ctx, const duk_uint8_t **sp, duk_uint_fast32_t count) {
  60804. return duk__utf8_backtrack(re_ctx->thr, sp, re_ctx->input, re_ctx->input_end, count);
  60805. }
  60806. /* Backtrack utf-8 input and return a (possibly canonicalized) input character. */
  60807. DUK_LOCAL duk_codepoint_t duk__inp_get_prev_cp(duk_re_matcher_ctx *re_ctx, const duk_uint8_t *sp) {
  60808. /* note: caller 'sp' is intentionally not updated here */
  60809. (void) duk__inp_backtrack(re_ctx, &sp, (duk_uint_fast32_t) 1);
  60810. return duk__inp_get_cp(re_ctx, &sp);
  60811. }
  60812. /*
  60813. * Regexp recursive matching function.
  60814. *
  60815. * Returns 'sp' on successful match (points to character after last matched one),
  60816. * NULL otherwise.
  60817. *
  60818. * The C recursion depth limit check is only performed in this function, this
  60819. * suffices because the function is present in all true recursion required by
  60820. * regexp execution.
  60821. */
  60822. DUK_LOCAL const duk_uint8_t *duk__match_regexp(duk_re_matcher_ctx *re_ctx, const duk_uint8_t *pc, const duk_uint8_t *sp) {
  60823. if (re_ctx->recursion_depth >= re_ctx->recursion_limit) {
  60824. DUK_ERROR(re_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_REGEXP_EXECUTOR_RECURSION_LIMIT);
  60825. }
  60826. re_ctx->recursion_depth++;
  60827. for (;;) {
  60828. duk_small_int_t op;
  60829. if (re_ctx->steps_count >= re_ctx->steps_limit) {
  60830. DUK_ERROR(re_ctx->thr, DUK_ERR_RANGE_ERROR, DUK_STR_REGEXP_EXECUTOR_STEP_LIMIT);
  60831. }
  60832. re_ctx->steps_count++;
  60833. op = (duk_small_int_t) duk__bc_get_u32(re_ctx, &pc);
  60834. DUK_DDD(DUK_DDDPRINT("match: rec=%ld, steps=%ld, pc (after op)=%ld, sp=%ld, op=%ld",
  60835. (long) re_ctx->recursion_depth,
  60836. (long) re_ctx->steps_count,
  60837. (long) (pc - re_ctx->bytecode),
  60838. (long) (sp - re_ctx->input),
  60839. (long) op));
  60840. switch (op) {
  60841. case DUK_REOP_MATCH: {
  60842. goto match;
  60843. }
  60844. case DUK_REOP_CHAR: {
  60845. /*
  60846. * Byte-based matching would be possible for case-sensitive
  60847. * matching but not for case-insensitive matching. So, we
  60848. * match by decoding the input and bytecode character normally.
  60849. *
  60850. * Bytecode characters are assumed to be already canonicalized.
  60851. * Input characters are canonicalized automatically by
  60852. * duk__inp_get_cp() if necessary.
  60853. *
  60854. * There is no opcode for matching multiple characters. The
  60855. * regexp compiler has trouble joining strings efficiently
  60856. * during compilation. See doc/regexp.txt for more discussion.
  60857. */
  60858. duk_codepoint_t c1, c2;
  60859. c1 = (duk_codepoint_t) duk__bc_get_u32(re_ctx, &pc);
  60860. DUK_ASSERT(!(re_ctx->re_flags & DUK_RE_FLAG_IGNORE_CASE) ||
  60861. c1 == duk_unicode_re_canonicalize_char(re_ctx->thr, c1)); /* canonicalized by compiler */
  60862. if (sp >= re_ctx->input_end) {
  60863. goto fail;
  60864. }
  60865. c2 = duk__inp_get_cp(re_ctx, &sp);
  60866. DUK_DDD(DUK_DDDPRINT("char match, c1=%ld, c2=%ld", (long) c1, (long) c2));
  60867. if (c1 != c2) {
  60868. goto fail;
  60869. }
  60870. break;
  60871. }
  60872. case DUK_REOP_PERIOD: {
  60873. duk_codepoint_t c;
  60874. if (sp >= re_ctx->input_end) {
  60875. goto fail;
  60876. }
  60877. c = duk__inp_get_cp(re_ctx, &sp);
  60878. if (duk_unicode_is_line_terminator(c)) {
  60879. /* E5 Sections 15.10.2.8, 7.3 */
  60880. goto fail;
  60881. }
  60882. break;
  60883. }
  60884. case DUK_REOP_RANGES:
  60885. case DUK_REOP_INVRANGES: {
  60886. duk_uint32_t n;
  60887. duk_codepoint_t c;
  60888. duk_small_int_t match;
  60889. n = duk__bc_get_u32(re_ctx, &pc);
  60890. if (sp >= re_ctx->input_end) {
  60891. goto fail;
  60892. }
  60893. c = duk__inp_get_cp(re_ctx, &sp);
  60894. match = 0;
  60895. while (n) {
  60896. duk_codepoint_t r1, r2;
  60897. r1 = (duk_codepoint_t) duk__bc_get_u32(re_ctx, &pc);
  60898. r2 = (duk_codepoint_t) duk__bc_get_u32(re_ctx, &pc);
  60899. DUK_DDD(DUK_DDDPRINT("matching ranges/invranges, n=%ld, r1=%ld, r2=%ld, c=%ld",
  60900. (long) n, (long) r1, (long) r2, (long) c));
  60901. if (c >= r1 && c <= r2) {
  60902. /* Note: don't bail out early, we must read all the ranges from
  60903. * bytecode. Another option is to skip them efficiently after
  60904. * breaking out of here. Prefer smallest code.
  60905. */
  60906. match = 1;
  60907. }
  60908. n--;
  60909. }
  60910. if (op == DUK_REOP_RANGES) {
  60911. if (!match) {
  60912. goto fail;
  60913. }
  60914. } else {
  60915. DUK_ASSERT(op == DUK_REOP_INVRANGES);
  60916. if (match) {
  60917. goto fail;
  60918. }
  60919. }
  60920. break;
  60921. }
  60922. case DUK_REOP_ASSERT_START: {
  60923. duk_codepoint_t c;
  60924. if (sp <= re_ctx->input) {
  60925. break;
  60926. }
  60927. if (!(re_ctx->re_flags & DUK_RE_FLAG_MULTILINE)) {
  60928. goto fail;
  60929. }
  60930. c = duk__inp_get_prev_cp(re_ctx, sp);
  60931. if (duk_unicode_is_line_terminator(c)) {
  60932. /* E5 Sections 15.10.2.8, 7.3 */
  60933. break;
  60934. }
  60935. goto fail;
  60936. }
  60937. case DUK_REOP_ASSERT_END: {
  60938. duk_codepoint_t c;
  60939. const duk_uint8_t *tmp_sp;
  60940. if (sp >= re_ctx->input_end) {
  60941. break;
  60942. }
  60943. if (!(re_ctx->re_flags & DUK_RE_FLAG_MULTILINE)) {
  60944. goto fail;
  60945. }
  60946. tmp_sp = sp;
  60947. c = duk__inp_get_cp(re_ctx, &tmp_sp);
  60948. if (duk_unicode_is_line_terminator(c)) {
  60949. /* E5 Sections 15.10.2.8, 7.3 */
  60950. break;
  60951. }
  60952. goto fail;
  60953. }
  60954. case DUK_REOP_ASSERT_WORD_BOUNDARY:
  60955. case DUK_REOP_ASSERT_NOT_WORD_BOUNDARY: {
  60956. /*
  60957. * E5 Section 15.10.2.6. The previous and current character
  60958. * should -not- be canonicalized as they are now. However,
  60959. * canonicalization does not affect the result of IsWordChar()
  60960. * (which depends on Unicode characters never canonicalizing
  60961. * into ASCII characters) so this does not matter.
  60962. */
  60963. duk_small_int_t w1, w2;
  60964. if (sp <= re_ctx->input) {
  60965. w1 = 0; /* not a wordchar */
  60966. } else {
  60967. duk_codepoint_t c;
  60968. c = duk__inp_get_prev_cp(re_ctx, sp);
  60969. w1 = duk_unicode_re_is_wordchar(c);
  60970. }
  60971. if (sp >= re_ctx->input_end) {
  60972. w2 = 0; /* not a wordchar */
  60973. } else {
  60974. const duk_uint8_t *tmp_sp = sp; /* dummy so sp won't get updated */
  60975. duk_codepoint_t c;
  60976. c = duk__inp_get_cp(re_ctx, &tmp_sp);
  60977. w2 = duk_unicode_re_is_wordchar(c);
  60978. }
  60979. if (op == DUK_REOP_ASSERT_WORD_BOUNDARY) {
  60980. if (w1 == w2) {
  60981. goto fail;
  60982. }
  60983. } else {
  60984. DUK_ASSERT(op == DUK_REOP_ASSERT_NOT_WORD_BOUNDARY);
  60985. if (w1 != w2) {
  60986. goto fail;
  60987. }
  60988. }
  60989. break;
  60990. }
  60991. case DUK_REOP_JUMP: {
  60992. duk_int32_t skip;
  60993. skip = duk__bc_get_i32(re_ctx, &pc);
  60994. pc += skip;
  60995. break;
  60996. }
  60997. case DUK_REOP_SPLIT1: {
  60998. /* split1: prefer direct execution (no jump) */
  60999. const duk_uint8_t *sub_sp;
  61000. duk_int32_t skip;
  61001. skip = duk__bc_get_i32(re_ctx, &pc);
  61002. sub_sp = duk__match_regexp(re_ctx, pc, sp);
  61003. if (sub_sp) {
  61004. sp = sub_sp;
  61005. goto match;
  61006. }
  61007. pc += skip;
  61008. break;
  61009. }
  61010. case DUK_REOP_SPLIT2: {
  61011. /* split2: prefer jump execution (not direct) */
  61012. const duk_uint8_t *sub_sp;
  61013. duk_int32_t skip;
  61014. skip = duk__bc_get_i32(re_ctx, &pc);
  61015. sub_sp = duk__match_regexp(re_ctx, pc + skip, sp);
  61016. if (sub_sp) {
  61017. sp = sub_sp;
  61018. goto match;
  61019. }
  61020. break;
  61021. }
  61022. case DUK_REOP_SQMINIMAL: {
  61023. duk_uint32_t q, qmin, qmax;
  61024. duk_int32_t skip;
  61025. const duk_uint8_t *sub_sp;
  61026. qmin = duk__bc_get_u32(re_ctx, &pc);
  61027. qmax = duk__bc_get_u32(re_ctx, &pc);
  61028. skip = duk__bc_get_i32(re_ctx, &pc);
  61029. DUK_DDD(DUK_DDDPRINT("minimal quantifier, qmin=%lu, qmax=%lu, skip=%ld",
  61030. (unsigned long) qmin, (unsigned long) qmax, (long) skip));
  61031. q = 0;
  61032. while (q <= qmax) {
  61033. if (q >= qmin) {
  61034. sub_sp = duk__match_regexp(re_ctx, pc + skip, sp);
  61035. if (sub_sp) {
  61036. sp = sub_sp;
  61037. goto match;
  61038. }
  61039. }
  61040. sub_sp = duk__match_regexp(re_ctx, pc, sp);
  61041. if (!sub_sp) {
  61042. break;
  61043. }
  61044. sp = sub_sp;
  61045. q++;
  61046. }
  61047. goto fail;
  61048. }
  61049. case DUK_REOP_SQGREEDY: {
  61050. duk_uint32_t q, qmin, qmax, atomlen;
  61051. duk_int32_t skip;
  61052. const duk_uint8_t *sub_sp;
  61053. qmin = duk__bc_get_u32(re_ctx, &pc);
  61054. qmax = duk__bc_get_u32(re_ctx, &pc);
  61055. atomlen = duk__bc_get_u32(re_ctx, &pc);
  61056. skip = duk__bc_get_i32(re_ctx, &pc);
  61057. DUK_DDD(DUK_DDDPRINT("greedy quantifier, qmin=%lu, qmax=%lu, atomlen=%lu, skip=%ld",
  61058. (unsigned long) qmin, (unsigned long) qmax, (unsigned long) atomlen, (long) skip));
  61059. q = 0;
  61060. while (q < qmax) {
  61061. sub_sp = duk__match_regexp(re_ctx, pc, sp);
  61062. if (!sub_sp) {
  61063. break;
  61064. }
  61065. sp = sub_sp;
  61066. q++;
  61067. }
  61068. while (q >= qmin) {
  61069. sub_sp = duk__match_regexp(re_ctx, pc + skip, sp);
  61070. if (sub_sp) {
  61071. sp = sub_sp;
  61072. goto match;
  61073. }
  61074. if (q == qmin) {
  61075. break;
  61076. }
  61077. /* Note: if atom were to contain e.g. captures, we would need to
  61078. * re-match the atom to get correct captures. Simply quantifiers
  61079. * do not allow captures in their atom now, so this is not an issue.
  61080. */
  61081. DUK_DDD(DUK_DDDPRINT("greedy quantifier, backtrack %ld characters (atomlen)",
  61082. (long) atomlen));
  61083. sp = duk__inp_backtrack(re_ctx, &sp, (duk_uint_fast32_t) atomlen);
  61084. q--;
  61085. }
  61086. goto fail;
  61087. }
  61088. case DUK_REOP_SAVE: {
  61089. duk_uint32_t idx;
  61090. const duk_uint8_t *old;
  61091. const duk_uint8_t *sub_sp;
  61092. idx = duk__bc_get_u32(re_ctx, &pc);
  61093. if (idx >= re_ctx->nsaved) {
  61094. /* idx is unsigned, < 0 check is not necessary */
  61095. DUK_D(DUK_DPRINT("internal error, regexp save index insane: idx=%ld", (long) idx));
  61096. goto internal_error;
  61097. }
  61098. old = re_ctx->saved[idx];
  61099. re_ctx->saved[idx] = sp;
  61100. sub_sp = duk__match_regexp(re_ctx, pc, sp);
  61101. if (sub_sp) {
  61102. sp = sub_sp;
  61103. goto match;
  61104. }
  61105. re_ctx->saved[idx] = old;
  61106. goto fail;
  61107. }
  61108. case DUK_REOP_WIPERANGE: {
  61109. /* Wipe capture range and save old values for backtracking.
  61110. *
  61111. * XXX: this typically happens with a relatively small idx_count.
  61112. * It might be useful to handle cases where the count is small
  61113. * (say <= 8) by saving the values in stack instead. This would
  61114. * reduce memory churn and improve performance, at the cost of a
  61115. * slightly higher code footprint.
  61116. */
  61117. duk_uint32_t idx_start, idx_count;
  61118. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  61119. duk_uint32_t idx_end, idx;
  61120. #endif
  61121. duk_uint8_t **range_save;
  61122. const duk_uint8_t *sub_sp;
  61123. idx_start = duk__bc_get_u32(re_ctx, &pc);
  61124. idx_count = duk__bc_get_u32(re_ctx, &pc);
  61125. DUK_DDD(DUK_DDDPRINT("wipe saved range: start=%ld, count=%ld -> [%ld,%ld] (captures [%ld,%ld])",
  61126. (long) idx_start, (long) idx_count,
  61127. (long) idx_start, (long) (idx_start + idx_count - 1),
  61128. (long) (idx_start / 2), (long) ((idx_start + idx_count - 1) / 2)));
  61129. if (idx_start + idx_count > re_ctx->nsaved || idx_count == 0) {
  61130. /* idx is unsigned, < 0 check is not necessary */
  61131. DUK_D(DUK_DPRINT("internal error, regexp wipe indices insane: idx_start=%ld, idx_count=%ld",
  61132. (long) idx_start, (long) idx_count));
  61133. goto internal_error;
  61134. }
  61135. DUK_ASSERT(idx_count > 0);
  61136. duk_require_stack((duk_context *) re_ctx->thr, 1);
  61137. range_save = (duk_uint8_t **) duk_push_fixed_buffer((duk_context *) re_ctx->thr,
  61138. sizeof(duk_uint8_t *) * idx_count);
  61139. DUK_ASSERT(range_save != NULL);
  61140. DUK_MEMCPY(range_save, re_ctx->saved + idx_start, sizeof(duk_uint8_t *) * idx_count);
  61141. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  61142. idx_end = idx_start + idx_count;
  61143. for (idx = idx_start; idx < idx_end; idx++) {
  61144. re_ctx->saved[idx] = NULL;
  61145. }
  61146. #else
  61147. DUK_MEMZERO((void *) (re_ctx->saved + idx_start), sizeof(duk_uint8_t *) * idx_count);
  61148. #endif
  61149. sub_sp = duk__match_regexp(re_ctx, pc, sp);
  61150. if (sub_sp) {
  61151. /* match: keep wiped/resaved values */
  61152. DUK_DDD(DUK_DDDPRINT("match: keep wiped/resaved values [%ld,%ld] (captures [%ld,%ld])",
  61153. (long) idx_start, (long) (idx_start + idx_count - 1),
  61154. (long) (idx_start / 2), (long) ((idx_start + idx_count - 1) / 2)));
  61155. duk_pop((duk_context *) re_ctx->thr);
  61156. sp = sub_sp;
  61157. goto match;
  61158. }
  61159. /* fail: restore saves */
  61160. DUK_DDD(DUK_DDDPRINT("fail: restore wiped/resaved values [%ld,%ld] (captures [%ld,%ld])",
  61161. (long) idx_start, (long) (idx_start + idx_count - 1),
  61162. (long) (idx_start / 2), (long) ((idx_start + idx_count - 1) / 2)));
  61163. DUK_MEMCPY((void *) (re_ctx->saved + idx_start),
  61164. (const void *) range_save,
  61165. sizeof(duk_uint8_t *) * idx_count);
  61166. duk_pop((duk_context *) re_ctx->thr);
  61167. goto fail;
  61168. }
  61169. case DUK_REOP_LOOKPOS:
  61170. case DUK_REOP_LOOKNEG: {
  61171. /*
  61172. * Needs a save of multiple saved[] entries depending on what range
  61173. * may be overwritten. Because the regexp parser does no such analysis,
  61174. * we currently save the entire saved array here. Lookaheads are thus
  61175. * a bit expensive. Note that the saved array is not needed for just
  61176. * the lookahead sub-match, but for the matching of the entire sequel.
  61177. *
  61178. * The temporary save buffer is pushed on to the valstack to handle
  61179. * errors correctly. Each lookahead causes a C recursion and pushes
  61180. * more stuff on the value stack. If the C recursion limit is less
  61181. * than the value stack spare, there is no need to check the stack.
  61182. * We do so regardless, just in case.
  61183. */
  61184. duk_int32_t skip;
  61185. duk_uint8_t **full_save;
  61186. const duk_uint8_t *sub_sp;
  61187. DUK_ASSERT(re_ctx->nsaved > 0);
  61188. duk_require_stack((duk_context *) re_ctx->thr, 1);
  61189. full_save = (duk_uint8_t **) duk_push_fixed_buffer((duk_context *) re_ctx->thr,
  61190. sizeof(duk_uint8_t *) * re_ctx->nsaved);
  61191. DUK_ASSERT(full_save != NULL);
  61192. DUK_MEMCPY(full_save, re_ctx->saved, sizeof(duk_uint8_t *) * re_ctx->nsaved);
  61193. skip = duk__bc_get_i32(re_ctx, &pc);
  61194. sub_sp = duk__match_regexp(re_ctx, pc, sp);
  61195. if (op == DUK_REOP_LOOKPOS) {
  61196. if (!sub_sp) {
  61197. goto lookahead_fail;
  61198. }
  61199. } else {
  61200. if (sub_sp) {
  61201. goto lookahead_fail;
  61202. }
  61203. }
  61204. sub_sp = duk__match_regexp(re_ctx, pc + skip, sp);
  61205. if (sub_sp) {
  61206. /* match: keep saves */
  61207. duk_pop((duk_context *) re_ctx->thr);
  61208. sp = sub_sp;
  61209. goto match;
  61210. }
  61211. /* fall through */
  61212. lookahead_fail:
  61213. /* fail: restore saves */
  61214. DUK_MEMCPY((void *) re_ctx->saved,
  61215. (const void *) full_save,
  61216. sizeof(duk_uint8_t *) * re_ctx->nsaved);
  61217. duk_pop((duk_context *) re_ctx->thr);
  61218. goto fail;
  61219. }
  61220. case DUK_REOP_BACKREFERENCE: {
  61221. /*
  61222. * Byte matching for back-references would be OK in case-
  61223. * sensitive matching. In case-insensitive matching we need
  61224. * to canonicalize characters, so back-reference matching needs
  61225. * to be done with codepoints instead. So, we just decode
  61226. * everything normally here, too.
  61227. *
  61228. * Note: back-reference index which is 0 or higher than
  61229. * NCapturingParens (= number of capturing parens in the
  61230. * -entire- regexp) is a compile time error. However, a
  61231. * backreference referring to a valid capture which has
  61232. * not matched anything always succeeds! See E5 Section
  61233. * 15.10.2.9, step 5, sub-step 3.
  61234. */
  61235. duk_uint32_t idx;
  61236. const duk_uint8_t *p;
  61237. idx = duk__bc_get_u32(re_ctx, &pc);
  61238. idx = idx << 1; /* backref n -> saved indices [n*2, n*2+1] */
  61239. if (idx < 2 || idx + 1 >= re_ctx->nsaved) {
  61240. /* regexp compiler should catch these */
  61241. DUK_D(DUK_DPRINT("internal error, backreference index insane"));
  61242. goto internal_error;
  61243. }
  61244. if (!re_ctx->saved[idx] || !re_ctx->saved[idx+1]) {
  61245. /* capture is 'undefined', always matches! */
  61246. DUK_DDD(DUK_DDDPRINT("backreference: saved[%ld,%ld] not complete, always match",
  61247. (long) idx, (long) (idx + 1)));
  61248. break;
  61249. }
  61250. DUK_DDD(DUK_DDDPRINT("backreference: match saved[%ld,%ld]", (long) idx, (long) (idx + 1)));
  61251. p = re_ctx->saved[idx];
  61252. while (p < re_ctx->saved[idx+1]) {
  61253. duk_codepoint_t c1, c2;
  61254. /* Note: not necessary to check p against re_ctx->input_end:
  61255. * the memory access is checked by duk__inp_get_cp(), while
  61256. * valid compiled regexps cannot write a saved[] entry
  61257. * which points to outside the string.
  61258. */
  61259. if (sp >= re_ctx->input_end) {
  61260. goto fail;
  61261. }
  61262. c1 = duk__inp_get_cp(re_ctx, &p);
  61263. c2 = duk__inp_get_cp(re_ctx, &sp);
  61264. if (c1 != c2) {
  61265. goto fail;
  61266. }
  61267. }
  61268. break;
  61269. }
  61270. default: {
  61271. DUK_D(DUK_DPRINT("internal error, regexp opcode error: %ld", (long) op));
  61272. goto internal_error;
  61273. }
  61274. }
  61275. }
  61276. match:
  61277. re_ctx->recursion_depth--;
  61278. return sp;
  61279. fail:
  61280. re_ctx->recursion_depth--;
  61281. return NULL;
  61282. internal_error:
  61283. DUK_ERROR(re_ctx->thr, DUK_ERR_INTERNAL_ERROR, DUK_STR_REGEXP_INTERNAL_ERROR);
  61284. return NULL; /* never here */
  61285. }
  61286. /*
  61287. * Exposed matcher function which provides the semantics of RegExp.prototype.exec().
  61288. *
  61289. * RegExp.prototype.test() has the same semantics as exec() but does not return the
  61290. * result object (which contains the matching string and capture groups). Currently
  61291. * there is no separate test() helper, so a temporary result object is created and
  61292. * discarded if test() is needed. This is intentional, to save code space.
  61293. *
  61294. * Input stack: [ ... re_obj input ]
  61295. * Output stack: [ ... result ]
  61296. */
  61297. DUK_LOCAL void duk__regexp_match_helper(duk_hthread *thr, duk_small_int_t force_global) {
  61298. duk_context *ctx = (duk_context *) thr;
  61299. duk_re_matcher_ctx re_ctx;
  61300. duk_hobject *h_regexp;
  61301. duk_hstring *h_bytecode;
  61302. duk_hstring *h_input;
  61303. const duk_uint8_t *pc;
  61304. const duk_uint8_t *sp;
  61305. duk_small_int_t match = 0;
  61306. duk_small_int_t global;
  61307. duk_uint_fast32_t i;
  61308. double d;
  61309. duk_uint32_t char_offset;
  61310. DUK_ASSERT(thr != NULL);
  61311. DUK_ASSERT(ctx != NULL);
  61312. DUK_DD(DUK_DDPRINT("regexp match: regexp=%!T, input=%!T",
  61313. (duk_tval *) duk_get_tval(ctx, -2),
  61314. (duk_tval *) duk_get_tval(ctx, -1)));
  61315. /*
  61316. * Regexp instance check, bytecode check, input coercion.
  61317. *
  61318. * See E5 Section 15.10.6.
  61319. */
  61320. /* TypeError if wrong; class check, see E5 Section 15.10.6 */
  61321. h_regexp = duk_require_hobject_with_class(ctx, -2, DUK_HOBJECT_CLASS_REGEXP);
  61322. DUK_ASSERT(h_regexp != NULL);
  61323. DUK_ASSERT(DUK_HOBJECT_GET_CLASS_NUMBER(h_regexp) == DUK_HOBJECT_CLASS_REGEXP);
  61324. DUK_UNREF(h_regexp);
  61325. duk_to_string(ctx, -1);
  61326. h_input = duk_get_hstring(ctx, -1);
  61327. DUK_ASSERT(h_input != NULL);
  61328. duk_get_prop_stridx(ctx, -2, DUK_STRIDX_INT_BYTECODE); /* [ ... re_obj input ] -> [ ... re_obj input bc ] */
  61329. h_bytecode = duk_require_hstring(ctx, -1); /* no regexp instance should exist without a non-configurable bytecode property */
  61330. DUK_ASSERT(h_bytecode != NULL);
  61331. /*
  61332. * Basic context initialization.
  61333. *
  61334. * Some init values are read from the bytecode header
  61335. * whose format is (UTF-8 codepoints):
  61336. *
  61337. * uint flags
  61338. * uint nsaved (even, 2n+2 where n = num captures)
  61339. */
  61340. /* [ ... re_obj input bc ] */
  61341. DUK_MEMZERO(&re_ctx, sizeof(re_ctx));
  61342. re_ctx.thr = thr;
  61343. re_ctx.input = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h_input);
  61344. re_ctx.input_end = re_ctx.input + DUK_HSTRING_GET_BYTELEN(h_input);
  61345. re_ctx.bytecode = (duk_uint8_t *) DUK_HSTRING_GET_DATA(h_bytecode);
  61346. re_ctx.bytecode_end = re_ctx.bytecode + DUK_HSTRING_GET_BYTELEN(h_bytecode);
  61347. re_ctx.saved = NULL;
  61348. re_ctx.recursion_limit = DUK_RE_EXECUTE_RECURSION_LIMIT;
  61349. re_ctx.steps_limit = DUK_RE_EXECUTE_STEPS_LIMIT;
  61350. /* read header */
  61351. pc = re_ctx.bytecode;
  61352. re_ctx.re_flags = duk__bc_get_u32(&re_ctx, &pc);
  61353. re_ctx.nsaved = duk__bc_get_u32(&re_ctx, &pc);
  61354. re_ctx.bytecode = pc;
  61355. DUK_ASSERT(DUK_RE_FLAG_GLOBAL < 0x10000UL); /* must fit into duk_small_int_t */
  61356. global = (duk_small_int_t) (force_global | (re_ctx.re_flags & DUK_RE_FLAG_GLOBAL));
  61357. DUK_ASSERT(re_ctx.nsaved >= 2);
  61358. DUK_ASSERT((re_ctx.nsaved % 2) == 0);
  61359. duk_push_fixed_buffer(ctx, sizeof(duk_uint8_t *) * re_ctx.nsaved);
  61360. re_ctx.saved = (const duk_uint8_t **) duk_get_buffer(ctx, -1, NULL);
  61361. DUK_ASSERT(re_ctx.saved != NULL);
  61362. /* [ ... re_obj input bc saved_buf ] */
  61363. /* buffer is automatically zeroed */
  61364. #ifdef DUK_USE_EXPLICIT_NULL_INIT
  61365. for (i = 0; i < re_ctx.nsaved; i++) {
  61366. re_ctx.saved[i] = (duk_uint8_t *) NULL;
  61367. }
  61368. #endif
  61369. DUK_DDD(DUK_DDDPRINT("regexp ctx initialized, flags=0x%08lx, nsaved=%ld, recursion_limit=%ld, steps_limit=%ld",
  61370. (unsigned long) re_ctx.re_flags, (long) re_ctx.nsaved, (long) re_ctx.recursion_limit,
  61371. (long) re_ctx.steps_limit));
  61372. /*
  61373. * Get starting character offset for match, and initialize 'sp' based on it.
  61374. *
  61375. * Note: lastIndex is non-configurable so it must be present (we check the
  61376. * internal class of the object above, so we know it is). User code can set
  61377. * its value to an arbitrary (garbage) value though; E5 requires that lastIndex
  61378. * be coerced to a number before using. The code below works even if the
  61379. * property is missing: the value will then be coerced to zero.
  61380. *
  61381. * Note: lastIndex may be outside Uint32 range even after ToInteger() coercion.
  61382. * For instance, ToInteger(+Infinity) = +Infinity. We track the match offset
  61383. * as an integer, but pre-check it to be inside the 32-bit range before the loop.
  61384. * If not, the check in E5 Section 15.10.6.2, step 9.a applies.
  61385. */
  61386. /* XXX: lastIndex handling produces a lot of asm */
  61387. /* [ ... re_obj input bc saved_buf ] */
  61388. duk_get_prop_stridx(ctx, -4, DUK_STRIDX_LAST_INDEX); /* -> [ ... re_obj input bc saved_buf lastIndex ] */
  61389. (void) duk_to_int(ctx, -1); /* ToInteger(lastIndex) */
  61390. d = duk_get_number(ctx, -1); /* integer, but may be +/- Infinite, +/- zero (not NaN, though) */
  61391. duk_pop(ctx);
  61392. if (global) {
  61393. if (d < 0.0 || d > (double) DUK_HSTRING_GET_CHARLEN(h_input)) {
  61394. /* match fail */
  61395. char_offset = 0; /* not really necessary */
  61396. DUK_ASSERT(match == 0);
  61397. goto match_over;
  61398. }
  61399. char_offset = (duk_uint32_t) d;
  61400. } else {
  61401. /* lastIndex must be ignored for non-global regexps, but get the
  61402. * value for (theoretical) side effects. No side effects can
  61403. * really occur, because lastIndex is a normal property and is
  61404. * always non-configurable for RegExp instances.
  61405. */
  61406. char_offset = (duk_uint32_t) 0;
  61407. }
  61408. sp = re_ctx.input + duk_heap_strcache_offset_char2byte(thr, h_input, char_offset);
  61409. /*
  61410. * Match loop.
  61411. *
  61412. * Try matching at different offsets until match found or input exhausted.
  61413. */
  61414. /* [ ... re_obj input bc saved_buf ] */
  61415. DUK_ASSERT(match == 0);
  61416. for (;;) {
  61417. /* char offset in [0, h_input->clen] (both ends inclusive), checked before entry */
  61418. DUK_ASSERT_DISABLE(char_offset >= 0);
  61419. DUK_ASSERT(char_offset <= DUK_HSTRING_GET_CHARLEN(h_input));
  61420. /* Note: ctx.steps is intentionally not reset, it applies to the entire unanchored match */
  61421. DUK_ASSERT(re_ctx.recursion_depth == 0);
  61422. DUK_DDD(DUK_DDDPRINT("attempt match at char offset %ld; %p [%p,%p]",
  61423. (long) char_offset, (void *) sp, (void *) re_ctx.input,
  61424. (void *) re_ctx.input_end));
  61425. /*
  61426. * Note:
  61427. *
  61428. * - duk__match_regexp() is required not to longjmp() in ordinary "non-match"
  61429. * conditions; a longjmp() will terminate the entire matching process.
  61430. *
  61431. * - Clearing saved[] is not necessary because backtracking does it
  61432. *
  61433. * - Backtracking also rewinds ctx.recursion back to zero, unless an
  61434. * internal/limit error occurs (which causes a longjmp())
  61435. *
  61436. * - If we supported anchored matches, we would break out here
  61437. * unconditionally; however, Ecmascript regexps don't have anchored
  61438. * matches. It might make sense to implement a fast bail-out if
  61439. * the regexp begins with '^' and sp is not 0: currently we'll just
  61440. * run through the entire input string, trivially failing the match
  61441. * at every non-zero offset.
  61442. */
  61443. if (duk__match_regexp(&re_ctx, re_ctx.bytecode, sp) != NULL) {
  61444. DUK_DDD(DUK_DDDPRINT("match at offset %ld", (long) char_offset));
  61445. match = 1;
  61446. break;
  61447. }
  61448. /* advance by one character (code point) and one char_offset */
  61449. char_offset++;
  61450. if (char_offset > DUK_HSTRING_GET_CHARLEN(h_input)) {
  61451. /*
  61452. * Note:
  61453. *
  61454. * - Intentionally attempt (empty) match at char_offset == k_input->clen
  61455. *
  61456. * - Negative char_offsets have been eliminated and char_offset is duk_uint32_t
  61457. * -> no need or use for a negative check
  61458. */
  61459. DUK_DDD(DUK_DDDPRINT("no match after trying all sp offsets"));
  61460. break;
  61461. }
  61462. /* avoid calling at end of input, will DUK_ERROR (above check suffices to avoid this) */
  61463. (void) duk__utf8_advance(thr, &sp, re_ctx.input, re_ctx.input_end, (duk_uint_fast32_t) 1);
  61464. }
  61465. match_over:
  61466. /*
  61467. * Matching complete, create result array or return a 'null'. Update lastIndex
  61468. * if necessary. See E5 Section 15.10.6.2.
  61469. *
  61470. * Because lastIndex is a character (not byte) offset, we need the character
  61471. * length of the match which we conveniently get as a side effect of interning
  61472. * the matching substring (0th index of result array).
  61473. *
  61474. * saved[0] start pointer (~ byte offset) of current match
  61475. * saved[1] end pointer (~ byte offset) of current match (exclusive)
  61476. * char_offset start character offset of current match (-> .index of result)
  61477. * char_end_offset end character offset (computed below)
  61478. */
  61479. /* [ ... re_obj input bc saved_buf ] */
  61480. if (match) {
  61481. #ifdef DUK_USE_ASSERTIONS
  61482. duk_hobject *h_res;
  61483. #endif
  61484. duk_uint32_t char_end_offset = 0;
  61485. DUK_DDD(DUK_DDDPRINT("regexp matches at char_offset %ld", (long) char_offset));
  61486. DUK_ASSERT(re_ctx.nsaved >= 2); /* must have start and end */
  61487. DUK_ASSERT((re_ctx.nsaved % 2) == 0); /* and even number */
  61488. /* XXX: Array size is known before and (2 * re_ctx.nsaved) but not taken
  61489. * advantage of now. The array is not compacted either, as regexp match
  61490. * objects are usually short lived.
  61491. */
  61492. duk_push_array(ctx);
  61493. #ifdef DUK_USE_ASSERTIONS
  61494. h_res = duk_require_hobject(ctx, -1);
  61495. DUK_ASSERT(DUK_HOBJECT_HAS_EXTENSIBLE(h_res));
  61496. DUK_ASSERT(DUK_HOBJECT_HAS_EXOTIC_ARRAY(h_res));
  61497. DUK_ASSERT(DUK_HOBJECT_GET_CLASS_NUMBER(h_res) == DUK_HOBJECT_CLASS_ARRAY);
  61498. #endif
  61499. /* [ ... re_obj input bc saved_buf res_obj ] */
  61500. duk_push_u32(ctx, char_offset);
  61501. duk_xdef_prop_stridx_wec(ctx, -2, DUK_STRIDX_INDEX);
  61502. duk_dup(ctx, -4);
  61503. duk_xdef_prop_stridx_wec(ctx, -2, DUK_STRIDX_INPUT);
  61504. for (i = 0; i < re_ctx.nsaved; i += 2) {
  61505. /* Captures which are undefined have NULL pointers and are returned
  61506. * as 'undefined'. The same is done when saved[] pointers are insane
  61507. * (this should, of course, never happen in practice).
  61508. */
  61509. if (re_ctx.saved[i] && re_ctx.saved[i+1] && re_ctx.saved[i+1] >= re_ctx.saved[i]) {
  61510. duk_hstring *h_saved;
  61511. duk_push_lstring(ctx,
  61512. (char *) re_ctx.saved[i],
  61513. (duk_size_t) (re_ctx.saved[i+1] - re_ctx.saved[i]));
  61514. h_saved = duk_get_hstring(ctx, -1);
  61515. DUK_ASSERT(h_saved != NULL);
  61516. if (i == 0) {
  61517. /* Assumes that saved[0] and saved[1] are always
  61518. * set by regexp bytecode (if not, char_end_offset
  61519. * will be zero). Also assumes clen reflects the
  61520. * correct char length.
  61521. */
  61522. char_end_offset = char_offset + DUK_HSTRING_GET_CHARLEN(h_saved);
  61523. }
  61524. } else {
  61525. duk_push_undefined(ctx);
  61526. }
  61527. /* [ ... re_obj input bc saved_buf res_obj val ] */
  61528. duk_put_prop_index(ctx, -2, i / 2);
  61529. }
  61530. /* [ ... re_obj input bc saved_buf res_obj ] */
  61531. /* NB: 'length' property is automatically updated by the array setup loop */
  61532. if (global) {
  61533. /* global regexp: lastIndex updated on match */
  61534. duk_push_u32(ctx, char_end_offset);
  61535. duk_put_prop_stridx(ctx, -6, DUK_STRIDX_LAST_INDEX);
  61536. } else {
  61537. /* non-global regexp: lastIndex never updated on match */
  61538. ;
  61539. }
  61540. } else {
  61541. /*
  61542. * No match, E5 Section 15.10.6.2, step 9.a.i - 9.a.ii apply, regardless
  61543. * of 'global' flag of the RegExp. In particular, if lastIndex is invalid
  61544. * initially, it is reset to zero.
  61545. */
  61546. DUK_DDD(DUK_DDDPRINT("regexp does not match"));
  61547. duk_push_null(ctx);
  61548. /* [ ... re_obj input bc saved_buf res_obj ] */
  61549. duk_push_int(ctx, 0);
  61550. duk_put_prop_stridx(ctx, -6, DUK_STRIDX_LAST_INDEX);
  61551. }
  61552. /* [ ... re_obj input bc saved_buf res_obj ] */
  61553. duk_insert(ctx, -5);
  61554. /* [ ... res_obj re_obj input bc saved_buf ] */
  61555. duk_pop_n(ctx, 4);
  61556. /* [ ... res_obj ] */
  61557. /* XXX: these last tricks are unnecessary if the function is made
  61558. * a genuine native function.
  61559. */
  61560. }
  61561. DUK_INTERNAL void duk_regexp_match(duk_hthread *thr) {
  61562. duk__regexp_match_helper(thr, 0 /*force_global*/);
  61563. }
  61564. /* This variant is needed by String.prototype.split(); it needs to perform
  61565. * global-style matching on a cloned RegExp which is potentially non-global.
  61566. */
  61567. DUK_INTERNAL void duk_regexp_match_force_global(duk_hthread *thr) {
  61568. duk__regexp_match_helper(thr, 1 /*force_global*/);
  61569. }
  61570. #else /* DUK_USE_REGEXP_SUPPORT */
  61571. /* regexp support disabled */
  61572. #endif /* DUK_USE_REGEXP_SUPPORT */
  61573. #line 1 "duk_replacements.c"
  61574. /*
  61575. * Replacements for missing platform functions.
  61576. *
  61577. * Unlike the originals, fpclassify() and signbit() replacements don't
  61578. * work on any floating point types, only doubles. The C typing here
  61579. * mimics the standard prototypes.
  61580. */
  61581. /* include removed: duk_internal.h */
  61582. #ifdef DUK_USE_COMPUTED_NAN
  61583. DUK_INTERNAL double duk_computed_nan;
  61584. #endif
  61585. #ifdef DUK_USE_COMPUTED_INFINITY
  61586. DUK_INTERNAL double duk_computed_infinity;
  61587. #endif
  61588. #ifdef DUK_USE_REPL_FPCLASSIFY
  61589. DUK_INTERNAL int duk_repl_fpclassify(double x) {
  61590. duk_double_union u;
  61591. duk_uint_fast16_t expt;
  61592. duk_small_int_t mzero;
  61593. u.d = x;
  61594. expt = (duk_uint_fast16_t) (u.us[DUK_DBL_IDX_US0] & 0x7ff0UL);
  61595. if (expt > 0x0000UL && expt < 0x7ff0UL) {
  61596. /* expt values [0x001,0x7fe] = normal */
  61597. return DUK_FP_NORMAL;
  61598. }
  61599. mzero = (u.ui[DUK_DBL_IDX_UI1] == 0 && (u.ui[DUK_DBL_IDX_UI0] & 0x000fffffUL) == 0);
  61600. if (expt == 0x0000UL) {
  61601. /* expt 0x000 is zero/subnormal */
  61602. if (mzero) {
  61603. return DUK_FP_ZERO;
  61604. } else {
  61605. return DUK_FP_SUBNORMAL;
  61606. }
  61607. } else {
  61608. /* expt 0xfff is infinite/nan */
  61609. if (mzero) {
  61610. return DUK_FP_INFINITE;
  61611. } else {
  61612. return DUK_FP_NAN;
  61613. }
  61614. }
  61615. }
  61616. #endif
  61617. #ifdef DUK_USE_REPL_SIGNBIT
  61618. DUK_INTERNAL int duk_repl_signbit(double x) {
  61619. duk_double_union u;
  61620. u.d = x;
  61621. return (int) (u.uc[DUK_DBL_IDX_UC0] & 0x80UL);
  61622. }
  61623. #endif
  61624. #ifdef DUK_USE_REPL_ISFINITE
  61625. DUK_INTERNAL int duk_repl_isfinite(double x) {
  61626. int c = DUK_FPCLASSIFY(x);
  61627. if (c == DUK_FP_NAN || c == DUK_FP_INFINITE) {
  61628. return 0;
  61629. } else {
  61630. return 1;
  61631. }
  61632. }
  61633. #endif
  61634. #ifdef DUK_USE_REPL_ISNAN
  61635. DUK_INTERNAL int duk_repl_isnan(double x) {
  61636. int c = DUK_FPCLASSIFY(x);
  61637. return (c == DUK_FP_NAN);
  61638. }
  61639. #endif
  61640. #ifdef DUK_USE_REPL_ISINF
  61641. DUK_INTERNAL int duk_repl_isinf(double x) {
  61642. int c = DUK_FPCLASSIFY(x);
  61643. return (c == DUK_FP_INFINITE);
  61644. }
  61645. #endif
  61646. #line 1 "duk_selftest.c"
  61647. /*
  61648. * Self tests to ensure execution environment is sane. Intended to catch
  61649. * compiler/platform problems which cannot be detected at compile time.
  61650. */
  61651. /* include removed: duk_internal.h */
  61652. #if defined(DUK_USE_SELF_TESTS)
  61653. /*
  61654. * Unions and structs for self tests
  61655. */
  61656. typedef union {
  61657. double d;
  61658. duk_uint8_t c[8];
  61659. } duk__test_double_union;
  61660. #define DUK__DBLUNION_CMP_TRUE(a,b) do { \
  61661. if (DUK_MEMCMP((void *) (a), (void *) (b), sizeof(duk__test_double_union)) != 0) { \
  61662. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: double union compares false (expected true)"); \
  61663. } \
  61664. } while (0)
  61665. #define DUK__DBLUNION_CMP_FALSE(a,b) do { \
  61666. if (DUK_MEMCMP((void *) (a), (void *) (b), sizeof(duk__test_double_union)) == 0) { \
  61667. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: double union compares true (expected false)"); \
  61668. } \
  61669. } while (0)
  61670. typedef union {
  61671. duk_uint32_t i;
  61672. duk_uint8_t c[8];
  61673. } duk__test_u32_union;
  61674. /*
  61675. * Various sanity checks for typing
  61676. */
  61677. DUK_LOCAL void duk__selftest_types(void) {
  61678. if (!(sizeof(duk_int8_t) == 1 &&
  61679. sizeof(duk_uint8_t) == 1 &&
  61680. sizeof(duk_int16_t) == 2 &&
  61681. sizeof(duk_uint16_t) == 2 &&
  61682. sizeof(duk_int32_t) == 4 &&
  61683. sizeof(duk_uint32_t) == 4)) {
  61684. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: duk_(u)int{8,16,32}_t size");
  61685. }
  61686. #if defined(DUK_USE_64BIT_OPS)
  61687. if (!(sizeof(duk_int64_t) == 8 &&
  61688. sizeof(duk_uint64_t) == 8)) {
  61689. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: duk_(u)int64_t size");
  61690. }
  61691. #endif
  61692. if (!(sizeof(duk_size_t) >= sizeof(duk_uint_t))) {
  61693. /* Some internal code now assumes that all duk_uint_t values
  61694. * can be expressed with a duk_size_t.
  61695. */
  61696. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: duk_size_t is smaller than duk_uint_t");
  61697. }
  61698. if (!(sizeof(duk_int_t) >= 4)) {
  61699. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: duk_int_t is not 32 bits");
  61700. }
  61701. }
  61702. /*
  61703. * Packed tval sanity
  61704. */
  61705. DUK_LOCAL void duk__selftest_packed_tval(void) {
  61706. #if defined(DUK_USE_PACKED_TVAL)
  61707. if (sizeof(void *) > 4) {
  61708. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: packed duk_tval in use but sizeof(void *) > 4");
  61709. }
  61710. #endif
  61711. }
  61712. /*
  61713. * Two's complement arithmetic.
  61714. */
  61715. DUK_LOCAL void duk__selftest_twos_complement(void) {
  61716. volatile int test;
  61717. test = -1;
  61718. if (((duk_uint8_t *) &test)[0] != (duk_uint8_t) 0xff) {
  61719. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: two's complement arithmetic");
  61720. }
  61721. }
  61722. /*
  61723. * Byte order. Important to self check, because on some exotic platforms
  61724. * there is no actual detection but rather assumption based on platform
  61725. * defines.
  61726. */
  61727. DUK_LOCAL void duk__selftest_byte_order(void) {
  61728. duk__test_u32_union u1;
  61729. duk__test_double_union u2;
  61730. /*
  61731. * >>> struct.pack('>d', 102030405060).encode('hex')
  61732. * '4237c17c6dc40000'
  61733. */
  61734. #if defined(DUK_USE_INTEGER_LE)
  61735. u1.c[0] = 0xef; u1.c[1] = 0xbe; u1.c[2] = 0xad; u1.c[3] = 0xde;
  61736. #elif defined(DUK_USE_INTEGER_ME)
  61737. #error integer mixed endian not supported now
  61738. #elif defined(DUK_USE_INTEGER_BE)
  61739. u1.c[0] = 0xde; u1.c[1] = 0xad; u1.c[2] = 0xbe; u1.c[3] = 0xef;
  61740. #else
  61741. #error unknown integer endianness
  61742. #endif
  61743. #if defined(DUK_USE_DOUBLE_LE)
  61744. u2.c[0] = 0x00; u2.c[1] = 0x00; u2.c[2] = 0xc4; u2.c[3] = 0x6d;
  61745. u2.c[4] = 0x7c; u2.c[5] = 0xc1; u2.c[6] = 0x37; u2.c[7] = 0x42;
  61746. #elif defined(DUK_USE_DOUBLE_ME)
  61747. u2.c[0] = 0x7c; u2.c[1] = 0xc1; u2.c[2] = 0x37; u2.c[3] = 0x42;
  61748. u2.c[4] = 0x00; u2.c[5] = 0x00; u2.c[6] = 0xc4; u2.c[7] = 0x6d;
  61749. #elif defined(DUK_USE_DOUBLE_BE)
  61750. u2.c[0] = 0x42; u2.c[1] = 0x37; u2.c[2] = 0xc1; u2.c[3] = 0x7c;
  61751. u2.c[4] = 0x6d; u2.c[5] = 0xc4; u2.c[6] = 0x00; u2.c[7] = 0x00;
  61752. #else
  61753. #error unknown double endianness
  61754. #endif
  61755. if (u1.i != (duk_uint32_t) 0xdeadbeefUL) {
  61756. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: duk_uint32_t byte order");
  61757. }
  61758. if (u2.d != (double) 102030405060.0) {
  61759. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: double byte order");
  61760. }
  61761. }
  61762. /*
  61763. * DUK_BSWAP macros
  61764. */
  61765. DUK_LOCAL void duk__selftest_bswap_macros(void) {
  61766. duk_uint32_t x32;
  61767. duk_uint16_t x16;
  61768. duk_double_union du;
  61769. duk_double_t du_diff;
  61770. x16 = 0xbeefUL;
  61771. x16 = DUK_BSWAP16(x16);
  61772. if (x16 != (duk_uint16_t) 0xefbeUL) {
  61773. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: DUK_BSWAP16");
  61774. }
  61775. x32 = 0xdeadbeefUL;
  61776. x32 = DUK_BSWAP32(x32);
  61777. if (x32 != (duk_uint32_t) 0xefbeaddeUL) {
  61778. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: DUK_BSWAP32");
  61779. }
  61780. /* >>> struct.unpack('>d', '4000112233445566'.decode('hex'))
  61781. * (2.008366013071895,)
  61782. */
  61783. du.uc[0] = 0x40; du.uc[1] = 0x00; du.uc[2] = 0x11; du.uc[3] = 0x22;
  61784. du.uc[4] = 0x33; du.uc[5] = 0x44; du.uc[6] = 0x55; du.uc[7] = 0x66;
  61785. DUK_DBLUNION_BSWAP(&du);
  61786. du_diff = du.d - 2.008366013071895;
  61787. #if 0
  61788. DUK_FPRINTF(DUK_STDERR, "du_diff: %lg\n", (double) du_diff);
  61789. #endif
  61790. if (du_diff > 1e-15) {
  61791. /* Allow very small lenience because some compilers won't parse
  61792. * exact IEEE double constants (happened in matrix testing with
  61793. * Linux gcc-4.8 -m32 at least).
  61794. */
  61795. #if 0
  61796. DUK_FPRINTF(DUK_STDERR, "Result of DUK_DBLUNION_BSWAP: %02x %02x %02x %02x %02x %02x %02x %02x\n",
  61797. (unsigned int) du.uc[0], (unsigned int) du.uc[1],
  61798. (unsigned int) du.uc[2], (unsigned int) du.uc[3],
  61799. (unsigned int) du.uc[4], (unsigned int) du.uc[5],
  61800. (unsigned int) du.uc[6], (unsigned int) du.uc[7]);
  61801. #endif
  61802. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: DUK_DBLUNION_BSWAP");
  61803. }
  61804. }
  61805. /*
  61806. * Basic double / byte union memory layout.
  61807. */
  61808. DUK_LOCAL void duk__selftest_double_union_size(void) {
  61809. if (sizeof(duk__test_double_union) != 8) {
  61810. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: invalid union size");
  61811. }
  61812. }
  61813. /*
  61814. * Union aliasing, see misc/clang_aliasing.c.
  61815. */
  61816. DUK_LOCAL void duk__selftest_double_aliasing(void) {
  61817. duk__test_double_union a, b;
  61818. /* This testcase fails when Emscripten-generated code runs on Firefox.
  61819. * It's not an issue because the failure should only affect packed
  61820. * duk_tval representation, which is not used with Emscripten.
  61821. */
  61822. #if defined(DUK_USE_NO_DOUBLE_ALIASING_SELFTEST)
  61823. #if defined(DUK_USE_PACKED_TVAL)
  61824. #error inconsistent defines: skipping double aliasing selftest when using packed duk_tval
  61825. #endif
  61826. return;
  61827. #endif
  61828. /* Test signaling NaN and alias assignment in all
  61829. * endianness combinations.
  61830. */
  61831. /* little endian */
  61832. a.c[0] = 0x11; a.c[1] = 0x22; a.c[2] = 0x33; a.c[3] = 0x44;
  61833. a.c[4] = 0x00; a.c[5] = 0x00; a.c[6] = 0xf1; a.c[7] = 0xff;
  61834. b = a;
  61835. DUK__DBLUNION_CMP_TRUE(&a, &b);
  61836. /* big endian */
  61837. a.c[0] = 0xff; a.c[1] = 0xf1; a.c[2] = 0x00; a.c[3] = 0x00;
  61838. a.c[4] = 0x44; a.c[5] = 0x33; a.c[6] = 0x22; a.c[7] = 0x11;
  61839. b = a;
  61840. DUK__DBLUNION_CMP_TRUE(&a, &b);
  61841. /* mixed endian */
  61842. a.c[0] = 0x00; a.c[1] = 0x00; a.c[2] = 0xf1; a.c[3] = 0xff;
  61843. a.c[4] = 0x11; a.c[5] = 0x22; a.c[6] = 0x33; a.c[7] = 0x44;
  61844. b = a;
  61845. DUK__DBLUNION_CMP_TRUE(&a, &b);
  61846. }
  61847. /*
  61848. * Zero sign, see misc/tcc_zerosign2.c.
  61849. */
  61850. DUK_LOCAL void duk__selftest_double_zero_sign(void) {
  61851. volatile duk__test_double_union a, b;
  61852. a.d = 0.0;
  61853. b.d = -a.d;
  61854. DUK__DBLUNION_CMP_FALSE(&a, &b);
  61855. }
  61856. /*
  61857. * Struct size/alignment if platform requires it
  61858. *
  61859. * There are some compiler specific struct padding pragmas etc in use, this
  61860. * selftest ensures they're correctly detected and used.
  61861. */
  61862. DUK_LOCAL void duk__selftest_struct_align(void) {
  61863. #if defined(DUK_USE_ALIGN_4)
  61864. if ((sizeof(duk_hbuffer_fixed) % 4) != 0) {
  61865. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: sizeof(duk_hbuffer_fixed) not aligned to 4");
  61866. }
  61867. #elif defined(DUK_USE_ALIGN_8)
  61868. if ((sizeof(duk_hbuffer_fixed) % 8) != 0) {
  61869. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: sizeof(duk_hbuffer_fixed) not aligned to 8");
  61870. }
  61871. #else
  61872. /* no check */
  61873. #endif
  61874. }
  61875. /*
  61876. * 64-bit arithmetic
  61877. *
  61878. * There are some platforms/compilers where 64-bit types are available
  61879. * but don't work correctly. Test for known cases.
  61880. */
  61881. DUK_LOCAL void duk__selftest_64bit_arithmetic(void) {
  61882. #if defined(DUK_USE_64BIT_OPS)
  61883. volatile duk_int64_t i;
  61884. volatile duk_double_t d;
  61885. /* Catch a double-to-int64 cast issue encountered in practice. */
  61886. d = 2147483648.0;
  61887. i = (duk_int64_t) d;
  61888. if (i != 0x80000000LL) {
  61889. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: casting 2147483648.0 to duk_int64_t failed");
  61890. }
  61891. #else
  61892. /* nop */
  61893. #endif
  61894. }
  61895. /*
  61896. * Casting
  61897. */
  61898. DUK_LOCAL void duk__selftest_cast_double_to_uint(void) {
  61899. /*
  61900. * https://github.com/svaarala/duktape/issues/127#issuecomment-77863473
  61901. */
  61902. duk_double_t d1, d2;
  61903. duk_small_uint_t u;
  61904. duk_double_t d1v, d2v;
  61905. duk_small_uint_t uv;
  61906. d1 = 1.0;
  61907. u = (duk_small_uint_t) d1;
  61908. d2 = (duk_double_t) u;
  61909. if (!(d1 == 1.0 && u == 1 && d2 == 1.0 && d1 == d2)) {
  61910. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: double to uint cast failed");
  61911. }
  61912. /* Same test with volatiles */
  61913. d1v = 1.0;
  61914. uv = (duk_small_uint_t) d1v;
  61915. d2v = (duk_double_t) uv;
  61916. if (!(d1v == 1.0 && uv == 1 && d2v == 1.0 && d1v == d2v)) {
  61917. DUK_PANIC(DUK_ERR_INTERNAL_ERROR, "self test failed: double to uint cast failed");
  61918. }
  61919. }
  61920. /*
  61921. * Self test main
  61922. */
  61923. DUK_INTERNAL void duk_selftest_run_tests(void) {
  61924. duk__selftest_types();
  61925. duk__selftest_packed_tval();
  61926. duk__selftest_twos_complement();
  61927. duk__selftest_byte_order();
  61928. duk__selftest_bswap_macros();
  61929. duk__selftest_double_union_size();
  61930. duk__selftest_double_aliasing();
  61931. duk__selftest_double_zero_sign();
  61932. duk__selftest_struct_align();
  61933. duk__selftest_64bit_arithmetic();
  61934. duk__selftest_cast_double_to_uint();
  61935. }
  61936. #undef DUK__DBLUNION_CMP_TRUE
  61937. #undef DUK__DBLUNION_CMP_FALSE
  61938. #endif /* DUK_USE_SELF_TESTS */
  61939. /* include removed: duk_internal.h */
  61940. #line 2 "duk_tval.c"
  61941. #if defined(DUK_USE_FASTINT)
  61942. /*
  61943. * Manually optimized double-to-fastint downgrade check.
  61944. *
  61945. * This check has a large impact on performance, especially for fastint
  61946. * slow paths, so must be changed carefully. The code should probably be
  61947. * optimized for the case where the result does not fit into a fastint,
  61948. * to minimize the penalty for "slow path code" dealing with fractions etc.
  61949. *
  61950. * At least on one tested soft float ARM platform double-to-int64 coercion
  61951. * is very slow (and sometimes produces incorrect results, see self tests).
  61952. * This algorithm combines a fastint compatibility check and extracting the
  61953. * integer value from an IEEE double for setting the tagged fastint. For
  61954. * other platforms a more naive approach might be better.
  61955. *
  61956. * See doc/fastint.rst for details.
  61957. */
  61958. DUK_INTERNAL DUK_ALWAYS_INLINE void duk_tval_set_number_chkfast(duk_tval *tv, duk_double_t x) {
  61959. duk_double_union du;
  61960. duk_int64_t i;
  61961. duk_small_int_t expt;
  61962. duk_small_int_t shift;
  61963. /* XXX: optimize for packed duk_tval directly? */
  61964. du.d = x;
  61965. i = (duk_int64_t) DUK_DBLUNION_GET_INT64(&du);
  61966. expt = (duk_small_int_t) ((i >> 52) & 0x07ff);
  61967. shift = expt - 1023;
  61968. if (shift >= 0 && shift <= 46) { /* exponents 1023 to 1069 */
  61969. duk_int64_t t;
  61970. if (((0x000fffffffffffffLL >> shift) & i) == 0) {
  61971. t = i | 0x0010000000000000LL; /* implicit leading one */
  61972. t = t & 0x001fffffffffffffLL;
  61973. t = t >> (52 - shift);
  61974. if (i < 0) {
  61975. t = -t;
  61976. }
  61977. DUK_TVAL_SET_FASTINT(tv, t);
  61978. return;
  61979. }
  61980. } else if (shift == -1023) { /* exponent 0 */
  61981. if (i >= 0 && (i & 0x000fffffffffffffLL) == 0) {
  61982. /* Note: reject negative zero. */
  61983. DUK_TVAL_SET_FASTINT(tv, (duk_int64_t) 0);
  61984. return;
  61985. }
  61986. } else if (shift == 47) { /* exponent 1070 */
  61987. if (i < 0 && (i & 0x000fffffffffffffLL) == 0) {
  61988. DUK_TVAL_SET_FASTINT(tv, (duk_int64_t) DUK_FASTINT_MIN);
  61989. return;
  61990. }
  61991. }
  61992. DUK_TVAL_SET_DOUBLE(tv, x);
  61993. return;
  61994. }
  61995. /*
  61996. * Manually optimized number-to-double conversion
  61997. */
  61998. #if defined(DUK_USE_FASTINT) && defined(DUK_USE_PACKED_TVAL)
  61999. DUK_INTERNAL DUK_ALWAYS_INLINE duk_double_t duk_tval_get_number_packed(duk_tval *tv) {
  62000. duk_double_union du;
  62001. duk_uint64_t t;
  62002. t = (duk_uint64_t) DUK_DBLUNION_GET_UINT64(tv);
  62003. if ((t >> 48) != DUK_TAG_FASTINT) {
  62004. return tv->d;
  62005. } else if (t & 0x0000800000000000ULL) {
  62006. t = (duk_uint64_t) (-((duk_int64_t) t)); /* avoid unary minus on unsigned */
  62007. t = t & 0x0000ffffffffffffULL; /* negative */
  62008. t |= 0xc330000000000000ULL;
  62009. DUK_DBLUNION_SET_UINT64(&du, t);
  62010. return du.d + 4503599627370496.0; /* 1 << 52 */
  62011. } else if (t != 0) {
  62012. t &= 0x0000ffffffffffffULL; /* positive */
  62013. t |= 0x4330000000000000ULL;
  62014. DUK_DBLUNION_SET_UINT64(&du, t);
  62015. return du.d - 4503599627370496.0; /* 1 << 52 */
  62016. } else {
  62017. return 0.0; /* zero */
  62018. }
  62019. }
  62020. #endif /* DUK_USE_FASTINT && DUK_USE_PACKED_TVAL */
  62021. #if 0 /* unused */
  62022. #if defined(DUK_USE_FASTINT) && !defined(DUK_USE_PACKED_TVAL)
  62023. DUK_INTERNAL DUK_ALWAYS_INLINE duk_double_t duk_tval_get_number_unpacked(duk_tval *tv) {
  62024. duk_double_union du;
  62025. duk_uint64_t t;
  62026. DUK_ASSERT(tv->t == DUK__TAG_NUMBER || tv->t == DUK_TAG_FASTINT);
  62027. if (tv->t == DUK_TAG_FASTINT) {
  62028. if (tv->v.fi >= 0) {
  62029. t = 0x4330000000000000ULL | (duk_uint64_t) tv->v.fi;
  62030. DUK_DBLUNION_SET_UINT64(&du, t);
  62031. return du.d - 4503599627370496.0; /* 1 << 52 */
  62032. } else {
  62033. t = 0xc330000000000000ULL | (duk_uint64_t) (-tv->v.fi);
  62034. DUK_DBLUNION_SET_UINT64(&du, t);
  62035. return du.d + 4503599627370496.0; /* 1 << 52 */
  62036. }
  62037. } else {
  62038. return tv->v.d;
  62039. }
  62040. }
  62041. #endif /* DUK_USE_FASTINT && DUK_USE_PACKED_TVAL */
  62042. #endif /* 0 */
  62043. #if defined(DUK_USE_FASTINT) && !defined(DUK_USE_PACKED_TVAL)
  62044. DUK_INTERNAL DUK_ALWAYS_INLINE duk_double_t duk_tval_get_number_unpacked_fastint(duk_tval *tv) {
  62045. duk_double_union du;
  62046. duk_uint64_t t;
  62047. DUK_ASSERT(tv->t == DUK_TAG_FASTINT);
  62048. if (tv->v.fi >= 0) {
  62049. t = 0x4330000000000000ULL | (duk_uint64_t) tv->v.fi;
  62050. DUK_DBLUNION_SET_UINT64(&du, t);
  62051. return du.d - 4503599627370496.0; /* 1 << 52 */
  62052. } else {
  62053. t = 0xc330000000000000ULL | (duk_uint64_t) (-tv->v.fi);
  62054. DUK_DBLUNION_SET_UINT64(&du, t);
  62055. return du.d + 4503599627370496.0; /* 1 << 52 */
  62056. }
  62057. }
  62058. #endif /* DUK_USE_FASTINT && DUK_USE_PACKED_TVAL */
  62059. #endif /* DUK_USE_FASTINT */
  62060. #line 1 "duk_unicode_tables.c"
  62061. /*
  62062. * Unicode support tables automatically generated during build.
  62063. */
  62064. /* include removed: duk_internal.h */
  62065. /*
  62066. * Unicode tables containing ranges of Unicode characters in a
  62067. * packed format. These tables are used to match non-ASCII
  62068. * characters of complex productions by resorting to a linear
  62069. * range-by-range comparison. This is very slow, but is expected
  62070. * to be very rare in practical Ecmascript source code, and thus
  62071. * compactness is most important.
  62072. *
  62073. * The tables are matched using uni_range_match() and the format
  62074. * is described in src/extract_chars.py.
  62075. */
  62076. #ifdef DUK_USE_SOURCE_NONBMP
  62077. /* IdentifierStart production with ASCII excluded */
  62078. /* duk_unicode_ids_noa[] */
  62079. /*
  62080. * Automatically generated by extract_chars.py, do not edit!
  62081. */
  62082. const duk_uint8_t duk_unicode_ids_noa[791] = {
  62083. 249,176,176,80,111,7,47,15,47,254,11,197,191,0,72,2,15,115,66,19,57,2,34,2,
  62084. 240,66,244,50,247,185,248,234,241,99,8,241,127,58,240,182,47,31,241,191,21,
  62085. 18,245,50,15,1,24,27,35,15,2,2,240,239,15,244,156,15,10,241,26,21,6,240,
  62086. 101,10,4,15,9,240,159,157,242,100,15,4,8,159,1,98,102,115,19,240,98,98,4,
  62087. 52,15,2,14,18,47,0,31,5,85,19,240,98,98,18,18,31,17,50,15,5,47,2,130,34,
  62088. 240,98,98,18,68,15,4,15,1,31,21,115,19,240,98,98,18,68,15,16,18,47,1,15,3,
  62089. 2,84,34,52,18,2,20,20,36,191,8,15,38,114,34,240,114,146,68,15,12,23,31,21,
  62090. 114,34,240,114,146,68,15,18,2,31,1,31,4,114,34,241,147,15,2,15,3,31,10,86,
  62091. 240,36,240,130,130,3,111,44,242,2,29,111,44,18,3,18,3,7,50,98,34,2,3,18,50,
  62092. 26,3,66,15,7,31,20,15,49,114,241,79,13,79,101,241,191,6,15,2,85,52,4,24,37,
  62093. 205,15,3,241,107,241,178,4,255,224,59,35,54,32,35,63,25,35,63,17,35,54,32,
  62094. 35,62,47,41,35,63,51,241,127,0,240,47,69,223,254,21,227,240,18,240,166,243,
  62095. 180,47,1,194,63,0,240,47,0,240,47,0,194,47,1,242,79,21,5,15,53,244,137,241,
  62096. 146,6,243,107,240,223,37,240,227,76,241,207,7,111,42,240,122,242,95,68,15,
  62097. 79,241,255,3,111,41,240,238,31,2,241,111,12,241,79,27,43,241,79,93,50,63,0,
  62098. 251,15,50,255,224,8,53,63,22,53,55,32,32,32,47,15,63,37,38,32,66,38,67,53,
  62099. 92,98,38,246,96,224,240,44,245,112,80,57,32,68,112,32,32,35,42,51,100,80,
  62100. 240,63,25,255,233,107,241,242,241,242,247,87,63,3,241,107,242,106,15,2,240,
  62101. 122,98,98,98,98,98,98,98,111,66,15,254,12,146,240,184,132,52,95,70,114,47,
  62102. 74,35,111,25,79,78,240,63,11,242,127,0,255,224,244,255,240,0,138,143,60,
  62103. 255,240,4,11,239,38,255,227,127,243,95,30,63,253,79,0,177,240,111,31,240,
  62104. 47,9,159,64,241,152,63,87,51,33,240,9,244,39,34,35,47,7,240,255,36,240,15,
  62105. 34,243,5,64,240,15,12,191,7,240,191,13,143,31,240,224,242,47,25,240,146,39,
  62106. 240,111,7,64,111,32,32,65,52,48,32,240,162,241,85,53,53,166,38,248,63,19,
  62107. 240,255,255,0,26,150,223,7,95,33,255,240,0,255,143,254,2,3,242,227,245,175,
  62108. 24,109,70,2,146,194,66,2,18,18,245,207,19,255,224,93,240,79,48,63,38,241,
  62109. 171,246,100,47,119,241,111,10,127,10,207,73,69,53,53,50,241,91,47,10,47,3,
  62110. 33,46,61,241,79,107,243,127,37,255,223,13,79,33,242,31,15,240,63,11,242,
  62111. 127,14,63,20,87,36,241,207,142,255,226,86,83,2,241,194,20,3,240,127,156,
  62112. 240,107,240,175,184,15,1,50,34,240,191,30,240,223,117,242,107,240,107,240,
  62113. 63,127,243,159,254,42,239,37,243,223,29,255,238,68,255,226,97,248,63,83,
  62114. 255,234,145,255,227,33,255,240,2,44,95,254,18,191,255,0,52,187,31,255,0,18,
  62115. 242,244,82,243,114,19,3,19,50,178,2,98,243,18,51,114,98,240,194,50,66,4,98,
  62116. 255,224,70,63,9,47,9,47,15,47,9,47,15,47,9,47,15,47,9,47,15,47,9,39,255,
  62117. 240,1,114,143,255,0,149,201,241,191,254,242,124,252,239,255,0,46,214,255,
  62118. 225,16,0,
  62119. };
  62120. #else
  62121. /* IdentifierStart production with ASCII and non-BMP excluded */
  62122. /* duk_unicode_ids_noabmp[] */
  62123. /*
  62124. * Automatically generated by extract_chars.py, do not edit!
  62125. */
  62126. const duk_uint8_t duk_unicode_ids_noabmp[611] = {
  62127. 249,176,176,80,111,7,47,15,47,254,11,197,191,0,72,2,15,115,66,19,57,2,34,2,
  62128. 240,66,244,50,247,185,248,234,241,99,8,241,127,58,240,182,47,31,241,191,21,
  62129. 18,245,50,15,1,24,27,35,15,2,2,240,239,15,244,156,15,10,241,26,21,6,240,
  62130. 101,10,4,15,9,240,159,157,242,100,15,4,8,159,1,98,102,115,19,240,98,98,4,
  62131. 52,15,2,14,18,47,0,31,5,85,19,240,98,98,18,18,31,17,50,15,5,47,2,130,34,
  62132. 240,98,98,18,68,15,4,15,1,31,21,115,19,240,98,98,18,68,15,16,18,47,1,15,3,
  62133. 2,84,34,52,18,2,20,20,36,191,8,15,38,114,34,240,114,146,68,15,12,23,31,21,
  62134. 114,34,240,114,146,68,15,18,2,31,1,31,4,114,34,241,147,15,2,15,3,31,10,86,
  62135. 240,36,240,130,130,3,111,44,242,2,29,111,44,18,3,18,3,7,50,98,34,2,3,18,50,
  62136. 26,3,66,15,7,31,20,15,49,114,241,79,13,79,101,241,191,6,15,2,85,52,4,24,37,
  62137. 205,15,3,241,107,241,178,4,255,224,59,35,54,32,35,63,25,35,63,17,35,54,32,
  62138. 35,62,47,41,35,63,51,241,127,0,240,47,69,223,254,21,227,240,18,240,166,243,
  62139. 180,47,1,194,63,0,240,47,0,240,47,0,194,47,1,242,79,21,5,15,53,244,137,241,
  62140. 146,6,243,107,240,223,37,240,227,76,241,207,7,111,42,240,122,242,95,68,15,
  62141. 79,241,255,3,111,41,240,238,31,2,241,111,12,241,79,27,43,241,79,93,50,63,0,
  62142. 251,15,50,255,224,8,53,63,22,53,55,32,32,32,47,15,63,37,38,32,66,38,67,53,
  62143. 92,98,38,246,96,224,240,44,245,112,80,57,32,68,112,32,32,35,42,51,100,80,
  62144. 240,63,25,255,233,107,241,242,241,242,247,87,63,3,241,107,242,106,15,2,240,
  62145. 122,98,98,98,98,98,98,98,111,66,15,254,12,146,240,184,132,52,95,70,114,47,
  62146. 74,35,111,25,79,78,240,63,11,242,127,0,255,224,244,255,240,0,138,143,60,
  62147. 255,240,4,11,239,38,255,227,127,243,95,30,63,253,79,0,177,240,111,31,240,
  62148. 47,9,159,64,241,152,63,87,51,33,240,9,244,39,34,35,47,7,240,255,36,240,15,
  62149. 34,243,5,64,240,15,12,191,7,240,191,13,143,31,240,224,242,47,25,240,146,39,
  62150. 240,111,7,64,111,32,32,65,52,48,32,240,162,241,85,53,53,166,38,248,63,19,
  62151. 240,255,255,0,26,150,223,7,95,33,255,240,0,255,143,254,2,3,242,227,245,175,
  62152. 24,109,70,2,146,194,66,2,18,18,245,207,19,255,224,93,240,79,48,63,38,241,
  62153. 171,246,100,47,119,241,111,10,127,10,207,73,69,53,53,50,0,
  62154. };
  62155. #endif
  62156. #ifdef DUK_USE_SOURCE_NONBMP
  62157. /* IdentifierStart production with Letter and ASCII excluded */
  62158. /* duk_unicode_ids_m_let_noa[] */
  62159. /*
  62160. * Automatically generated by extract_chars.py, do not edit!
  62161. */
  62162. const duk_uint8_t duk_unicode_ids_m_let_noa[42] = {
  62163. 255,240,0,94,18,255,233,99,241,51,63,254,215,32,240,184,240,2,255,240,6,89,
  62164. 249,255,240,4,148,79,37,255,224,192,9,15,120,79,255,0,15,30,245,48,
  62165. };
  62166. #else
  62167. /* IdentifierStart production with Letter, ASCII, and non-BMP excluded */
  62168. /* duk_unicode_ids_m_let_noabmp[] */
  62169. /*
  62170. * Automatically generated by extract_chars.py, do not edit!
  62171. */
  62172. const duk_uint8_t duk_unicode_ids_m_let_noabmp[24] = {
  62173. 255,240,0,94,18,255,233,99,241,51,63,254,215,32,240,184,240,2,255,240,6,89,
  62174. 249,0,
  62175. };
  62176. #endif
  62177. #ifdef DUK_USE_SOURCE_NONBMP
  62178. /* IdentifierPart production with IdentifierStart and ASCII excluded */
  62179. /* duk_unicode_idp_m_ids_noa[] */
  62180. /*
  62181. * Automatically generated by extract_chars.py, do not edit!
  62182. */
  62183. const duk_uint8_t duk_unicode_idp_m_ids_noa[397] = {
  62184. 255,225,243,246,15,254,0,116,255,191,29,32,33,33,32,243,170,242,47,15,112,
  62185. 245,118,53,49,35,57,240,144,241,15,11,244,218,240,25,241,56,241,67,40,34,
  62186. 36,241,210,249,99,242,130,47,2,38,177,57,240,50,242,160,38,49,50,160,177,
  62187. 57,240,50,242,160,36,81,50,64,240,107,64,194,242,160,39,34,34,240,97,57,
  62188. 240,50,242,160,38,49,50,145,177,57,240,64,242,212,66,35,160,240,9,240,50,
  62189. 242,198,34,35,129,193,57,240,65,242,160,38,34,35,129,193,57,240,65,242,198,
  62190. 34,35,160,177,57,240,65,243,128,85,32,39,240,65,242,240,54,215,41,244,144,
  62191. 53,33,197,57,243,1,121,192,32,32,81,242,63,4,33,106,47,20,160,245,111,4,41,
  62192. 211,82,34,54,67,235,46,255,225,179,47,254,42,98,240,242,240,241,241,1,243,
  62193. 79,14,160,57,241,50,57,248,16,246,139,91,185,245,47,1,129,121,242,244,242,
  62194. 185,47,13,58,121,245,132,242,31,1,201,240,56,210,241,9,105,241,237,242,47,
  62195. 4,153,121,246,130,47,5,80,80,251,255,23,240,115,255,225,0,31,35,31,5,15,
  62196. 109,197,4,191,254,175,34,247,240,245,47,16,255,225,30,95,91,31,255,0,100,
  62197. 121,159,55,13,31,100,31,254,0,64,64,80,240,148,244,161,242,79,1,201,127,2,
  62198. 240,9,240,231,240,188,241,227,242,29,240,25,244,29,208,145,57,241,48,242,
  62199. 96,34,49,97,32,255,224,21,114,19,159,255,0,62,24,15,254,29,95,0,240,38,209,
  62200. 240,162,251,41,241,112,255,225,177,15,254,25,105,255,228,75,34,22,63,26,37,
  62201. 15,254,75,66,242,126,241,25,240,34,241,250,255,240,10,249,228,69,151,54,
  62202. 241,3,248,98,255,228,125,242,47,255,12,23,244,254,0,
  62203. };
  62204. #else
  62205. /* IdentifierPart production with IdentifierStart, ASCII, and non-BMP excluded */
  62206. /* duk_unicode_idp_m_ids_noabmp[] */
  62207. /*
  62208. * Automatically generated by extract_chars.py, do not edit!
  62209. */
  62210. const duk_uint8_t duk_unicode_idp_m_ids_noabmp[348] = {
  62211. 255,225,243,246,15,254,0,116,255,191,29,32,33,33,32,243,170,242,47,15,112,
  62212. 245,118,53,49,35,57,240,144,241,15,11,244,218,240,25,241,56,241,67,40,34,
  62213. 36,241,210,249,99,242,130,47,2,38,177,57,240,50,242,160,38,49,50,160,177,
  62214. 57,240,50,242,160,36,81,50,64,240,107,64,194,242,160,39,34,34,240,97,57,
  62215. 240,50,242,160,38,49,50,145,177,57,240,64,242,212,66,35,160,240,9,240,50,
  62216. 242,198,34,35,129,193,57,240,65,242,160,38,34,35,129,193,57,240,65,242,198,
  62217. 34,35,160,177,57,240,65,243,128,85,32,39,240,65,242,240,54,215,41,244,144,
  62218. 53,33,197,57,243,1,121,192,32,32,81,242,63,4,33,106,47,20,160,245,111,4,41,
  62219. 211,82,34,54,67,235,46,255,225,179,47,254,42,98,240,242,240,241,241,1,243,
  62220. 79,14,160,57,241,50,57,248,16,246,139,91,185,245,47,1,129,121,242,244,242,
  62221. 185,47,13,58,121,245,132,242,31,1,201,240,56,210,241,9,105,241,237,242,47,
  62222. 4,153,121,246,130,47,5,80,80,251,255,23,240,115,255,225,0,31,35,31,5,15,
  62223. 109,197,4,191,254,175,34,247,240,245,47,16,255,225,30,95,91,31,255,0,100,
  62224. 121,159,55,13,31,100,31,254,0,64,64,80,240,148,244,161,242,79,1,201,127,2,
  62225. 240,9,240,231,240,188,241,227,242,29,240,25,244,29,208,145,57,241,48,242,
  62226. 96,34,49,97,32,255,224,21,114,19,159,255,0,62,24,15,254,29,95,0,240,38,209,
  62227. 240,162,251,41,241,112,0,
  62228. };
  62229. #endif
  62230. /*
  62231. * Case conversion tables generated using src/extract_caseconv.py.
  62232. */
  62233. /* duk_unicode_caseconv_uc[] */
  62234. /* duk_unicode_caseconv_lc[] */
  62235. /*
  62236. * Automatically generated by extract_caseconv.py, do not edit!
  62237. */
  62238. const duk_uint8_t duk_unicode_caseconv_uc[1288] = {
  62239. 132,3,128,3,0,184,7,192,6,192,112,35,242,199,224,64,74,192,49,32,128,162,
  62240. 128,108,65,1,189,129,254,131,3,173,3,136,6,7,98,7,34,68,15,12,14,140,72,30,
  62241. 104,28,112,32,67,0,65,4,0,138,0,128,4,1,88,65,76,83,15,128,15,132,8,31,16,
  62242. 31,24,12,62,64,62,80,32,124,192,124,224,64,250,0,250,64,97,246,1,246,129,3,
  62243. 238,3,247,64,135,220,135,242,2,15,187,15,237,2,31,120,31,248,4,62,244,63,
  62244. 212,8,125,240,127,232,16,253,128,253,192,33,253,1,253,128,67,252,3,253,0,
  62245. 136,92,8,88,8,18,104,18,91,26,44,48,44,0,94,90,0,33,64,155,253,7,252,132,
  62246. 212,0,32,32,32,6,0,76,192,76,129,128,157,0,156,136,1,75,1,74,46,2,244,2,
  62247. 242,12,6,12,6,8,16,13,8,13,0,48,27,64,27,48,64,57,192,57,162,0,119,192,119,
  62248. 132,128,252,128,252,20,2,35,2,34,18,4,142,4,140,20,13,196,13,192,16,30,200,
  62249. 30,192,192,70,16,70,2,32,145,96,145,70,193,48,129,48,67,130,104,130,104,44,
  62250. 30,1,30,0,150,61,66,61,64,192,125,68,125,100,33,99,65,99,56,50,200,18,200,
  62251. 6,69,157,133,157,96,169,144,105,144,11,211,64,211,64,12,167,35,167,34,15,
  62252. 78,103,78,100,126,157,234,157,228,21,59,253,59,240,90,122,26,122,0,163,128,
  62253. 214,128,214,2,1,197,1,196,6,3,140,3,136,12,7,200,7,196,16,20,0,13,48,32,63,
  62254. 128,63,112,69,142,101,142,64,130,1,136,1,135,4,3,114,3,112,8,26,120,202,
  62255. 120,176,65,1,30,1,29,130,2,105,1,150,5,255,96,22,160,115,128,31,224,47,0,
  62256. 38,32,9,32,47,224,10,96,48,0,72,96,50,64,50,32,50,160,62,192,51,32,51,0,51,
  62257. 64,71,160,51,192,68,0,53,0,52,224,55,224,62,224,59,160,49,192,62,96,62,32,
  62258. 74,5,141,224,74,37,141,160,74,69,142,0,74,96,48,32,74,128,48,192,75,32,49,
  62259. 224,75,96,50,0,76,0,50,96,76,96,50,128,76,180,241,160,77,0,50,224,77,101,
  62260. 140,64,78,37,141,192,78,64,51,160,78,160,51,224,79,165,140,128,81,0,53,192,
  62261. 81,32,72,128,81,128,72,160,82,64,54,224,104,160,115,32,110,224,110,192,117,
  62262. 128,112,192,120,64,116,96,121,128,113,128,122,0,114,64,122,32,115,0,122,
  62263. 160,116,192,122,192,116,0,122,224,121,224,126,0,115,64,126,32,116,32,126,
  62264. 64,127,32,126,160,114,160,153,224,152,3,175,52,239,163,175,165,140,99,211,
  62265. 99,204,3,247,192,115,35,252,163,253,132,41,196,38,68,48,132,48,101,140,37,
  62266. 140,5,140,160,71,69,140,192,71,217,128,55,224,5,48,5,48,20,152,10,240,1,56,
  62267. 7,194,0,74,3,12,3,144,192,230,64,194,0,192,64,236,48,58,80,48,128,48,16,88,
  62268. 120,20,212,21,72,122,90,0,72,3,49,30,151,128,21,0,194,7,166,32,5,112,48,
  62269. 161,233,152,1,100,12,40,122,106,0,65,2,190,31,80,128,233,64,196,199,212,
  62270. 176,58,80,49,48,48,1,245,76,14,148,12,76,12,4,125,91,3,165,3,19,3,66,31,
  62271. 128,135,194,0,230,71,224,97,240,144,57,145,248,40,124,40,14,100,126,14,31,
  62272. 11,3,153,31,132,135,195,0,230,71,225,97,240,208,57,145,248,104,124,56,14,
  62273. 100,126,30,31,15,3,153,31,136,135,194,0,230,71,226,97,240,144,57,145,248,
  62274. 168,124,40,14,100,126,46,31,11,3,153,31,140,135,195,0,230,71,227,97,240,
  62275. 208,57,145,248,232,124,56,14,100,126,62,31,15,3,153,31,144,135,202,0,230,
  62276. 71,228,97,242,144,57,145,249,40,124,168,14,100,126,78,31,43,3,153,31,148,
  62277. 135,203,0,230,71,229,97,242,208,57,145,249,104,124,184,14,100,126,94,31,47,
  62278. 3,153,31,152,135,202,0,230,71,230,97,242,144,57,145,249,168,124,168,14,100,
  62279. 126,110,31,43,3,153,31,156,135,203,0,230,71,231,97,242,208,57,145,249,232,
  62280. 124,184,14,100,126,126,31,47,3,153,31,160,135,218,0,230,71,232,97,246,144,
  62281. 57,145,250,40,125,168,14,100,126,142,31,107,3,153,31,164,135,219,0,230,71,
  62282. 233,97,246,208,57,145,250,104,125,184,14,100,126,158,31,111,3,153,31,168,
  62283. 135,218,0,230,71,234,97,246,144,57,145,250,168,125,168,14,100,126,174,31,
  62284. 107,3,153,31,172,135,219,0,230,71,235,97,246,208,57,145,250,232,125,184,14,
  62285. 100,126,190,31,111,3,153,31,178,135,238,128,230,71,236,224,57,16,57,145,
  62286. 251,72,14,24,14,100,126,218,3,145,3,66,31,183,192,228,64,208,128,230,71,
  62287. 239,32,57,16,57,145,252,40,127,40,14,100,127,14,3,151,3,153,31,196,128,226,
  62288. 64,230,71,241,160,57,112,52,33,252,124,14,92,13,8,14,100,127,50,3,151,3,
  62289. 153,31,210,192,230,64,194,0,192,7,244,240,57,144,48,128,48,17,253,104,14,
  62290. 100,13,8,127,95,3,153,3,8,3,66,31,226,192,233,64,194,0,192,7,248,240,58,80,
  62291. 48,128,48,17,254,72,14,132,12,76,127,154,3,165,3,66,31,231,192,233,64,194,
  62292. 0,208,135,252,161,255,160,57,145,255,56,14,164,14,100,127,210,3,143,3,153,
  62293. 31,246,128,234,64,208,135,253,240,58,144,52,32,57,145,255,200,14,164,14,
  62294. 103,236,2,0,70,0,70,251,1,128,17,128,18,126,192,160,4,96,4,207,176,60,1,24,
  62295. 1,24,1,39,236,19,0,70,0,70,0,76,251,5,128,20,192,21,62,193,160,5,48,5,79,
  62296. 177,56,21,16,21,27,236,82,5,68,5,53,251,21,129,81,1,78,254,197,160,84,224,
  62297. 84,111,177,120,21,16,20,244,
  62298. };
  62299. const duk_uint8_t duk_unicode_caseconv_lc[616] = {
  62300. 144,3,0,3,128,184,6,192,7,192,112,24,144,37,96,64,54,32,81,64,128,226,0,
  62301. 235,65,129,199,1,230,130,3,145,3,177,34,7,70,7,134,36,15,244,13,236,24,32,
  62302. 0,34,129,0,65,0,67,4,0,166,32,172,41,132,40,11,64,19,15,132,15,128,8,31,24,
  62303. 31,16,12,62,80,62,64,32,124,224,124,192,64,250,64,250,0,97,246,129,246,1,3,
  62304. 241,3,240,2,7,230,7,228,4,15,212,15,208,8,31,184,31,176,4,63,116,62,224,8,
  62305. 127,32,125,200,32,254,192,254,128,33,253,161,247,96,67,253,3,252,0,135,250,
  62306. 135,222,129,15,252,15,188,2,31,250,31,124,4,66,192,66,224,64,146,216,147,
  62307. 64,209,96,1,97,130,242,199,224,35,240,95,228,63,232,38,161,1,0,1,1,48,2,
  62308. 100,2,102,12,4,228,4,232,64,10,80,10,89,112,23,144,23,160,96,48,64,48,96,
  62309. 128,104,0,104,65,128,217,128,218,2,1,203,1,204,18,3,188,3,190,36,7,200,7,
  62310. 204,16,15,192,15,201,64,34,32,34,49,32,72,192,72,225,64,220,0,220,65,1,236,
  62311. 1,236,140,4,96,4,97,34,9,20,9,22,108,19,4,19,8,56,38,128,38,138,193,224,1,
  62312. 224,25,99,212,3,212,44,7,214,71,212,66,22,51,150,52,3,44,128,44,129,100,89,
  62313. 214,89,216,10,153,2,153,4,189,52,5,52,8,202,114,42,114,48,244,230,84,230,
  62314. 103,233,222,105,222,129,83,191,83,191,133,167,160,167,161,10,48,13,48,20,0,
  62315. 32,26,192,26,208,64,56,128,56,192,192,113,64,113,129,1,251,129,252,2,44,
  62316. 114,44,115,4,16,12,56,12,64,32,27,128,27,144,64,211,197,211,198,2,8,6,88,9,
  62317. 164,16,17,216,17,224,47,245,1,120,0,255,1,129,2,83,1,134,2,84,1,142,1,221,
  62318. 1,143,2,89,1,144,2,91,1,145,1,146,1,147,2,96,1,148,2,99,1,151,2,104,1,152,
  62319. 1,153,1,157,2,114,1,159,2,117,1,167,1,168,1,174,2,136,1,183,2,146,1,241,1,
  62320. 243,1,246,1,149,1,247,1,191,2,32,1,158,2,58,44,101,2,61,1,154,2,62,44,102,
  62321. 2,67,1,128,2,68,2,137,2,69,2,140,3,118,3,119,3,134,3,172,3,140,3,204,3,207,
  62322. 3,215,3,244,3,184,3,249,3,242,4,192,4,207,30,158,0,223,31,188,31,179,31,
  62323. 204,31,195,31,236,31,229,31,252,31,243,33,38,3,201,33,42,0,107,33,43,0,229,
  62324. 33,50,33,78,33,131,33,132,44,96,44,97,44,98,2,107,44,99,29,125,44,100,2,
  62325. 125,44,109,2,81,44,110,2,113,44,111,2,80,44,112,2,82,167,125,29,121,167,
  62326. 141,2,101,2,2,97,0,52,129,131,128,
  62327. };
  62328. #line 1 "duk_util_bitdecoder.c"
  62329. /*
  62330. * Bitstream decoder.
  62331. */
  62332. /* include removed: duk_internal.h */
  62333. /* Decode 'bits' bits from the input stream (bits must be 1...24).
  62334. * When reading past bitstream end, zeroes are shifted in. The result
  62335. * is signed to match duk_bd_decode_flagged.
  62336. */
  62337. DUK_INTERNAL duk_int32_t duk_bd_decode(duk_bitdecoder_ctx *ctx, duk_small_int_t bits) {
  62338. duk_small_int_t shift;
  62339. duk_uint32_t mask;
  62340. duk_uint32_t tmp;
  62341. /* Note: cannot read more than 24 bits without possibly shifting top bits out.
  62342. * Fixable, but adds complexity.
  62343. */
  62344. DUK_ASSERT(bits >= 1 && bits <= 24);
  62345. while (ctx->currbits < bits) {
  62346. #if 0
  62347. DUK_DDD(DUK_DDDPRINT("decode_bits: shift more data (bits=%ld, currbits=%ld)",
  62348. (long) bits, (long) ctx->currbits));
  62349. #endif
  62350. ctx->currval <<= 8;
  62351. if (ctx->offset < ctx->length) {
  62352. /* If ctx->offset >= ctx->length, we "shift zeroes in"
  62353. * instead of croaking.
  62354. */
  62355. ctx->currval |= ctx->data[ctx->offset++];
  62356. }
  62357. ctx->currbits += 8;
  62358. }
  62359. #if 0
  62360. DUK_DDD(DUK_DDDPRINT("decode_bits: bits=%ld, currbits=%ld, currval=0x%08lx",
  62361. (long) bits, (long) ctx->currbits, (unsigned long) ctx->currval));
  62362. #endif
  62363. /* Extract 'top' bits of currval; note that the extracted bits do not need
  62364. * to be cleared, we just ignore them on next round.
  62365. */
  62366. shift = ctx->currbits - bits;
  62367. mask = (1 << bits) - 1;
  62368. tmp = (ctx->currval >> shift) & mask;
  62369. ctx->currbits = shift; /* remaining */
  62370. #if 0
  62371. DUK_DDD(DUK_DDDPRINT("decode_bits: %ld bits -> 0x%08lx (%ld), currbits=%ld, currval=0x%08lx",
  62372. (long) bits, (unsigned long) tmp, (long) tmp, (long) ctx->currbits, (unsigned long) ctx->currval));
  62373. #endif
  62374. return tmp;
  62375. }
  62376. DUK_INTERNAL duk_small_int_t duk_bd_decode_flag(duk_bitdecoder_ctx *ctx) {
  62377. return (duk_small_int_t) duk_bd_decode(ctx, 1);
  62378. }
  62379. /* Decode a one-bit flag, and if set, decode a value of 'bits', otherwise return
  62380. * default value. Return value is signed so that negative marker value can be
  62381. * used by caller as a "not present" value.
  62382. */
  62383. DUK_INTERNAL duk_int32_t duk_bd_decode_flagged(duk_bitdecoder_ctx *ctx, duk_small_int_t bits, duk_int32_t def_value) {
  62384. if (duk_bd_decode_flag(ctx)) {
  62385. return (duk_int32_t) duk_bd_decode(ctx, bits);
  62386. } else {
  62387. return def_value;
  62388. }
  62389. }
  62390. #line 1 "duk_util_bitencoder.c"
  62391. /*
  62392. * Bitstream encoder.
  62393. */
  62394. /* include removed: duk_internal.h */
  62395. DUK_INTERNAL void duk_be_encode(duk_bitencoder_ctx *ctx, duk_uint32_t data, duk_small_int_t bits) {
  62396. duk_uint8_t tmp;
  62397. DUK_ASSERT(ctx != NULL);
  62398. DUK_ASSERT(ctx->currbits < 8);
  62399. /* This limitation would be fixable but adds unnecessary complexity. */
  62400. DUK_ASSERT(bits >= 1 && bits <= 24);
  62401. ctx->currval = (ctx->currval << bits) | data;
  62402. ctx->currbits += bits;
  62403. while (ctx->currbits >= 8) {
  62404. if (ctx->offset < ctx->length) {
  62405. tmp = (duk_uint8_t) ((ctx->currval >> (ctx->currbits - 8)) & 0xff);
  62406. ctx->data[ctx->offset++] = tmp;
  62407. } else {
  62408. /* If buffer has been exhausted, truncate bitstream */
  62409. ctx->truncated = 1;
  62410. }
  62411. ctx->currbits -= 8;
  62412. }
  62413. }
  62414. DUK_INTERNAL void duk_be_finish(duk_bitencoder_ctx *ctx) {
  62415. duk_small_int_t npad;
  62416. DUK_ASSERT(ctx != NULL);
  62417. DUK_ASSERT(ctx->currbits < 8);
  62418. npad = (duk_small_int_t) (8 - ctx->currbits);
  62419. if (npad > 0) {
  62420. duk_be_encode(ctx, 0, npad);
  62421. }
  62422. DUK_ASSERT(ctx->currbits == 0);
  62423. }
  62424. #line 1 "duk_util_hashbytes.c"
  62425. /*
  62426. * Hash function duk_util_hashbytes().
  62427. *
  62428. * Currently, 32-bit MurmurHash2.
  62429. *
  62430. * Don't rely on specific hash values; hash function may be endianness
  62431. * dependent, for instance.
  62432. */
  62433. /* include removed: duk_internal.h */
  62434. /* 'magic' constants for Murmurhash2 */
  62435. #define DUK__MAGIC_M ((duk_uint32_t) 0x5bd1e995UL)
  62436. #define DUK__MAGIC_R 24
  62437. DUK_INTERNAL duk_uint32_t duk_util_hashbytes(const duk_uint8_t *data, duk_size_t len, duk_uint32_t seed) {
  62438. duk_uint32_t h = seed ^ ((duk_uint32_t) len);
  62439. while (len >= 4) {
  62440. /* Portability workaround is required for platforms without
  62441. * unaligned access. The replacement code emulates little
  62442. * endian access even on big endian architectures, which is
  62443. * OK as long as it is consistent for a build.
  62444. */
  62445. #ifdef DUK_USE_HASHBYTES_UNALIGNED_U32_ACCESS
  62446. duk_uint32_t k = *((duk_uint32_t *) data);
  62447. #else
  62448. duk_uint32_t k = ((duk_uint32_t) data[0]) |
  62449. (((duk_uint32_t) data[1]) << 8) |
  62450. (((duk_uint32_t) data[2]) << 16) |
  62451. (((duk_uint32_t) data[3]) << 24);
  62452. #endif
  62453. k *= DUK__MAGIC_M;
  62454. k ^= k >> DUK__MAGIC_R;
  62455. k *= DUK__MAGIC_M;
  62456. h *= DUK__MAGIC_M;
  62457. h ^= k;
  62458. data += 4;
  62459. len -= 4;
  62460. }
  62461. switch (len) {
  62462. case 3: h ^= data[2] << 16;
  62463. case 2: h ^= data[1] << 8;
  62464. case 1: h ^= data[0];
  62465. h *= DUK__MAGIC_M;
  62466. }
  62467. h ^= h >> 13;
  62468. h *= DUK__MAGIC_M;
  62469. h ^= h >> 15;
  62470. return h;
  62471. }
  62472. #line 1 "duk_util_tinyrandom.c"
  62473. /*
  62474. * A tiny random number generator.
  62475. *
  62476. * Currently used for Math.random().
  62477. *
  62478. * http://www.woodmann.com/forum/archive/index.php/t-3100.html
  62479. */
  62480. /* include removed: duk_internal.h */
  62481. #define DUK__UPDATE_RND(rnd) do { \
  62482. (rnd) += ((rnd) * (rnd)) | 0x05; \
  62483. (rnd) = ((rnd) & 0xffffffffU); /* if duk_uint32_t is exactly 32 bits, this is a NOP */ \
  62484. } while (0)
  62485. #define DUK__RND_BIT(rnd) ((rnd) >> 31) /* only use the highest bit */
  62486. DUK_INTERNAL duk_uint32_t duk_util_tinyrandom_get_bits(duk_hthread *thr, duk_small_int_t n) {
  62487. duk_small_int_t i;
  62488. duk_uint32_t res = 0;
  62489. duk_uint32_t rnd;
  62490. rnd = thr->heap->rnd_state;
  62491. for (i = 0; i < n; i++) {
  62492. DUK__UPDATE_RND(rnd);
  62493. res <<= 1;
  62494. res += DUK__RND_BIT(rnd);
  62495. }
  62496. thr->heap->rnd_state = rnd;
  62497. return res;
  62498. }
  62499. DUK_INTERNAL duk_double_t duk_util_tinyrandom_get_double(duk_hthread *thr) {
  62500. duk_double_t t;
  62501. duk_small_int_t n;
  62502. duk_uint32_t rnd;
  62503. /*
  62504. * XXX: could make this a lot faster if we create the double memory
  62505. * representation directly. Feasible easily (must be uniform random).
  62506. */
  62507. rnd = thr->heap->rnd_state;
  62508. n = 53; /* enough to cover the whole mantissa */
  62509. t = 0.0;
  62510. do {
  62511. DUK__UPDATE_RND(rnd);
  62512. t += DUK__RND_BIT(rnd);
  62513. t /= 2.0;
  62514. } while (--n);
  62515. thr->heap->rnd_state = rnd;
  62516. DUK_ASSERT(t >= (duk_double_t) 0.0);
  62517. DUK_ASSERT(t < (duk_double_t) 1.0);
  62518. return t;
  62519. }