PageRenderTime 416ms CodeModel.GetById 33ms RepoModel.GetById 10ms app.codeStats 1ms

/erts/emulator/beam/beam_emu.c

https://github.com/Bwooce/otp
C | 6589 lines | 4900 code | 730 blank | 959 comment | 905 complexity | 29d45437e2edcfc7ffe8a39bb9a27dfb MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-2-Clause
  1. /*
  2. * %CopyrightBegin%
  3. *
  4. * Copyright Ericsson AB 1996-2010. All Rights Reserved.
  5. *
  6. * The contents of this file are subject to the Erlang Public License,
  7. * Version 1.1, (the "License"); you may not use this file except in
  8. * compliance with the License. You should have received a copy of the
  9. * Erlang Public License along with this software. If not, it can be
  10. * retrieved online at http://www.erlang.org/.
  11. *
  12. * Software distributed under the License is distributed on an "AS IS"
  13. * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
  14. * the License for the specific language governing rights and limitations
  15. * under the License.
  16. *
  17. * %CopyrightEnd%
  18. */
  19. #ifdef HAVE_CONFIG_H
  20. # include "config.h"
  21. #endif
  22. #include <stddef.h> /* offsetof() */
  23. #include "sys.h"
  24. #include "erl_vm.h"
  25. #include "global.h"
  26. #include "erl_process.h"
  27. #include "erl_nmgc.h"
  28. #include "error.h"
  29. #include "bif.h"
  30. #include "big.h"
  31. #include "beam_load.h"
  32. #include "erl_binary.h"
  33. #include "erl_bits.h"
  34. #include "dist.h"
  35. #include "beam_bp.h"
  36. #include "beam_catches.h"
  37. #ifdef HIPE
  38. #include "hipe_mode_switch.h"
  39. #include "hipe_bif1.h"
  40. #endif
  41. /* #define HARDDEBUG 1 */
  42. #if defined(NO_JUMP_TABLE)
  43. # define OpCase(OpCode) case op_##OpCode: lb_##OpCode
  44. # define CountCase(OpCode) case op_count_##OpCode
  45. # define OpCode(OpCode) ((Uint*)op_##OpCode)
  46. # define Goto(Rel) {Go = (int)(Rel); goto emulator_loop;}
  47. # define LabelAddr(Addr) &&##Addr
  48. #else
  49. # define OpCase(OpCode) lb_##OpCode
  50. # define CountCase(OpCode) lb_count_##OpCode
  51. # define Goto(Rel) goto *(Rel)
  52. # define LabelAddr(Label) &&Label
  53. # define OpCode(OpCode) (&&lb_##OpCode)
  54. #endif
  55. #ifdef ERTS_ENABLE_LOCK_CHECK
  56. # ifdef ERTS_SMP
  57. # define PROCESS_MAIN_CHK_LOCKS(P) \
  58. do { \
  59. if ((P)) { \
  60. erts_pix_lock_t *pix_lock__ = ERTS_PIX2PIXLOCK(internal_pid_index((P)->id));\
  61. erts_proc_lc_chk_only_proc_main((P)); \
  62. erts_pix_lock(pix_lock__); \
  63. ASSERT(0 < (P)->lock.refc && (P)->lock.refc < erts_no_schedulers*5);\
  64. erts_pix_unlock(pix_lock__); \
  65. } \
  66. else \
  67. erts_lc_check_exact(NULL, 0); \
  68. ERTS_SMP_LC_ASSERT(!ERTS_LC_IS_BLOCKING); \
  69. } while (0)
  70. # define ERTS_SMP_REQ_PROC_MAIN_LOCK(P) \
  71. if ((P)) erts_proc_lc_require_lock((P), ERTS_PROC_LOCK_MAIN)
  72. # define ERTS_SMP_UNREQ_PROC_MAIN_LOCK(P) \
  73. if ((P)) erts_proc_lc_unrequire_lock((P), ERTS_PROC_LOCK_MAIN)
  74. # else
  75. # define ERTS_SMP_REQ_PROC_MAIN_LOCK(P)
  76. # define ERTS_SMP_UNREQ_PROC_MAIN_LOCK(P)
  77. # define PROCESS_MAIN_CHK_LOCKS(P) erts_lc_check_exact(NULL, 0)
  78. # endif
  79. #else
  80. # define PROCESS_MAIN_CHK_LOCKS(P)
  81. # define ERTS_SMP_REQ_PROC_MAIN_LOCK(P)
  82. # define ERTS_SMP_UNREQ_PROC_MAIN_LOCK(P)
  83. #endif
  84. /*
  85. * Define macros for deep checking of terms.
  86. */
  87. #if defined(HARDDEBUG)
  88. # define CHECK_TERM(T) size_object(T)
  89. # define CHECK_ARGS(PC) \
  90. do { \
  91. int i_; \
  92. int Arity_ = PC[-1]; \
  93. if (Arity_ > 0) { \
  94. CHECK_TERM(r(0)); \
  95. } \
  96. for (i_ = 1; i_ < Arity_; i_++) { \
  97. CHECK_TERM(x(i_)); \
  98. } \
  99. } while (0)
  100. #else
  101. # define CHECK_TERM(T) ASSERT(!is_CP(T))
  102. # define CHECK_ARGS(T)
  103. #endif
  104. #ifndef MAX
  105. #define MAX(x, y) (((x) > (y)) ? (x) : (y))
  106. #endif
  107. #define GET_BIF_ADDRESS(p) ((BifFunction) (((Export *) p)->code[4]))
  108. #define TermWords(t) (((t) / (sizeof(BeamInstr)/sizeof(Eterm))) + !!((t) % (sizeof(BeamInstr)/sizeof(Eterm))))
  109. /*
  110. * We reuse some of fields in the save area in the process structure.
  111. * This is safe to do, since this space is only activly used when
  112. * the process is switched out.
  113. */
  114. #define REDS_IN(p) ((p)->def_arg_reg[5])
  115. /*
  116. * Add a byte offset to a pointer to Eterm. This is useful when the
  117. * the loader has precalculated a byte offset.
  118. */
  119. #define ADD_BYTE_OFFSET(ptr, offset) \
  120. ((Eterm *) (((unsigned char *)ptr) + (offset)))
  121. /* We don't check the range if an ordinary switch is used */
  122. #ifdef NO_JUMP_TABLE
  123. #define VALID_INSTR(IP) (0 <= (int)(IP) && ((int)(IP) < (NUMBER_OF_OPCODES*2+10)))
  124. #else
  125. #define VALID_INSTR(IP) \
  126. ((SWord)LabelAddr(emulator_loop) <= (SWord)(IP) && \
  127. (SWord)(IP) < (SWord)LabelAddr(end_emulator_loop))
  128. #endif /* NO_JUMP_TABLE */
  129. #define SET_CP(p, ip) \
  130. ASSERT(VALID_INSTR(*(ip))); \
  131. (p)->cp = (ip)
  132. #define SET_I(ip) \
  133. ASSERT(VALID_INSTR(* (Eterm *)(ip))); \
  134. I = (ip)
  135. #define FetchArgs(S1, S2) tmp_arg1 = (S1); tmp_arg2 = (S2)
  136. /*
  137. * Store a result into a register given a destination descriptor.
  138. */
  139. #define StoreResult(Result, DestDesc) \
  140. do { \
  141. Eterm stb_reg; \
  142. stb_reg = (DestDesc); \
  143. CHECK_TERM(Result); \
  144. switch (beam_reg_tag(stb_reg)) { \
  145. case R_REG_DEF: \
  146. r(0) = (Result); break; \
  147. case X_REG_DEF: \
  148. xb(x_reg_offset(stb_reg)) = (Result); break; \
  149. default: \
  150. yb(y_reg_offset(stb_reg)) = (Result); break; \
  151. } \
  152. } while (0)
  153. #define StoreSimpleDest(Src, Dest) Dest = (Src)
  154. /*
  155. * Store a result into a register and execute the next instruction.
  156. * Dst points to the word with a destination descriptor, which MUST
  157. * be just before the next instruction.
  158. */
  159. #define StoreBifResult(Dst, Result) \
  160. do { \
  161. BeamInstr* stb_next; \
  162. Eterm stb_reg; \
  163. stb_reg = Arg(Dst); \
  164. I += (Dst) + 2; \
  165. stb_next = (BeamInstr *) *I; \
  166. CHECK_TERM(Result); \
  167. switch (beam_reg_tag(stb_reg)) { \
  168. case R_REG_DEF: \
  169. r(0) = (Result); Goto(stb_next); \
  170. case X_REG_DEF: \
  171. xb(x_reg_offset(stb_reg)) = (Result); Goto(stb_next); \
  172. default: \
  173. yb(y_reg_offset(stb_reg)) = (Result); Goto(stb_next); \
  174. } \
  175. } while (0)
  176. #define ClauseFail() goto lb_jump_f
  177. #define SAVE_CP(X) \
  178. do { \
  179. *(X) = make_cp(c_p->cp); \
  180. c_p->cp = 0; \
  181. } while(0)
  182. #define RESTORE_CP(X) SET_CP(c_p, (BeamInstr *) cp_val(*(X)))
  183. #define ISCATCHEND(instr) ((Eterm *) *(instr) == OpCode(catch_end_y))
  184. /*
  185. * Special Beam instructions.
  186. */
  187. BeamInstr beam_apply[2];
  188. BeamInstr beam_exit[1];
  189. BeamInstr beam_continue_exit[1];
  190. BeamInstr* em_call_error_handler;
  191. BeamInstr* em_apply_bif;
  192. BeamInstr* em_call_traced_function;
  193. /* NOTE These should be the only variables containing trace instructions.
  194. ** Sometimes tests are form the instruction value, and sometimes
  195. ** for the refering variable (one of these), and rouge references
  196. ** will most likely cause chaos.
  197. */
  198. BeamInstr beam_return_to_trace[1]; /* OpCode(i_return_to_trace) */
  199. BeamInstr beam_return_trace[1]; /* OpCode(i_return_trace) */
  200. BeamInstr beam_exception_trace[1]; /* UGLY also OpCode(i_return_trace) */
  201. BeamInstr beam_return_time_trace[1]; /* OpCode(i_return_time_trace) */
  202. /*
  203. * All Beam instructions in numerical order.
  204. */
  205. #ifndef NO_JUMP_TABLE
  206. void** beam_ops;
  207. #endif
  208. #ifndef ERTS_SMP /* Not supported with smp emulator */
  209. extern int count_instructions;
  210. #endif
  211. #if defined(HYBRID)
  212. #define SWAPIN \
  213. g_htop = global_htop; \
  214. g_hend = global_hend; \
  215. HTOP = HEAP_TOP(c_p); \
  216. E = c_p->stop
  217. #define SWAPOUT \
  218. global_htop = g_htop; \
  219. global_hend = g_hend; \
  220. HEAP_TOP(c_p) = HTOP; \
  221. c_p->stop = E
  222. #else
  223. #define SWAPIN \
  224. HTOP = HEAP_TOP(c_p); \
  225. E = c_p->stop
  226. #define SWAPOUT \
  227. HEAP_TOP(c_p) = HTOP; \
  228. c_p->stop = E
  229. /*
  230. * Use LIGHT_SWAPOUT when the called function
  231. * will call HeapOnlyAlloc() (and never HAlloc()).
  232. */
  233. #ifdef DEBUG
  234. # /* The stack pointer is used in an assertion. */
  235. # define LIGHT_SWAPOUT SWAPOUT
  236. #else
  237. # define LIGHT_SWAPOUT HEAP_TOP(c_p) = HTOP
  238. #endif
  239. /*
  240. * Use LIGHT_SWAPIN when we know that c_p->stop cannot
  241. * have been updated (i.e. if there cannot have been
  242. * a garbage-collection).
  243. */
  244. #define LIGHT_SWAPIN HTOP = HEAP_TOP(c_p)
  245. #endif
  246. #ifdef FORCE_HEAP_FRAGS
  247. # define HEAP_SPACE_VERIFIED(Words) do { \
  248. c_p->space_verified = (Words); \
  249. c_p->space_verified_from = HTOP; \
  250. }while(0)
  251. #else
  252. # define HEAP_SPACE_VERIFIED(Words) ((void)0)
  253. #endif
  254. #define PRE_BIF_SWAPOUT(P) \
  255. HEAP_TOP((P)) = HTOP; \
  256. (P)->stop = E; \
  257. PROCESS_MAIN_CHK_LOCKS((P)); \
  258. ERTS_SMP_UNREQ_PROC_MAIN_LOCK((P))
  259. #if defined(HYBRID)
  260. # define POST_BIF_GC_SWAPIN_0(_p, _res) \
  261. if (((_p)->mbuf) || (MSO(_p).overhead >= BIN_VHEAP_SZ(_p)) ) { \
  262. _res = erts_gc_after_bif_call((_p), (_res), NULL, 0); \
  263. } \
  264. SWAPIN
  265. # define POST_BIF_GC_SWAPIN(_p, _res, _regs, _arity) \
  266. if (((_p)->mbuf) || (MSO(_p).overhead >= BIN_VHEAP_SZ(_p)) ) { \
  267. _regs[0] = r(0); \
  268. _res = erts_gc_after_bif_call((_p), (_res), _regs, (_arity)); \
  269. r(0) = _regs[0]; \
  270. } \
  271. SWAPIN
  272. #else
  273. # define POST_BIF_GC_SWAPIN_0(_p, _res) \
  274. ERTS_SMP_REQ_PROC_MAIN_LOCK((_p)); \
  275. PROCESS_MAIN_CHK_LOCKS((_p)); \
  276. ERTS_VERIFY_UNUSED_TEMP_ALLOC((_p)); \
  277. if (((_p)->mbuf) || (MSO(_p).overhead >= BIN_VHEAP_SZ(_p)) ) { \
  278. _res = erts_gc_after_bif_call((_p), (_res), NULL, 0); \
  279. E = (_p)->stop; \
  280. } \
  281. HTOP = HEAP_TOP((_p))
  282. # define POST_BIF_GC_SWAPIN(_p, _res, _regs, _arity) \
  283. ERTS_VERIFY_UNUSED_TEMP_ALLOC((_p)); \
  284. ERTS_SMP_REQ_PROC_MAIN_LOCK((_p)); \
  285. PROCESS_MAIN_CHK_LOCKS((_p)); \
  286. if (((_p)->mbuf) || (MSO(_p).overhead >= BIN_VHEAP_SZ(_p)) ) { \
  287. _regs[0] = r(0); \
  288. _res = erts_gc_after_bif_call((_p), (_res), _regs, (_arity)); \
  289. r(0) = _regs[0]; \
  290. E = (_p)->stop; \
  291. } \
  292. HTOP = HEAP_TOP((_p))
  293. #endif
  294. #define db(N) (N)
  295. #define tb(N) (N)
  296. #define xb(N) (*(Eterm *) (((unsigned char *)reg) + (N)))
  297. #define yb(N) (*(Eterm *) (((unsigned char *)E) + (N)))
  298. #define fb(N) (*(double *) (((unsigned char *)&(freg[0].fd)) + (N)))
  299. #define Qb(N) (N)
  300. #define Ib(N) (N)
  301. #define x(N) reg[N]
  302. #define y(N) E[N]
  303. #define r(N) x##N
  304. /*
  305. * Makes sure that there are StackNeed + HeapNeed + 1 words available
  306. * on the combined heap/stack segment, then allocates StackNeed + 1
  307. * words on the stack and saves CP.
  308. *
  309. * M is number of live registers to preserve during garbage collection
  310. */
  311. #define AH(StackNeed, HeapNeed, M) \
  312. do { \
  313. int needed; \
  314. needed = (StackNeed) + 1; \
  315. if (E - HTOP < (needed + (HeapNeed))) { \
  316. SWAPOUT; \
  317. reg[0] = r(0); \
  318. PROCESS_MAIN_CHK_LOCKS(c_p); \
  319. FCALLS -= erts_garbage_collect(c_p, needed + (HeapNeed), reg, (M)); \
  320. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p); \
  321. PROCESS_MAIN_CHK_LOCKS(c_p); \
  322. r(0) = reg[0]; \
  323. SWAPIN; \
  324. } \
  325. E -= needed; \
  326. SAVE_CP(E); \
  327. } while (0)
  328. #define Allocate(Ns, Live) AH(Ns, 0, Live)
  329. #define AllocateZero(Ns, Live) \
  330. do { Eterm* ptr; \
  331. int i = (Ns); \
  332. AH(i, 0, Live); \
  333. for (ptr = E + i; ptr > E; ptr--) { \
  334. make_blank(*ptr); \
  335. } \
  336. } while (0)
  337. #define AllocateHeap(Ns, Nh, Live) AH(Ns, Nh, Live)
  338. #define AllocateHeapZero(Ns, Nh, Live) \
  339. do { Eterm* ptr; \
  340. int i = (Ns); \
  341. AH(i, Nh, Live); \
  342. for (ptr = E + i; ptr > E; ptr--) { \
  343. make_blank(*ptr); \
  344. } \
  345. } while (0)
  346. #define AllocateInit(Ns, Live, Y) \
  347. do { AH(Ns, 0, Live); make_blank(Y); } while (0)
  348. /*
  349. * Like the AH macro, but allocates no additional heap space.
  350. */
  351. #define A(StackNeed, M) AH(StackNeed, 0, M)
  352. #define D(N) \
  353. RESTORE_CP(E); \
  354. E += (N) + 1;
  355. #define TestBinVHeap(VNh, Nh, Live) \
  356. do { \
  357. unsigned need = (Nh); \
  358. if ((E - HTOP < need) || (MSO(c_p).overhead + (VNh) >= BIN_VHEAP_SZ(c_p))) {\
  359. SWAPOUT; \
  360. reg[0] = r(0); \
  361. PROCESS_MAIN_CHK_LOCKS(c_p); \
  362. FCALLS -= erts_garbage_collect(c_p, need, reg, (Live)); \
  363. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p); \
  364. PROCESS_MAIN_CHK_LOCKS(c_p); \
  365. r(0) = reg[0]; \
  366. SWAPIN; \
  367. } \
  368. HEAP_SPACE_VERIFIED(need); \
  369. } while (0)
  370. /*
  371. * Check if Nh words of heap are available; if not, do a garbage collection.
  372. * Live is number of active argument registers to be preserved.
  373. */
  374. #define TestHeap(Nh, Live) \
  375. do { \
  376. unsigned need = (Nh); \
  377. if (E - HTOP < need) { \
  378. SWAPOUT; \
  379. reg[0] = r(0); \
  380. PROCESS_MAIN_CHK_LOCKS(c_p); \
  381. FCALLS -= erts_garbage_collect(c_p, need, reg, (Live)); \
  382. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p); \
  383. PROCESS_MAIN_CHK_LOCKS(c_p); \
  384. r(0) = reg[0]; \
  385. SWAPIN; \
  386. } \
  387. HEAP_SPACE_VERIFIED(need); \
  388. } while (0)
  389. /*
  390. * Check if Nh words of heap are available; if not, do a garbage collection.
  391. * Live is number of active argument registers to be preserved.
  392. * Takes special care to preserve Extra if a garbage collection occurs.
  393. */
  394. #define TestHeapPreserve(Nh, Live, Extra) \
  395. do { \
  396. unsigned need = (Nh); \
  397. if (E - HTOP < need) { \
  398. SWAPOUT; \
  399. reg[0] = r(0); \
  400. reg[Live] = Extra; \
  401. PROCESS_MAIN_CHK_LOCKS(c_p); \
  402. FCALLS -= erts_garbage_collect(c_p, need, reg, (Live)+1); \
  403. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p); \
  404. PROCESS_MAIN_CHK_LOCKS(c_p); \
  405. if (Live > 0) { \
  406. r(0) = reg[0]; \
  407. } \
  408. Extra = reg[Live]; \
  409. SWAPIN; \
  410. } \
  411. HEAP_SPACE_VERIFIED(need); \
  412. } while (0)
  413. #define TestHeapPutList(Need, Reg) \
  414. do { \
  415. TestHeap((Need), 1); \
  416. PutList(Reg, r(0), r(0), StoreSimpleDest); \
  417. CHECK_TERM(r(0)); \
  418. } while (0)
  419. #ifdef HYBRID
  420. #ifdef INCREMENTAL
  421. #define TestGlobalHeap(Nh, Live, hp) \
  422. do { \
  423. unsigned need = (Nh); \
  424. ASSERT(global_heap <= g_htop && g_htop <= global_hend); \
  425. SWAPOUT; \
  426. reg[0] = r(0); \
  427. FCALLS -= need; \
  428. (hp) = IncAlloc(c_p,need,reg,(Live)); \
  429. r(0) = reg[0]; \
  430. SWAPIN; \
  431. } while (0)
  432. #else
  433. #define TestGlobalHeap(Nh, Live, hp) \
  434. do { \
  435. unsigned need = (Nh); \
  436. ASSERT(global_heap <= g_htop && g_htop <= global_hend); \
  437. if (g_hend - g_htop < need) { \
  438. SWAPOUT; \
  439. reg[0] = r(0); \
  440. FCALLS -= erts_global_garbage_collect(c_p, need, reg, (Live)); \
  441. r(0) = reg[0]; \
  442. SWAPIN; \
  443. } \
  444. (hp) = global_htop; \
  445. } while (0)
  446. #endif
  447. #endif /* HYBRID */
  448. #define Init(N) make_blank(yb(N))
  449. #define Init2(Y1, Y2) do { make_blank(Y1); make_blank(Y2); } while (0)
  450. #define Init3(Y1, Y2, Y3) \
  451. do { make_blank(Y1); make_blank(Y2); make_blank(Y3); } while (0)
  452. #define MakeFun(FunP, NumFree) \
  453. do { \
  454. SWAPOUT; \
  455. reg[0] = r(0); \
  456. r(0) = new_fun(c_p, reg, (ErlFunEntry *) FunP, NumFree); \
  457. SWAPIN; \
  458. } while (0)
  459. #define PutTuple(Dst, Arity) \
  460. do { \
  461. Dst = make_tuple(HTOP); \
  462. pt_arity = (Arity); \
  463. } while (0)
  464. /*
  465. * Check that we haven't used the reductions and jump to function pointed to by
  466. * the I register. If we are out of reductions, do a context switch.
  467. */
  468. #define DispatchMacro() \
  469. do { \
  470. BeamInstr* dis_next; \
  471. dis_next = (BeamInstr *) *I; \
  472. CHECK_ARGS(I); \
  473. if (FCALLS > 0 || FCALLS > neg_o_reds) { \
  474. FCALLS--; \
  475. Goto(dis_next); \
  476. } else { \
  477. goto context_switch; \
  478. } \
  479. } while (0)
  480. #define DispatchMacroFun() \
  481. do { \
  482. BeamInstr* dis_next; \
  483. dis_next = (BeamInstr *) *I; \
  484. CHECK_ARGS(I); \
  485. if (FCALLS > 0 || FCALLS > neg_o_reds) { \
  486. FCALLS--; \
  487. Goto(dis_next); \
  488. } else { \
  489. goto context_switch_fun; \
  490. } \
  491. } while (0)
  492. #define DispatchMacrox() \
  493. do { \
  494. if (FCALLS > 0) { \
  495. Eterm* dis_next; \
  496. SET_I(((Export *) Arg(0))->address); \
  497. dis_next = (Eterm *) *I; \
  498. FCALLS--; \
  499. CHECK_ARGS(I); \
  500. Goto(dis_next); \
  501. } else if (ERTS_PROC_GET_SAVED_CALLS_BUF(c_p) \
  502. && FCALLS > neg_o_reds) { \
  503. goto save_calls1; \
  504. } else { \
  505. SET_I(((Export *) Arg(0))->address); \
  506. CHECK_ARGS(I); \
  507. goto context_switch; \
  508. } \
  509. } while (0)
  510. #ifdef DEBUG
  511. /*
  512. * To simplify breakpoint setting, put the code in one place only and jump to it.
  513. */
  514. # define Dispatch() goto do_dispatch
  515. # define Dispatchx() goto do_dispatchx
  516. # define Dispatchfun() goto do_dispatchfun
  517. #else
  518. /*
  519. * Inline for speed.
  520. */
  521. # define Dispatch() DispatchMacro()
  522. # define Dispatchx() DispatchMacrox()
  523. # define Dispatchfun() DispatchMacroFun()
  524. #endif
  525. #define Self(R) R = c_p->id
  526. #define Node(R) R = erts_this_node->sysname
  527. #define Arg(N) I[(N)+1]
  528. #define Next(N) \
  529. I += (N) + 1; \
  530. ASSERT(VALID_INSTR(*I)); \
  531. Goto(*I)
  532. #define PreFetch(N, Dst) do { Dst = (BeamInstr *) *(I + N + 1); } while (0)
  533. #define NextPF(N, Dst) \
  534. I += N + 1; \
  535. ASSERT(VALID_INSTR(Dst)); \
  536. Goto(Dst)
  537. #define GetR(pos, tr) \
  538. do { \
  539. tr = Arg(pos); \
  540. switch (beam_reg_tag(tr)) { \
  541. case R_REG_DEF: tr = r(0); break; \
  542. case X_REG_DEF: tr = xb(x_reg_offset(tr)); break; \
  543. case Y_REG_DEF: ASSERT(y_reg_offset(tr) >= 1); tr = yb(y_reg_offset(tr)); break; \
  544. } \
  545. CHECK_TERM(tr); \
  546. } while (0)
  547. #define GetArg1(N, Dst) GetR((N), Dst)
  548. #define GetArg2(N, Dst1, Dst2) \
  549. do { \
  550. GetR(N, Dst1); \
  551. GetR((N)+1, Dst2); \
  552. } while (0)
  553. #define PutList(H, T, Dst, Store) \
  554. do { \
  555. HTOP[0] = (H); HTOP[1] = (T); \
  556. Store(make_list(HTOP), Dst); \
  557. HTOP += 2; \
  558. } while (0)
  559. #define Move(Src, Dst, Store) \
  560. do { \
  561. Eterm term = (Src); \
  562. Store(term, Dst); \
  563. } while (0)
  564. #define Move2(src1, dst1, src2, dst2) dst1 = (src1); dst2 = (src2)
  565. #define MoveGenDest(src, dstp) \
  566. if ((dstp) == NULL) { r(0) = (src); } else { *(dstp) = src; }
  567. #define MoveReturn(Src, Dest) \
  568. (Dest) = (Src); \
  569. I = c_p->cp; \
  570. ASSERT(VALID_INSTR(*c_p->cp)); \
  571. c_p->cp = 0; \
  572. CHECK_TERM(r(0)); \
  573. Goto(*I)
  574. #define DeallocateReturn(Deallocate) \
  575. do { \
  576. int words_to_pop = (Deallocate); \
  577. SET_I((BeamInstr *) cp_val(*E)); \
  578. E = ADD_BYTE_OFFSET(E, words_to_pop); \
  579. CHECK_TERM(r(0)); \
  580. Goto(*I); \
  581. } while (0)
  582. #define MoveDeallocateReturn(Src, Dest, Deallocate) \
  583. (Dest) = (Src); \
  584. DeallocateReturn(Deallocate)
  585. #define MoveCall(Src, Dest, CallDest, Size) \
  586. (Dest) = (Src); \
  587. SET_CP(c_p, I+Size+1); \
  588. SET_I((BeamInstr *) CallDest); \
  589. Dispatch();
  590. #define MoveCallLast(Src, Dest, CallDest, Deallocate) \
  591. (Dest) = (Src); \
  592. RESTORE_CP(E); \
  593. E = ADD_BYTE_OFFSET(E, (Deallocate)); \
  594. SET_I((BeamInstr *) CallDest); \
  595. Dispatch();
  596. #define MoveCallOnly(Src, Dest, CallDest) \
  597. (Dest) = (Src); \
  598. SET_I((BeamInstr *) CallDest); \
  599. Dispatch();
  600. #define MoveJump(Src) \
  601. r(0) = (Src); \
  602. SET_I((BeamInstr *) Arg(0)); \
  603. Goto(*I);
  604. #define GetList(Src, H, T) do { \
  605. Eterm* tmp_ptr = list_val(Src); \
  606. H = CAR(tmp_ptr); \
  607. T = CDR(tmp_ptr); } while (0)
  608. #define GetTupleElement(Src, Element, Dest) \
  609. do { \
  610. tmp_arg1 = (Eterm) COMPRESS_POINTER(((unsigned char *) tuple_val(Src)) + \
  611. (Element)); \
  612. (Dest) = (*(Eterm *) EXPAND_POINTER(tmp_arg1)); \
  613. } while (0)
  614. #define ExtractNextElement(Dest) \
  615. tmp_arg1 += sizeof(Eterm); \
  616. (Dest) = (* (Eterm *) (((unsigned char *) EXPAND_POINTER(tmp_arg1))))
  617. #define ExtractNextElement2(Dest) \
  618. do { \
  619. Eterm* ene_dstp = &(Dest); \
  620. ene_dstp[0] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[1]; \
  621. ene_dstp[1] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[2]; \
  622. tmp_arg1 += sizeof(Eterm) + sizeof(Eterm); \
  623. } while (0)
  624. #define ExtractNextElement3(Dest) \
  625. do { \
  626. Eterm* ene_dstp = &(Dest); \
  627. ene_dstp[0] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[1]; \
  628. ene_dstp[1] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[2]; \
  629. ene_dstp[2] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[3]; \
  630. tmp_arg1 += 3*sizeof(Eterm); \
  631. } while (0)
  632. #define ExtractNextElement4(Dest) \
  633. do { \
  634. Eterm* ene_dstp = &(Dest); \
  635. ene_dstp[0] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[1]; \
  636. ene_dstp[1] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[2]; \
  637. ene_dstp[2] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[3]; \
  638. ene_dstp[3] = ((Eterm *) EXPAND_POINTER(tmp_arg1))[4]; \
  639. tmp_arg1 += 4*sizeof(Eterm); \
  640. } while (0)
  641. #define ExtractElement(Element, Dest) \
  642. do { \
  643. tmp_arg1 += (Element); \
  644. (Dest) = (* (Eterm *) EXPAND_POINTER(tmp_arg1)); \
  645. } while (0)
  646. #define EqualImmed(X, Y, Action) if (X != Y) { Action; }
  647. #define NotEqualImmed(X, Y, Action) if (X == Y) { Action; }
  648. #define IsFloat(Src, Fail) if (is_not_float(Src)) { Fail; }
  649. #define IsInteger(Src, Fail) if (is_not_integer(Src)) { Fail; }
  650. #define IsNumber(X, Fail) if (is_not_integer(X) && is_not_float(X)) { Fail; }
  651. #define IsAtom(Src, Fail) if (is_not_atom(Src)) { Fail; }
  652. #define IsIntegerAllocate(Src, Need, Alive, Fail) \
  653. if (is_not_integer(Src)) { Fail; } \
  654. A(Need, Alive)
  655. #define IsNil(Src, Fail) if (is_not_nil(Src)) { Fail; }
  656. #define IsList(Src, Fail) if (is_not_list(Src) && is_not_nil(Src)) { Fail; }
  657. #define IsNonemptyList(Src, Fail) if (is_not_list(Src)) { Fail; }
  658. #define IsNonemptyListAllocate(Src, Need, Alive, Fail) \
  659. if (is_not_list(Src)) { Fail; } \
  660. A(Need, Alive)
  661. #define IsNonemptyListTestHeap(Src, Need, Alive, Fail) \
  662. if (is_not_list(Src)) { Fail; } \
  663. TestHeap(Need, Alive)
  664. #define IsTuple(X, Action) if (is_not_tuple(X)) Action
  665. #define IsArity(Pointer, Arity, Fail) \
  666. if (*(Eterm *) \
  667. EXPAND_POINTER(tmp_arg1 = (Eterm) \
  668. COMPRESS_POINTER(tuple_val(Pointer))) != (Arity)) \
  669. { \
  670. Fail; \
  671. }
  672. #define IsFunction(X, Action) \
  673. do { \
  674. if ( !(is_any_fun(X)) ) { \
  675. Action; \
  676. } \
  677. } while (0)
  678. #define IsFunction2(F, A, Action) \
  679. do { \
  680. if (is_function_2(c_p, F, A) != am_true ) {\
  681. Action; \
  682. } \
  683. } while (0)
  684. #define IsTupleOfArity(Src, Arity, Fail) \
  685. do { \
  686. if (is_not_tuple(Src) || \
  687. *(Eterm *) \
  688. EXPAND_POINTER(tmp_arg1 = \
  689. (Eterm) COMPRESS_POINTER(tuple_val(Src))) != Arity) { \
  690. Fail; \
  691. } \
  692. } while (0)
  693. #define IsBoolean(X, Fail) if ((X) != am_true && (X) != am_false) { Fail; }
  694. #define IsBinary(Src, Fail) \
  695. if (is_not_binary(Src) || binary_bitsize(Src) != 0) { Fail; }
  696. #define IsBitstring(Src, Fail) \
  697. if (is_not_binary(Src)) { Fail; }
  698. #if defined(ARCH_64) && !HALFWORD_HEAP
  699. #define BsSafeMul(A, B, Fail, Target) \
  700. do { Uint64 _res = (A) * (B); \
  701. if (_res / B != A) { Fail; } \
  702. Target = _res; \
  703. } while (0)
  704. #else
  705. #define BsSafeMul(A, B, Fail, Target) \
  706. do { Uint64 _res = (Uint64)(A) * (Uint64)(B); \
  707. if ((_res >> (8*sizeof(Uint))) != 0) { Fail; } \
  708. Target = _res; \
  709. } while (0)
  710. #endif
  711. #define BsGetFieldSize(Bits, Unit, Fail, Target) \
  712. do { \
  713. Sint _signed_size; Uint _uint_size; \
  714. if (is_small(Bits)) { \
  715. _signed_size = signed_val(Bits); \
  716. if (_signed_size < 0) { Fail; } \
  717. _uint_size = (Uint) _signed_size; \
  718. } else { \
  719. if (!term_to_Uint(Bits, &temp_bits)) { Fail; } \
  720. _uint_size = temp_bits; \
  721. } \
  722. BsSafeMul(_uint_size, Unit, Fail, Target); \
  723. } while (0)
  724. #define BsGetUncheckedFieldSize(Bits, Unit, Fail, Target) \
  725. do { \
  726. Sint _signed_size; Uint _uint_size; \
  727. if (is_small(Bits)) { \
  728. _signed_size = signed_val(Bits); \
  729. if (_signed_size < 0) { Fail; } \
  730. _uint_size = (Uint) _signed_size; \
  731. } else { \
  732. if (!term_to_Uint(Bits, &temp_bits)) { Fail; } \
  733. _uint_size = (Uint) temp_bits; \
  734. } \
  735. Target = _uint_size * Unit; \
  736. } while (0)
  737. #define BsGetFloat2(Ms, Live, Sz, Flags, Dst, Store, Fail) \
  738. do { \
  739. ErlBinMatchBuffer *_mb; \
  740. Eterm _result; Sint _size; \
  741. if (!is_small(Sz) || (_size = unsigned_val(Sz)) > 64) { Fail; } \
  742. _size *= ((Flags) >> 3); \
  743. TestHeap(FLOAT_SIZE_OBJECT, Live); \
  744. _mb = ms_matchbuffer(Ms); \
  745. LIGHT_SWAPOUT; \
  746. _result = erts_bs_get_float_2(c_p, _size, (Flags), _mb); \
  747. LIGHT_SWAPIN; \
  748. HEAP_SPACE_VERIFIED(0); \
  749. if (is_non_value(_result)) { Fail; } \
  750. else { Store(_result, Dst); } \
  751. } while (0)
  752. #define BsGetBinaryImm_2(Ms, Live, Sz, Flags, Dst, Store, Fail) \
  753. do { \
  754. ErlBinMatchBuffer *_mb; \
  755. Eterm _result; \
  756. TestHeap(heap_bin_size(ERL_ONHEAP_BIN_LIMIT), Live); \
  757. _mb = ms_matchbuffer(Ms); \
  758. LIGHT_SWAPOUT; \
  759. _result = erts_bs_get_binary_2(c_p, (Sz), (Flags), _mb); \
  760. LIGHT_SWAPIN; \
  761. HEAP_SPACE_VERIFIED(0); \
  762. if (is_non_value(_result)) { Fail; } \
  763. else { Store(_result, Dst); } \
  764. } while (0)
  765. #define BsGetBinary_2(Ms, Live, Sz, Flags, Dst, Store, Fail) \
  766. do { \
  767. ErlBinMatchBuffer *_mb; \
  768. Eterm _result; Uint _size; \
  769. BsGetFieldSize(Sz, ((Flags) >> 3), Fail, _size); \
  770. TestHeap(ERL_SUB_BIN_SIZE, Live); \
  771. _mb = ms_matchbuffer(Ms); \
  772. LIGHT_SWAPOUT; \
  773. _result = erts_bs_get_binary_2(c_p, _size, (Flags), _mb); \
  774. LIGHT_SWAPIN; \
  775. HEAP_SPACE_VERIFIED(0); \
  776. if (is_non_value(_result)) { Fail; } \
  777. else { Store(_result, Dst); } \
  778. } while (0)
  779. #define BsGetBinaryAll_2(Ms, Live, Unit, Dst, Store, Fail) \
  780. do { \
  781. ErlBinMatchBuffer *_mb; \
  782. Eterm _result; \
  783. TestHeap(ERL_SUB_BIN_SIZE, Live); \
  784. _mb = ms_matchbuffer(Ms); \
  785. if (((_mb->size - _mb->offset) % Unit) == 0) { \
  786. LIGHT_SWAPOUT; \
  787. _result = erts_bs_get_binary_all_2(c_p, _mb); \
  788. LIGHT_SWAPIN; \
  789. HEAP_SPACE_VERIFIED(0); \
  790. ASSERT(is_value(_result)); \
  791. Store(_result, Dst); \
  792. } else { \
  793. HEAP_SPACE_VERIFIED(0); \
  794. Fail; } \
  795. } while (0)
  796. #define BsSkipBits2(Ms, Bits, Unit, Fail) \
  797. do { \
  798. ErlBinMatchBuffer *_mb; \
  799. size_t new_offset; \
  800. Uint _size; \
  801. _mb = ms_matchbuffer(Ms); \
  802. BsGetFieldSize(Bits, Unit, Fail, _size); \
  803. new_offset = _mb->offset + _size; \
  804. if (new_offset <= _mb->size) { _mb->offset = new_offset; } \
  805. else { Fail; } \
  806. } while (0)
  807. #define BsSkipBitsAll2(Ms, Unit, Fail) \
  808. do { \
  809. ErlBinMatchBuffer *_mb; \
  810. _mb = ms_matchbuffer(Ms); \
  811. if (((_mb->size - _mb->offset) % Unit) == 0) {_mb->offset = _mb->size; } \
  812. else { Fail; } \
  813. } while (0)
  814. #define BsSkipBitsImm2(Ms, Bits, Fail) \
  815. do { \
  816. ErlBinMatchBuffer *_mb; \
  817. size_t new_offset; \
  818. _mb = ms_matchbuffer(Ms); \
  819. new_offset = _mb->offset + (Bits); \
  820. if (new_offset <= _mb->size) { _mb->offset = new_offset; } \
  821. else { Fail; } \
  822. } while (0)
  823. #define NewBsPutIntegerImm(Sz, Flags, Src) \
  824. do { \
  825. if (!erts_new_bs_put_integer(ERL_BITS_ARGS_3((Src), (Sz), (Flags)))) { goto badarg; } \
  826. } while (0)
  827. #define NewBsPutInteger(Sz, Flags, Src) \
  828. do { \
  829. Sint _size; \
  830. BsGetUncheckedFieldSize(Sz, ((Flags) >> 3), goto badarg, _size); \
  831. if (!erts_new_bs_put_integer(ERL_BITS_ARGS_3((Src), _size, (Flags)))) \
  832. { goto badarg; } \
  833. } while (0)
  834. #define NewBsPutFloatImm(Sz, Flags, Src) \
  835. do { \
  836. if (!erts_new_bs_put_float(c_p, (Src), (Sz), (Flags))) { goto badarg; } \
  837. } while (0)
  838. #define NewBsPutFloat(Sz, Flags, Src) \
  839. do { \
  840. Sint _size; \
  841. BsGetUncheckedFieldSize(Sz, ((Flags) >> 3), goto badarg, _size); \
  842. if (!erts_new_bs_put_float(c_p, (Src), _size, (Flags))) { goto badarg; } \
  843. } while (0)
  844. #define NewBsPutBinary(Sz, Flags, Src) \
  845. do { \
  846. Sint _size; \
  847. BsGetUncheckedFieldSize(Sz, ((Flags) >> 3), goto badarg, _size); \
  848. if (!erts_new_bs_put_binary(ERL_BITS_ARGS_2((Src), _size))) { goto badarg; } \
  849. } while (0)
  850. #define NewBsPutBinaryImm(Sz, Src) \
  851. do { \
  852. if (!erts_new_bs_put_binary(ERL_BITS_ARGS_2((Src), (Sz)))) { goto badarg; } \
  853. } while (0)
  854. #define NewBsPutBinaryAll(Src, Unit) \
  855. do { \
  856. if (!erts_new_bs_put_binary_all(ERL_BITS_ARGS_2((Src), (Unit)))) { goto badarg; } \
  857. } while (0)
  858. #define IsPort(Src, Fail) if (is_not_port(Src)) { Fail; }
  859. #define IsPid(Src, Fail) if (is_not_pid(Src)) { Fail; }
  860. #define IsRef(Src, Fail) if (is_not_ref(Src)) { Fail; }
  861. /*
  862. * process_main() is already huge, so we want to avoid inlining
  863. * into it. Especially functions that are seldom used.
  864. */
  865. #ifdef __GNUC__
  866. # define NOINLINE __attribute__((__noinline__))
  867. #else
  868. # define NOINLINE
  869. #endif
  870. /*
  871. * The following functions are called directly by process_main().
  872. * Don't inline them.
  873. */
  874. static BifFunction translate_gc_bif(void* gcf) NOINLINE;
  875. static BeamInstr* handle_error(Process* c_p, BeamInstr* pc,
  876. Eterm* reg, BifFunction bf) NOINLINE;
  877. static BeamInstr* call_error_handler(Process* p, BeamInstr* ip,
  878. Eterm* reg, Eterm func) NOINLINE;
  879. static BeamInstr* fixed_apply(Process* p, Eterm* reg, Uint arity) NOINLINE;
  880. static BeamInstr* apply(Process* p, Eterm module, Eterm function,
  881. Eterm args, Eterm* reg) NOINLINE;
  882. static int hibernate(Process* c_p, Eterm module, Eterm function,
  883. Eterm args, Eterm* reg) NOINLINE;
  884. static BeamInstr* call_fun(Process* p, int arity,
  885. Eterm* reg, Eterm args) NOINLINE;
  886. static BeamInstr* apply_fun(Process* p, Eterm fun,
  887. Eterm args, Eterm* reg) NOINLINE;
  888. static Eterm new_fun(Process* p, Eterm* reg,
  889. ErlFunEntry* fe, int num_free) NOINLINE;
  890. /*
  891. * Functions not directly called by process_main(). OK to inline.
  892. */
  893. static BeamInstr* next_catch(Process* c_p, Eterm *reg);
  894. static void terminate_proc(Process* c_p, Eterm Value);
  895. static Eterm add_stacktrace(Process* c_p, Eterm Value, Eterm exc);
  896. static void save_stacktrace(Process* c_p, BeamInstr* pc, Eterm* reg,
  897. BifFunction bf, Eterm args);
  898. static struct StackTrace * get_trace_from_exc(Eterm exc);
  899. static Eterm make_arglist(Process* c_p, Eterm* reg, int a);
  900. #if defined(VXWORKS)
  901. static int init_done;
  902. #endif
  903. void
  904. init_emulator(void)
  905. {
  906. #if defined(VXWORKS)
  907. init_done = 0;
  908. #endif
  909. process_main();
  910. }
  911. /*
  912. * On certain platforms, make sure that the main variables really are placed
  913. * in registers.
  914. */
  915. #if defined(__GNUC__) && defined(sparc) && !defined(DEBUG)
  916. # define REG_x0 asm("%l0")
  917. # define REG_xregs asm("%l1")
  918. # define REG_htop asm("%l2")
  919. # define REG_stop asm("%l3")
  920. # define REG_I asm("%l4")
  921. # define REG_fcalls asm("%l5")
  922. # define REG_tmp_arg1 asm("%l6")
  923. # define REG_tmp_arg2 asm("%l7")
  924. #else
  925. # define REG_x0
  926. # define REG_xregs
  927. # define REG_htop
  928. # define REG_stop
  929. # define REG_I
  930. # define REG_fcalls
  931. # define REG_tmp_arg1
  932. # define REG_tmp_arg2
  933. #endif
  934. /*
  935. * process_main() is called twice:
  936. * The first call performs some initialisation, including exporting
  937. * the instructions' C labels to the loader.
  938. * The second call starts execution of BEAM code. This call never returns.
  939. */
  940. void process_main(void)
  941. {
  942. #if !defined(VXWORKS)
  943. static int init_done = 0;
  944. #endif
  945. Process* c_p = NULL;
  946. int reds_used;
  947. #ifdef DEBUG
  948. Eterm pid;
  949. #endif
  950. /*
  951. * X register zero; also called r(0)
  952. */
  953. register Eterm x0 REG_x0 = NIL;
  954. /* Pointer to X registers: x(1)..x(N); reg[0] is used when doing GC,
  955. * in all other cases x0 is used.
  956. */
  957. register Eterm* reg REG_xregs = NULL;
  958. /*
  959. * Top of heap (next free location); grows upwards.
  960. */
  961. register Eterm* HTOP REG_htop = NULL;
  962. #ifdef HYBRID
  963. Eterm *g_htop;
  964. Eterm *g_hend;
  965. #endif
  966. /* Stack pointer. Grows downwards; points
  967. * to last item pushed (normally a saved
  968. * continuation pointer).
  969. */
  970. register Eterm* E REG_stop = NULL;
  971. /*
  972. * Pointer to next threaded instruction.
  973. */
  974. register BeamInstr *I REG_I = NULL;
  975. /* Number of reductions left. This function
  976. * returns to the scheduler when FCALLS reaches zero.
  977. */
  978. register Sint FCALLS REG_fcalls = 0;
  979. /*
  980. * Temporaries used for picking up arguments for instructions.
  981. */
  982. register Eterm tmp_arg1 REG_tmp_arg1 = NIL;
  983. register Eterm tmp_arg2 REG_tmp_arg2 = NIL;
  984. #if HEAP_ON_C_STACK
  985. Eterm tmp_big[2]; /* Temporary buffer for small bignums if HEAP_ON_C_STACK. */
  986. #else
  987. Eterm *tmp_big; /* Temporary buffer for small bignums if !HEAP_ON_C_STACK. */
  988. #endif
  989. #ifndef ERTS_SMP
  990. #if !HALFWORD_HEAP
  991. static Eterm save_reg[ERTS_X_REGS_ALLOCATED];
  992. /* X registers -- not used directly, but
  993. * through 'reg', because using it directly
  994. * needs two instructions on a SPARC,
  995. * while using it through reg needs only
  996. * one.
  997. */
  998. #endif
  999. /*
  1000. * Floating point registers.
  1001. */
  1002. static FloatDef freg[MAX_REG];
  1003. #else
  1004. /* X regisers and floating point registers are located in
  1005. * scheduler specific data.
  1006. */
  1007. register FloatDef *freg;
  1008. #endif
  1009. /*
  1010. * For keeping the negative old value of 'reds' when call saving is active.
  1011. */
  1012. int neg_o_reds = 0;
  1013. Eterm (*arith_func)(Process* p, Eterm* reg, Uint live);
  1014. #ifndef NO_JUMP_TABLE
  1015. static void* opcodes[] = { DEFINE_OPCODES };
  1016. #ifdef ERTS_OPCODE_COUNTER_SUPPORT
  1017. static void* counting_opcodes[] = { DEFINE_COUNTING_OPCODES };
  1018. #endif
  1019. #else
  1020. int Go;
  1021. #endif
  1022. Uint temp_bits; /* Temporary used by BsSkipBits2 & BsGetInteger2 */
  1023. Eterm pt_arity; /* Used by do_put_tuple */
  1024. ERL_BITS_DECLARE_STATEP; /* Has to be last declaration */
  1025. /*
  1026. * Note: In this function, we attempt to place rarely executed code towards
  1027. * the end of the function, in the hope that the cache hit rate will be better.
  1028. * The initialization code is only run once, so it is at the very end.
  1029. *
  1030. * Note: c_p->arity must be set to reflect the number of useful terms in
  1031. * c_p->arg_reg before calling the scheduler.
  1032. */
  1033. if (!init_done) {
  1034. init_done = 1;
  1035. goto init_emulator;
  1036. }
  1037. #ifndef ERTS_SMP
  1038. #if !HALFWORD_HEAP
  1039. reg = save_reg; /* XXX: probably wastes a register on x86 */
  1040. #else
  1041. /* Registers need to be heap allocated (correct memory range) for tracing to work */
  1042. reg = erts_alloc(ERTS_ALC_T_BEAM_REGISTER, ERTS_X_REGS_ALLOCATED * sizeof(Eterm));
  1043. #endif
  1044. #endif
  1045. c_p = NULL;
  1046. reds_used = 0;
  1047. goto do_schedule1;
  1048. do_schedule:
  1049. reds_used = REDS_IN(c_p) - FCALLS;
  1050. do_schedule1:
  1051. PROCESS_MAIN_CHK_LOCKS(c_p);
  1052. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  1053. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1054. c_p = schedule(c_p, reds_used);
  1055. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1056. #ifdef DEBUG
  1057. pid = c_p->id;
  1058. #endif
  1059. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  1060. PROCESS_MAIN_CHK_LOCKS(c_p);
  1061. #ifdef ERTS_SMP
  1062. reg = c_p->scheduler_data->save_reg;
  1063. freg = c_p->scheduler_data->freg;
  1064. #endif
  1065. #if !HEAP_ON_C_STACK
  1066. tmp_big = ERTS_PROC_GET_SCHDATA(c_p)->beam_emu_tmp_heap;
  1067. #endif
  1068. ERL_BITS_RELOAD_STATEP(c_p);
  1069. {
  1070. int reds;
  1071. Eterm* argp;
  1072. BeamInstr *next;
  1073. int i;
  1074. argp = c_p->arg_reg;
  1075. for (i = c_p->arity - 1; i > 0; i--) {
  1076. reg[i] = argp[i];
  1077. CHECK_TERM(reg[i]);
  1078. }
  1079. /*
  1080. * We put the original reduction count in the process structure, to reduce
  1081. * the code size (referencing a field in a struct through a pointer stored
  1082. * in a register gives smaller code than referencing a global variable).
  1083. */
  1084. SET_I(c_p->i);
  1085. reds = c_p->fcalls;
  1086. if (ERTS_PROC_GET_SAVED_CALLS_BUF(c_p)
  1087. && (c_p->trace_flags & F_SENSITIVE) == 0) {
  1088. neg_o_reds = -reds;
  1089. FCALLS = REDS_IN(c_p) = 0;
  1090. } else {
  1091. neg_o_reds = 0;
  1092. FCALLS = REDS_IN(c_p) = reds;
  1093. }
  1094. next = (BeamInstr *) *I;
  1095. r(0) = c_p->arg_reg[0];
  1096. #ifdef HARDDEBUG
  1097. if (c_p->arity > 0) {
  1098. CHECK_TERM(r(0));
  1099. }
  1100. #endif
  1101. SWAPIN;
  1102. ASSERT(VALID_INSTR(next));
  1103. Goto(next);
  1104. }
  1105. #if defined(DEBUG) || defined(NO_JUMP_TABLE)
  1106. emulator_loop:
  1107. #endif
  1108. #ifdef NO_JUMP_TABLE
  1109. switch (Go) {
  1110. #endif
  1111. #include "beam_hot.h"
  1112. #define STORE_ARITH_RESULT(res) StoreBifResult(2, (res));
  1113. #define ARITH_FUNC(name) erts_gc_##name
  1114. {
  1115. Eterm increment_reg_val;
  1116. Eterm increment_val;
  1117. Uint live;
  1118. Eterm result;
  1119. OpCase(i_increment_yIId):
  1120. increment_reg_val = yb(Arg(0));
  1121. goto do_increment;
  1122. OpCase(i_increment_xIId):
  1123. increment_reg_val = xb(Arg(0));
  1124. goto do_increment;
  1125. OpCase(i_increment_rIId):
  1126. increment_reg_val = r(0);
  1127. I--;
  1128. do_increment:
  1129. increment_val = Arg(1);
  1130. if (is_small(increment_reg_val)) {
  1131. Sint i = signed_val(increment_reg_val) + increment_val;
  1132. ASSERT(MY_IS_SSMALL(i) == IS_SSMALL(i));
  1133. if (MY_IS_SSMALL(i)) {
  1134. result = make_small(i);
  1135. store_result:
  1136. StoreBifResult(3, result);
  1137. }
  1138. }
  1139. live = Arg(2);
  1140. SWAPOUT;
  1141. reg[0] = r(0);
  1142. reg[live] = increment_reg_val;
  1143. reg[live+1] = make_small(increment_val);
  1144. result = erts_gc_mixed_plus(c_p, reg, live);
  1145. r(0) = reg[0];
  1146. SWAPIN;
  1147. ERTS_HOLE_CHECK(c_p);
  1148. if (is_value(result)) {
  1149. goto store_result;
  1150. }
  1151. ASSERT(c_p->freason != BADMATCH || is_value(c_p->fvalue));
  1152. goto find_func_info;
  1153. }
  1154. OpCase(i_plus_jId):
  1155. {
  1156. Eterm result;
  1157. if (is_both_small(tmp_arg1, tmp_arg2)) {
  1158. Sint i = signed_val(tmp_arg1) + signed_val(tmp_arg2);
  1159. ASSERT(MY_IS_SSMALL(i) == IS_SSMALL(i));
  1160. if (MY_IS_SSMALL(i)) {
  1161. result = make_small(i);
  1162. STORE_ARITH_RESULT(result);
  1163. }
  1164. }
  1165. arith_func = ARITH_FUNC(mixed_plus);
  1166. goto do_big_arith2;
  1167. }
  1168. OpCase(i_minus_jId):
  1169. {
  1170. Eterm result;
  1171. if (is_both_small(tmp_arg1, tmp_arg2)) {
  1172. Sint i = signed_val(tmp_arg1) - signed_val(tmp_arg2);
  1173. ASSERT(MY_IS_SSMALL(i) == IS_SSMALL(i));
  1174. if (MY_IS_SSMALL(i)) {
  1175. result = make_small(i);
  1176. STORE_ARITH_RESULT(result);
  1177. }
  1178. }
  1179. arith_func = ARITH_FUNC(mixed_minus);
  1180. goto do_big_arith2;
  1181. }
  1182. OpCase(i_is_lt_f):
  1183. if (CMP_GE(tmp_arg1, tmp_arg2)) {
  1184. ClauseFail();
  1185. }
  1186. Next(1);
  1187. OpCase(i_is_ge_f):
  1188. if (CMP_LT(tmp_arg1, tmp_arg2)) {
  1189. ClauseFail();
  1190. }
  1191. Next(1);
  1192. OpCase(i_is_eq_f):
  1193. if (CMP_NE(tmp_arg1, tmp_arg2)) {
  1194. ClauseFail();
  1195. }
  1196. Next(1);
  1197. OpCase(i_is_ne_f):
  1198. if (CMP_EQ(tmp_arg1, tmp_arg2)) {
  1199. ClauseFail();
  1200. }
  1201. Next(1);
  1202. OpCase(i_is_eq_exact_f):
  1203. if (!EQ(tmp_arg1, tmp_arg2)) {
  1204. ClauseFail();
  1205. }
  1206. Next(1);
  1207. {
  1208. Eterm is_eq_exact_lit_val;
  1209. OpCase(i_is_eq_exact_literal_xfc):
  1210. is_eq_exact_lit_val = xb(Arg(0));
  1211. I++;
  1212. goto do_is_eq_exact_literal;
  1213. OpCase(i_is_eq_exact_literal_yfc):
  1214. is_eq_exact_lit_val = yb(Arg(0));
  1215. I++;
  1216. goto do_is_eq_exact_literal;
  1217. OpCase(i_is_eq_exact_literal_rfc):
  1218. is_eq_exact_lit_val = r(0);
  1219. do_is_eq_exact_literal:
  1220. if (!eq(Arg(1), is_eq_exact_lit_val)) {
  1221. ClauseFail();
  1222. }
  1223. Next(2);
  1224. }
  1225. {
  1226. Eterm is_ne_exact_lit_val;
  1227. OpCase(i_is_ne_exact_literal_xfc):
  1228. is_ne_exact_lit_val = xb(Arg(0));
  1229. I++;
  1230. goto do_is_ne_exact_literal;
  1231. OpCase(i_is_ne_exact_literal_yfc):
  1232. is_ne_exact_lit_val = yb(Arg(0));
  1233. I++;
  1234. goto do_is_ne_exact_literal;
  1235. OpCase(i_is_ne_exact_literal_rfc):
  1236. is_ne_exact_lit_val = r(0);
  1237. do_is_ne_exact_literal:
  1238. if (eq(Arg(1), is_ne_exact_lit_val)) {
  1239. ClauseFail();
  1240. }
  1241. Next(2);
  1242. }
  1243. OpCase(i_move_call_only_fcr): {
  1244. r(0) = Arg(1);
  1245. }
  1246. /* FALL THROUGH */
  1247. OpCase(i_call_only_f): {
  1248. SET_I((BeamInstr *) Arg(0));
  1249. Dispatch();
  1250. }
  1251. OpCase(i_move_call_last_fPcr): {
  1252. r(0) = Arg(2);
  1253. }
  1254. /* FALL THROUGH */
  1255. OpCase(i_call_last_fP): {
  1256. RESTORE_CP(E);
  1257. E = ADD_BYTE_OFFSET(E, Arg(1));
  1258. SET_I((BeamInstr *) Arg(0));
  1259. Dispatch();
  1260. }
  1261. OpCase(i_move_call_crf): {
  1262. r(0) = Arg(0);
  1263. I++;
  1264. }
  1265. /* FALL THROUGH */
  1266. OpCase(i_call_f): {
  1267. SET_CP(c_p, I+2);
  1268. SET_I((BeamInstr *) Arg(0));
  1269. Dispatch();
  1270. }
  1271. OpCase(i_move_call_ext_last_ePcr): {
  1272. r(0) = Arg(2);
  1273. }
  1274. /* FALL THROUGH */
  1275. OpCase(i_call_ext_last_eP):
  1276. RESTORE_CP(E);
  1277. E = ADD_BYTE_OFFSET(E, Arg(1));
  1278. /*
  1279. * Note: The pointer to the export entry is never NULL; if the module
  1280. * is not loaded, it points to code which will invoke the error handler
  1281. * (see lb_call_error_handler below).
  1282. */
  1283. Dispatchx();
  1284. OpCase(i_move_call_ext_cre): {
  1285. r(0) = Arg(0);
  1286. I++;
  1287. }
  1288. /* FALL THROUGH */
  1289. OpCase(i_call_ext_e):
  1290. SET_CP(c_p, I+2);
  1291. Dispatchx();
  1292. OpCase(i_move_call_ext_only_ecr): {
  1293. r(0) = Arg(1);
  1294. }
  1295. /* FALL THROUGH */
  1296. OpCase(i_call_ext_only_e):
  1297. Dispatchx();
  1298. OpCase(init_y): {
  1299. BeamInstr *next;
  1300. PreFetch(1, next);
  1301. make_blank(yb(Arg(0)));
  1302. NextPF(1, next);
  1303. }
  1304. OpCase(i_trim_I): {
  1305. BeamInstr *next;
  1306. Uint words;
  1307. Uint cp;
  1308. words = Arg(0);
  1309. cp = E[0];
  1310. PreFetch(1, next);
  1311. E += words;
  1312. E[0] = cp;
  1313. NextPF(1, next);
  1314. }
  1315. OpCase(move_x1_c): {
  1316. x(1) = Arg(0);
  1317. Next(1);
  1318. }
  1319. OpCase(move_x2_c): {
  1320. x(2) = Arg(0);
  1321. Next(1);
  1322. }
  1323. OpCase(return): {
  1324. SET_I(c_p->cp);
  1325. /*
  1326. * We must clear the CP to make sure that a stale value do not
  1327. * create a false module dependcy preventing code upgrading.
  1328. * It also means that we can use the CP in stack backtraces.
  1329. */
  1330. c_p->cp = 0;
  1331. CHECK_TERM(r(0));
  1332. HEAP_SPACE_VERIFIED(0);
  1333. Goto(*I);
  1334. }
  1335. /*
  1336. * Send is almost a standard call-BIF with two arguments, except for:
  1337. * 1) It cannot be traced.
  1338. * 2) There is no pointer to the send_2 function stored in
  1339. * the instruction.
  1340. */
  1341. OpCase(send): {
  1342. BeamInstr *next;
  1343. Eterm result;
  1344. PRE_BIF_SWAPOUT(c_p);
  1345. c_p->fcalls = FCALLS - 1;
  1346. result = send_2(c_p, r(0), x(1));
  1347. PreFetch(0, next);
  1348. POST_BIF_GC_SWAPIN(c_p, result, reg, 2);
  1349. FCALLS = c_p->fcalls;
  1350. if (is_value(result)) {
  1351. r(0) = result;
  1352. CHECK_TERM(r(0));
  1353. NextPF(0, next);
  1354. } else if (c_p->freason == TRAP) {
  1355. SET_CP(c_p, I+1);
  1356. SET_I(*((BeamInstr **) (BeamInstr) ((c_p)->def_arg_reg + 3)));
  1357. SWAPIN;
  1358. r(0) = c_p->def_arg_reg[0];
  1359. x(1) = c_p->def_arg_reg[1];
  1360. Dispatch();
  1361. }
  1362. goto find_func_info;
  1363. }
  1364. {
  1365. Eterm element_index;
  1366. Eterm element_tuple;
  1367. OpCase(i_element_xjsd):
  1368. element_tuple = xb(Arg(0));
  1369. I++;
  1370. goto do_element;
  1371. OpCase(i_element_yjsd):
  1372. element_tuple = yb(Arg(0));
  1373. I++;
  1374. goto do_element;
  1375. OpCase(i_element_rjsd):
  1376. element_tuple = r(0);
  1377. /* Fall through */
  1378. do_element:
  1379. GetArg1(1, element_index);
  1380. if (is_small(element_index) && is_tuple(element_tuple)) {
  1381. Eterm* tp = tuple_val(element_tuple);
  1382. if ((signed_val(element_index) >= 1) &&
  1383. (signed_val(element_index) <= arityval(*tp))) {
  1384. Eterm result = tp[signed_val(element_index)];
  1385. StoreBifResult(2, result);
  1386. }
  1387. }
  1388. }
  1389. /* Fall through */
  1390. OpCase(badarg_j):
  1391. badarg:
  1392. c_p->freason = BADARG;
  1393. goto lb_Cl_error;
  1394. {
  1395. Eterm fast_element_tuple;
  1396. OpCase(i_fast_element_rjId):
  1397. fast_element_tuple = r(0);
  1398. do_fast_element:
  1399. if (is_tuple(fast_element_tuple)) {
  1400. Eterm* tp = tuple_val(fast_element_tuple);
  1401. Eterm pos = Arg(1); /* Untagged integer >= 1 */
  1402. if (pos <= arityval(*tp)) {
  1403. Eterm result = tp[pos];
  1404. StoreBifResult(2, result);
  1405. }
  1406. }
  1407. goto badarg;
  1408. OpCase(i_fast_element_xjId):
  1409. fast_element_tuple = xb(Arg(0));
  1410. I++;
  1411. goto do_fast_element;
  1412. OpCase(i_fast_element_yjId):
  1413. fast_element_tuple = yb(Arg(0));
  1414. I++;
  1415. goto do_fast_element;
  1416. }
  1417. OpCase(catch_yf):
  1418. c_p->catches++;
  1419. yb(Arg(0)) = Arg(1);
  1420. Next(2);
  1421. OpCase(catch_end_y): {
  1422. c_p->catches--;
  1423. make_blank(yb(Arg(0)));
  1424. if (is_non_value(r(0))) {
  1425. if (x(1) == am_throw) {
  1426. r(0) = x(2);
  1427. } else {
  1428. if (x(1) == am_error) {
  1429. SWAPOUT;
  1430. x(2) = add_stacktrace(c_p, x(2), x(3));
  1431. SWAPIN;
  1432. }
  1433. /* only x(2) is included in the rootset here */
  1434. if (E - HTOP < 3 || c_p->mbuf) { /* Force GC in case add_stacktrace()
  1435. * created heap fragments */
  1436. SWAPOUT;
  1437. PROCESS_MAIN_CHK_LOCKS(c_p);
  1438. FCALLS -= erts_garbage_collect(c_p, 3, reg+2, 1);
  1439. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1440. PROCESS_MAIN_CHK_LOCKS(c_p);
  1441. SWAPIN;
  1442. }
  1443. r(0) = TUPLE2(HTOP, am_EXIT, x(2));
  1444. HTOP += 3;
  1445. }
  1446. }
  1447. CHECK_TERM(r(0));
  1448. Next(1);
  1449. }
  1450. OpCase(try_end_y): {
  1451. c_p->catches--;
  1452. make_blank(yb(Arg(0)));
  1453. if (is_non_value(r(0))) {
  1454. r(0) = x(1);
  1455. x(1) = x(2);
  1456. x(2) = x(3);
  1457. }
  1458. Next(1);
  1459. }
  1460. /*
  1461. * Skeleton for receive statement:
  1462. *
  1463. * recv_mark L1 Optional
  1464. * call make_ref/monitor Optional
  1465. * ...
  1466. * recv_set L1 Optional
  1467. * L1: <-------------------+
  1468. * <-----------+ |
  1469. * | |
  1470. * loop_rec L2 ------+---+ |
  1471. * ... | | |
  1472. * remove_message | | |
  1473. * jump L3 | | |
  1474. * ... | | |
  1475. * loop_rec_end L1 --+ | |
  1476. * L2: <---------------+ |
  1477. * wait L1 -----------------+ or wait_timeout
  1478. * timeout
  1479. *
  1480. * L3: Code after receive...
  1481. *
  1482. *
  1483. */
  1484. OpCase(recv_mark_f): {
  1485. /*
  1486. * Save the current position in message buffer and the
  1487. * the label for the loop_rec/2 instruction for the
  1488. * the receive statement.
  1489. */
  1490. c_p->msg.mark = (BeamInstr *) Arg(0);
  1491. c_p->msg.saved_last = c_p->msg.last;
  1492. Next(1);
  1493. }
  1494. OpCase(i_recv_set): {
  1495. /*
  1496. * If the mark is valid (points to the loop_rec/2
  1497. * instruction that follows), we know that the saved
  1498. * position points to the first message that could
  1499. * possibly be matched out.
  1500. *
  1501. * If the mark is invalid, we do nothing, meaning that
  1502. * we will look through all messages in the message queue.
  1503. */
  1504. if (c_p->msg.mark == (BeamInstr *) (I+1)) {
  1505. c_p->msg.save = c_p->msg.saved_last;
  1506. }
  1507. I++;
  1508. /* Fall through to the loop_rec/2 instruction */
  1509. }
  1510. /*
  1511. * Pick up the next message and place it in x(0).
  1512. * If no message, jump to a wait or wait_timeout instruction.
  1513. */
  1514. OpCase(i_loop_rec_fr):
  1515. {
  1516. BeamInstr *next;
  1517. ErlMessage* msgp;
  1518. loop_rec__:
  1519. PROCESS_MAIN_CHK_LOCKS(c_p);
  1520. msgp = PEEK_MESSAGE(c_p);
  1521. if (!msgp) {
  1522. #ifdef ERTS_SMP
  1523. erts_smp_proc_lock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1524. /* Make sure messages wont pass exit signals... */
  1525. if (ERTS_PROC_PENDING_EXIT(c_p)) {
  1526. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1527. SWAPOUT;
  1528. goto do_schedule; /* Will be rescheduled for exit */
  1529. }
  1530. ERTS_SMP_MSGQ_MV_INQ2PRIVQ(c_p);
  1531. msgp = PEEK_MESSAGE(c_p);
  1532. if (msgp)
  1533. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1534. else {
  1535. #endif
  1536. SET_I((BeamInstr *) Arg(0));
  1537. Goto(*I); /* Jump to a wait or wait_timeout instruction */
  1538. #ifdef ERTS_SMP
  1539. }
  1540. #endif
  1541. }
  1542. ErtsMoveMsgAttachmentIntoProc(msgp, c_p, E, HTOP, FCALLS,
  1543. {
  1544. SWAPOUT;
  1545. reg[0] = r(0);
  1546. PROCESS_MAIN_CHK_LOCKS(c_p);
  1547. },
  1548. {
  1549. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1550. PROCESS_MAIN_CHK_LOCKS(c_p);
  1551. r(0) = reg[0];
  1552. SWAPIN;
  1553. });
  1554. if (is_non_value(ERL_MESSAGE_TERM(msgp))) {
  1555. /*
  1556. * A corrupt distribution message that we weren't able to decode;
  1557. * remove it...
  1558. */
  1559. ASSERT(!msgp->data.attached);
  1560. UNLINK_MESSAGE(c_p, msgp);
  1561. free_message(msgp);
  1562. goto loop_rec__;
  1563. }
  1564. PreFetch(1, next);
  1565. r(0) = ERL_MESSAGE_TERM(msgp);
  1566. NextPF(1, next);
  1567. }
  1568. /*
  1569. * Remove a (matched) message from the message queue.
  1570. */
  1571. OpCase(remove_message): {
  1572. BeamInstr *next;
  1573. ErlMessage* msgp;
  1574. PROCESS_MAIN_CHK_LOCKS(c_p);
  1575. PreFetch(0, next);
  1576. msgp = PEEK_MESSAGE(c_p);
  1577. if (ERTS_PROC_GET_SAVED_CALLS_BUF(c_p)) {
  1578. save_calls(c_p, &exp_receive);
  1579. }
  1580. if (ERL_MESSAGE_TOKEN(msgp) == NIL) {
  1581. SEQ_TRACE_TOKEN(c_p) = NIL;
  1582. } else if (ERL_MESSAGE_TOKEN(msgp) != am_undefined) {
  1583. Eterm msg;
  1584. SEQ_TRACE_TOKEN(c_p) = ERL_MESSAGE_TOKEN(msgp);
  1585. ASSERT(is_tuple(SEQ_TRACE_TOKEN(c_p)));
  1586. ASSERT(SEQ_TRACE_TOKEN_ARITY(c_p) == 5);
  1587. ASSERT(is_small(SEQ_TRACE_TOKEN_SERIAL(c_p)));
  1588. ASSERT(is_small(SEQ_TRACE_TOKEN_LASTCNT(c_p)));
  1589. ASSERT(is_small(SEQ_TRACE_TOKEN_FLAGS(c_p)));
  1590. ASSERT(is_pid(SEQ_TRACE_TOKEN_SENDER(c_p)));
  1591. c_p->seq_trace_lastcnt = unsigned_val(SEQ_TRACE_TOKEN_SERIAL(c_p));
  1592. if (c_p->seq_trace_clock < unsigned_val(SEQ_TRACE_TOKEN_SERIAL(c_p))) {
  1593. c_p->seq_trace_clock = unsigned_val(SEQ_TRACE_TOKEN_SERIAL(c_p));
  1594. }
  1595. msg = ERL_MESSAGE_TERM(msgp);
  1596. seq_trace_output(SEQ_TRACE_TOKEN(c_p), msg, SEQ_TRACE_RECEIVE,
  1597. c_p->id, c_p);
  1598. }
  1599. UNLINK_MESSAGE(c_p, msgp);
  1600. JOIN_MESSAGE(c_p);
  1601. CANCEL_TIMER(c_p);
  1602. free_message(msgp);
  1603. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1604. PROCESS_MAIN_CHK_LOCKS(c_p);
  1605. NextPF(0, next);
  1606. }
  1607. /*
  1608. * Advance the save pointer to the next message (the current
  1609. * message didn't match), then jump to the loop_rec instruction.
  1610. */
  1611. OpCase(loop_rec_end_f): {
  1612. SET_I((BeamInstr *) Arg(0));
  1613. SAVE_MESSAGE(c_p);
  1614. goto loop_rec__;
  1615. }
  1616. /*
  1617. * Prepare to wait for a message or a timeout, whichever occurs first.
  1618. *
  1619. * Note: In order to keep the compatibility between 32 and 64 bits
  1620. * emulators, only timeout values that can be represented in 32 bits
  1621. * (unsigned) or less are allowed.
  1622. */
  1623. OpCase(i_wait_timeout_fs): {
  1624. erts_smp_proc_lock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1625. /* Fall through */
  1626. }
  1627. OpCase(i_wait_timeout_locked_fs): {
  1628. Eterm timeout_value;
  1629. /*
  1630. * If we have already set the timer, we must NOT set it again. Therefore,
  1631. * we must test the F_INSLPQUEUE flag as well as the F_TIMO flag.
  1632. */
  1633. if (c_p->flags & (F_INSLPQUEUE | F_TIMO)) {
  1634. goto wait2;
  1635. }
  1636. GetArg1(1, timeout_value);
  1637. if (timeout_value != make_small(0)) {
  1638. #if !defined(ARCH_64) || HALFWORD_HEAP
  1639. Uint time_val;
  1640. #endif
  1641. if (is_small(timeout_value) && signed_val(timeout_value) > 0 &&
  1642. #if defined(ARCH_64) && !HALFWORD_HEAP
  1643. ((unsigned_val(timeout_value) >> 32) == 0)
  1644. #else
  1645. 1
  1646. #endif
  1647. ) {
  1648. /*
  1649. * The timer routiner will set c_p->i to the value in
  1650. * c_p->def_arg_reg[0]. Note that it is safe to use this
  1651. * location because there are no living x registers in
  1652. * a receive statement.
  1653. * Note that for the halfword emulator, the two first elements
  1654. * of the array are used.
  1655. */
  1656. *((BeamInstr **) (UWord) c_p->def_arg_reg) = I+3;
  1657. set_timer(c_p, unsigned_val(timeout_value));
  1658. } else if (timeout_value == am_infinity) {
  1659. c_p->flags |= F_TIMO;
  1660. #if !defined(ARCH_64) || HALFWORD_HEAP
  1661. } else if (term_to_Uint(timeout_value, &time_val)) {
  1662. *((BeamInstr **) (UWord) c_p->def_arg_reg) = I+3;
  1663. set_timer(c_p, time_val);
  1664. #endif
  1665. } else { /* Wrong time */
  1666. OpCase(i_wait_error_locked): {
  1667. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1668. /* Fall through */
  1669. }
  1670. OpCase(i_wait_error): {
  1671. c_p->freason = EXC_TIMEOUT_VALUE;
  1672. goto find_func_info;
  1673. }
  1674. }
  1675. /*
  1676. * Prepare to wait indefinitely for a new message to arrive
  1677. * (or the time set above if falling through from above).
  1678. *
  1679. * When a new message arrives, control will be transferred
  1680. * the loop_rec instruction (at label L1). In case of
  1681. * of timeout, control will be transferred to the timeout
  1682. * instruction following the wait_timeout instruction.
  1683. */
  1684. OpCase(wait_locked_f):
  1685. OpCase(wait_f):
  1686. wait2: {
  1687. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  1688. c_p->i = (BeamInstr *) Arg(0); /* L1 */
  1689. SWAPOUT;
  1690. c_p->arity = 0;
  1691. c_p->status = P_WAITING;
  1692. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1693. c_p->current = NULL;
  1694. goto do_schedule;
  1695. }
  1696. OpCase(wait_unlocked_f): {
  1697. erts_smp_proc_lock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1698. goto wait2;
  1699. }
  1700. }
  1701. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1702. Next(2);
  1703. }
  1704. OpCase(i_wait_timeout_fI): {
  1705. erts_smp_proc_lock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1706. }
  1707. OpCase(i_wait_timeout_locked_fI):
  1708. {
  1709. /*
  1710. * If we have already set the timer, we must NOT set it again. Therefore,
  1711. * we must test the F_INSLPQUEUE flag as well as the F_TIMO flag.
  1712. */
  1713. if ((c_p->flags & (F_INSLPQUEUE | F_TIMO)) == 0) {
  1714. *((BeamInstr **) (UWord) c_p->def_arg_reg) = I+3;
  1715. set_timer(c_p, Arg(1));
  1716. }
  1717. goto wait2;
  1718. }
  1719. /*
  1720. * A timeout has occurred. Reset the save pointer so that the next
  1721. * receive statement will examine the first message first.
  1722. */
  1723. OpCase(timeout_locked): {
  1724. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_MSG_RECEIVE);
  1725. }
  1726. OpCase(timeout): {
  1727. BeamInstr *next;
  1728. PreFetch(0, next);
  1729. if (IS_TRACED_FL(c_p, F_TRACE_RECEIVE)) {
  1730. trace_receive(c_p, am_timeout);
  1731. }
  1732. if (ERTS_PROC_GET_SAVED_CALLS_BUF(c_p)) {
  1733. save_calls(c_p, &exp_timeout);
  1734. }
  1735. c_p->flags &= ~F_TIMO;
  1736. JOIN_MESSAGE(c_p);
  1737. NextPF(0, next);
  1738. }
  1739. {
  1740. Eterm select_val2;
  1741. OpCase(i_select_tuple_arity2_yfAfAf):
  1742. select_val2 = yb(Arg(0));
  1743. goto do_select_tuple_arity2;
  1744. OpCase(i_select_tuple_arity2_xfAfAf):
  1745. select_val2 = xb(Arg(0));
  1746. goto do_select_tuple_arity2;
  1747. OpCase(i_select_tuple_arity2_rfAfAf):
  1748. select_val2 = r(0);
  1749. I--;
  1750. do_select_tuple_arity2:
  1751. if (is_not_tuple(select_val2)) {
  1752. goto select_val2_fail;
  1753. }
  1754. select_val2 = *tuple_val(select_val2);
  1755. goto do_select_val2;
  1756. OpCase(i_select_val2_yfcfcf):
  1757. select_val2 = yb(Arg(0));
  1758. goto do_select_val2;
  1759. OpCase(i_select_val2_xfcfcf):
  1760. select_val2 = xb(Arg(0));
  1761. goto do_select_val2;
  1762. OpCase(i_select_val2_rfcfcf):
  1763. select_val2 = r(0);
  1764. I--;
  1765. do_select_val2:
  1766. if (select_val2 == Arg(2)) {
  1767. I += 2;
  1768. } else if (select_val2 == Arg(4)) {
  1769. I += 4;
  1770. }
  1771. select_val2_fail:
  1772. SET_I((BeamInstr *) Arg(1));
  1773. Goto(*I);
  1774. }
  1775. {
  1776. Eterm select_val;
  1777. OpCase(i_select_tuple_arity_xfI):
  1778. select_val = xb(Arg(0));
  1779. goto do_select_tuple_arity;
  1780. OpCase(i_select_tuple_arity_yfI):
  1781. select_val = yb(Arg(0));
  1782. goto do_select_tuple_arity;
  1783. OpCase(i_select_tuple_arity_rfI):
  1784. select_val = r(0);
  1785. I--;
  1786. do_select_tuple_arity:
  1787. if (is_tuple(select_val)) {
  1788. select_val = *tuple_val(select_val);
  1789. goto do_binary_search;
  1790. }
  1791. SET_I((BeamInstr *) Arg(1));
  1792. Goto(*I);
  1793. OpCase(i_select_val_xfI):
  1794. select_val = xb(Arg(0));
  1795. goto do_binary_search;
  1796. OpCase(i_select_val_yfI):
  1797. select_val = yb(Arg(0));
  1798. goto do_binary_search;
  1799. OpCase(i_select_val_rfI):
  1800. select_val = r(0);
  1801. I--;
  1802. do_binary_search:
  1803. {
  1804. struct Pairs {
  1805. BeamInstr val;
  1806. BeamInstr* addr;
  1807. };
  1808. struct Pairs* low;
  1809. struct Pairs* high;
  1810. struct Pairs* mid;
  1811. int bdiff; /* int not long because the arrays aren't that large */
  1812. low = (struct Pairs *) &Arg(3);
  1813. high = low + Arg(2);
  1814. /* The pointer subtraction (high-low) below must produce
  1815. * a signed result, because high could be < low. That
  1816. * requires the compiler to insert quite a bit of code.
  1817. *
  1818. * However, high will be > low so the result will be
  1819. * positive. We can use that knowledge to optimise the
  1820. * entire sequence, from the initial comparison to the
  1821. * computation of mid.
  1822. *
  1823. * -- Mikael Pettersson, Acumem AB
  1824. *
  1825. * Original loop control code:
  1826. *
  1827. * while (low < high) {
  1828. * mid = low + (high-low) / 2;
  1829. *
  1830. */
  1831. while ((bdiff = (int)((char*)high - (char*)low)) > 0) {
  1832. unsigned int boffset = ((unsigned int)bdiff >> 1) & ~(sizeof(struct Pairs)-1);
  1833. mid = (struct Pairs*)((char*)low + boffset);
  1834. if (select_val < mid->val) {
  1835. high = mid;
  1836. } else if (select_val > mid->val) {
  1837. low = mid + 1;
  1838. } else {
  1839. SET_I(mid->addr);
  1840. Goto(*I);
  1841. }
  1842. }
  1843. SET_I((BeamInstr *) Arg(1));
  1844. Goto(*I);
  1845. }
  1846. }
  1847. {
  1848. Eterm jump_on_val_zero_index;
  1849. OpCase(i_jump_on_val_zero_yfI):
  1850. jump_on_val_zero_index = yb(Arg(0));
  1851. goto do_jump_on_val_zero_index;
  1852. OpCase(i_jump_on_val_zero_xfI):
  1853. jump_on_val_zero_index = xb(Arg(0));
  1854. goto do_jump_on_val_zero_index;
  1855. OpCase(i_jump_on_val_zero_rfI):
  1856. jump_on_val_zero_index = r(0);
  1857. I--;
  1858. do_jump_on_val_zero_index:
  1859. if (is_small(jump_on_val_zero_index)) {
  1860. jump_on_val_zero_index = signed_val(jump_on_val_zero_index);
  1861. if (jump_on_val_zero_index < Arg(2)) {
  1862. SET_I((BeamInstr *) (&Arg(3))[jump_on_val_zero_index]);
  1863. Goto(*I);
  1864. }
  1865. }
  1866. SET_I((BeamInstr *) Arg(1));
  1867. Goto(*I);
  1868. }
  1869. {
  1870. Eterm jump_on_val_index;
  1871. OpCase(i_jump_on_val_yfII):
  1872. jump_on_val_index = yb(Arg(0));
  1873. goto do_jump_on_val_index;
  1874. OpCase(i_jump_on_val_xfII):
  1875. jump_on_val_index = xb(Arg(0));
  1876. goto do_jump_on_val_index;
  1877. OpCase(i_jump_on_val_rfII):
  1878. jump_on_val_index = r(0);
  1879. I--;
  1880. do_jump_on_val_index:
  1881. if (is_small(jump_on_val_index)) {
  1882. jump_on_val_index = (Uint) (signed_val(jump_on_val_index) - Arg(3));
  1883. if (jump_on_val_index < Arg(2)) {
  1884. SET_I((BeamInstr *) (&Arg(4))[jump_on_val_index]);
  1885. Goto(*I);
  1886. }
  1887. }
  1888. SET_I((BeamInstr *) Arg(1));
  1889. Goto(*I);
  1890. }
  1891. do_put_tuple: {
  1892. Eterm* hp = HTOP;
  1893. *hp++ = make_arityval(pt_arity);
  1894. do {
  1895. Eterm term = *I++;
  1896. switch (term & _TAG_IMMED1_MASK) {
  1897. case (R_REG_DEF << _TAG_PRIMARY_SIZE) | TAG_PRIMARY_HEADER:
  1898. *hp++ = r(0);
  1899. break;
  1900. case (X_REG_DEF << _TAG_PRIMARY_SIZE) | TAG_PRIMARY_HEADER:
  1901. *hp++ = x(term >> _TAG_IMMED1_SIZE);
  1902. break;
  1903. case (Y_REG_DEF << _TAG_PRIMARY_SIZE) | TAG_PRIMARY_HEADER:
  1904. *hp++ = y(term >> _TAG_IMMED1_SIZE);
  1905. break;
  1906. default:
  1907. *hp++ = term;
  1908. break;
  1909. }
  1910. } while (--pt_arity != 0);
  1911. HTOP = hp;
  1912. Goto(*I);
  1913. }
  1914. /*
  1915. * All guards with zero arguments have special instructions:
  1916. * self/0
  1917. * node/0
  1918. *
  1919. * All other guard BIFs take one or two arguments.
  1920. */
  1921. /*
  1922. * Guard BIF in head. On failure, ignore the error and jump
  1923. * to the code for the next clause. We don't support tracing
  1924. * of guard BIFs.
  1925. */
  1926. OpCase(bif1_fbsd):
  1927. {
  1928. Eterm (*bf)(Process*, Eterm);
  1929. Eterm arg;
  1930. Eterm result;
  1931. GetArg1(2, arg);
  1932. bf = (BifFunction) Arg(1);
  1933. c_p->fcalls = FCALLS;
  1934. PROCESS_MAIN_CHK_LOCKS(c_p);
  1935. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  1936. result = (*bf)(c_p, arg);
  1937. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
  1938. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1939. PROCESS_MAIN_CHK_LOCKS(c_p);
  1940. ERTS_HOLE_CHECK(c_p);
  1941. FCALLS = c_p->fcalls;
  1942. if (is_value(result)) {
  1943. StoreBifResult(3, result);
  1944. }
  1945. SET_I((BeamInstr *) Arg(0));
  1946. Goto(*I);
  1947. }
  1948. /*
  1949. * Guard BIF in body. It can fail like any BIF. No trace support.
  1950. */
  1951. OpCase(bif1_body_bsd):
  1952. {
  1953. Eterm (*bf)(Process*, Eterm);
  1954. Eterm arg;
  1955. Eterm result;
  1956. GetArg1(1, arg);
  1957. bf = (BifFunction) Arg(0);
  1958. c_p->fcalls = FCALLS;
  1959. PROCESS_MAIN_CHK_LOCKS(c_p);
  1960. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  1961. result = (*bf)(c_p, arg);
  1962. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
  1963. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1964. PROCESS_MAIN_CHK_LOCKS(c_p);
  1965. ERTS_HOLE_CHECK(c_p);
  1966. FCALLS = c_p->fcalls;
  1967. if (is_value(result)) {
  1968. StoreBifResult(2, result);
  1969. }
  1970. reg[0] = arg;
  1971. SWAPOUT;
  1972. I = handle_error(c_p, I, reg, bf);
  1973. goto post_error_handling;
  1974. }
  1975. OpCase(i_gc_bif1_jIsId):
  1976. {
  1977. typedef Eterm (*GcBifFunction)(Process*, Eterm*, Uint);
  1978. GcBifFunction bf;
  1979. Eterm arg;
  1980. Eterm result;
  1981. Uint live = (Uint) Arg(3);
  1982. GetArg1(2, arg);
  1983. reg[0] = r(0);
  1984. reg[live] = arg;
  1985. bf = (GcBifFunction) Arg(1);
  1986. c_p->fcalls = FCALLS;
  1987. SWAPOUT;
  1988. PROCESS_MAIN_CHK_LOCKS(c_p);
  1989. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  1990. result = (*bf)(c_p, reg, live);
  1991. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  1992. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  1993. PROCESS_MAIN_CHK_LOCKS(c_p);
  1994. SWAPIN;
  1995. r(0) = reg[0];
  1996. ERTS_HOLE_CHECK(c_p);
  1997. FCALLS = c_p->fcalls;
  1998. if (is_value(result)) {
  1999. StoreBifResult(4, result);
  2000. }
  2001. if (Arg(0) != 0) {
  2002. SET_I((BeamInstr *) Arg(0));
  2003. Goto(*I);
  2004. }
  2005. reg[0] = arg;
  2006. I = handle_error(c_p, I, reg, translate_gc_bif((void *) bf));
  2007. goto post_error_handling;
  2008. }
  2009. OpCase(i_gc_bif2_jIId): /* Note, one less parameter than the i_gc_bif1
  2010. and i_gc_bif3 */
  2011. {
  2012. typedef Eterm (*GcBifFunction)(Process*, Eterm*, Uint);
  2013. GcBifFunction bf;
  2014. Eterm result;
  2015. Uint live = (Uint) Arg(2);
  2016. reg[0] = r(0);
  2017. reg[live++] = tmp_arg1;
  2018. reg[live] = tmp_arg2;
  2019. bf = (GcBifFunction) Arg(1);
  2020. c_p->fcalls = FCALLS;
  2021. SWAPOUT;
  2022. PROCESS_MAIN_CHK_LOCKS(c_p);
  2023. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  2024. result = (*bf)(c_p, reg, live);
  2025. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2026. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  2027. PROCESS_MAIN_CHK_LOCKS(c_p);
  2028. SWAPIN;
  2029. r(0) = reg[0];
  2030. ERTS_HOLE_CHECK(c_p);
  2031. FCALLS = c_p->fcalls;
  2032. if (is_value(result)) {
  2033. StoreBifResult(3, result);
  2034. }
  2035. if (Arg(0) != 0) {
  2036. SET_I((BeamInstr *) Arg(0));
  2037. Goto(*I);
  2038. }
  2039. reg[0] = tmp_arg1;
  2040. reg[1] = tmp_arg2;
  2041. I = handle_error(c_p, I, reg, translate_gc_bif((void *) bf));
  2042. goto post_error_handling;
  2043. }
  2044. OpCase(i_gc_bif3_jIsId):
  2045. {
  2046. typedef Eterm (*GcBifFunction)(Process*, Eterm*, Uint);
  2047. GcBifFunction bf;
  2048. Eterm arg;
  2049. Eterm result;
  2050. Uint live = (Uint) Arg(3);
  2051. GetArg1(2, arg);
  2052. reg[0] = r(0);
  2053. reg[live++] = arg;
  2054. reg[live++] = tmp_arg1;
  2055. reg[live] = tmp_arg2;
  2056. bf = (GcBifFunction) Arg(1);
  2057. c_p->fcalls = FCALLS;
  2058. SWAPOUT;
  2059. PROCESS_MAIN_CHK_LOCKS(c_p);
  2060. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  2061. result = (*bf)(c_p, reg, live);
  2062. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2063. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  2064. PROCESS_MAIN_CHK_LOCKS(c_p);
  2065. SWAPIN;
  2066. r(0) = reg[0];
  2067. ERTS_HOLE_CHECK(c_p);
  2068. FCALLS = c_p->fcalls;
  2069. if (is_value(result)) {
  2070. StoreBifResult(4, result);
  2071. }
  2072. if (Arg(0) != 0) {
  2073. SET_I((BeamInstr *) Arg(0));
  2074. Goto(*I);
  2075. }
  2076. reg[0] = arg;
  2077. reg[1] = tmp_arg1;
  2078. reg[2] = tmp_arg2;
  2079. I = handle_error(c_p, I, reg, translate_gc_bif((void *) bf));
  2080. goto post_error_handling;
  2081. }
  2082. /*
  2083. * Guards bifs and, or, xor in guards.
  2084. */
  2085. OpCase(i_bif2_fbd):
  2086. {
  2087. Eterm (*bf)(Process*, Eterm, Eterm);
  2088. Eterm result;
  2089. bf = (BifFunction) Arg(1);
  2090. c_p->fcalls = FCALLS;
  2091. PROCESS_MAIN_CHK_LOCKS(c_p);
  2092. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2093. result = (*bf)(c_p, tmp_arg1, tmp_arg2);
  2094. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
  2095. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2096. PROCESS_MAIN_CHK_LOCKS(c_p);
  2097. ERTS_HOLE_CHECK(c_p);
  2098. FCALLS = c_p->fcalls;
  2099. if (is_value(result)) {
  2100. StoreBifResult(2, result);
  2101. }
  2102. SET_I((BeamInstr *) Arg(0));
  2103. Goto(*I);
  2104. }
  2105. /*
  2106. * Guards bifs and, or, xor, relational operators in body.
  2107. */
  2108. OpCase(i_bif2_body_bd):
  2109. {
  2110. Eterm (*bf)(Process*, Eterm, Eterm);
  2111. Eterm result;
  2112. bf = (BifFunction) Arg(0);
  2113. PROCESS_MAIN_CHK_LOCKS(c_p);
  2114. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2115. result = (*bf)(c_p, tmp_arg1, tmp_arg2);
  2116. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
  2117. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2118. PROCESS_MAIN_CHK_LOCKS(c_p);
  2119. ERTS_HOLE_CHECK(c_p);
  2120. if (is_value(result)) {
  2121. ASSERT(!is_CP(result));
  2122. StoreBifResult(1, result);
  2123. }
  2124. reg[0] = tmp_arg1;
  2125. reg[1] = tmp_arg2;
  2126. SWAPOUT;
  2127. I = handle_error(c_p, I, reg, bf);
  2128. goto post_error_handling;
  2129. }
  2130. /*
  2131. * The most general BIF call. The BIF may build any amount of data
  2132. * on the heap. The result is always returned in r(0).
  2133. */
  2134. OpCase(call_bif0_e):
  2135. {
  2136. Eterm (*bf)(Process*, BeamInstr*) = GET_BIF_ADDRESS(Arg(0));
  2137. PRE_BIF_SWAPOUT(c_p);
  2138. c_p->fcalls = FCALLS - 1;
  2139. if (FCALLS <= 0) {
  2140. save_calls(c_p, (Export *) Arg(0));
  2141. }
  2142. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2143. r(0) = (*bf)(c_p, I);
  2144. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(r(0)));
  2145. ERTS_HOLE_CHECK(c_p);
  2146. POST_BIF_GC_SWAPIN_0(c_p, r(0));
  2147. FCALLS = c_p->fcalls;
  2148. if (is_value(r(0))) {
  2149. CHECK_TERM(r(0));
  2150. Next(1);
  2151. }
  2152. else if (c_p->freason == TRAP) {
  2153. goto call_bif_trap3;
  2154. }
  2155. /*
  2156. * Error handling. SWAPOUT is not needed because it was done above.
  2157. */
  2158. ASSERT(c_p->stop == E);
  2159. reg[0] = r(0);
  2160. I = handle_error(c_p, I, reg, bf);
  2161. goto post_error_handling;
  2162. }
  2163. OpCase(call_bif1_e):
  2164. {
  2165. Eterm (*bf)(Process*, Eterm, BeamInstr*) = GET_BIF_ADDRESS(Arg(0));
  2166. Eterm result;
  2167. BeamInstr *next;
  2168. c_p->fcalls = FCALLS - 1;
  2169. if (FCALLS <= 0) {
  2170. save_calls(c_p, (Export *) Arg(0));
  2171. }
  2172. PreFetch(1, next);
  2173. PRE_BIF_SWAPOUT(c_p);
  2174. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2175. result = (*bf)(c_p, r(0), I);
  2176. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
  2177. ERTS_HOLE_CHECK(c_p);
  2178. POST_BIF_GC_SWAPIN(c_p, result, reg, 1);
  2179. FCALLS = c_p->fcalls;
  2180. if (is_value(result)) {
  2181. r(0) = result;
  2182. CHECK_TERM(r(0));
  2183. NextPF(1, next);
  2184. } else if (c_p->freason == TRAP) {
  2185. goto call_bif_trap3;
  2186. }
  2187. /*
  2188. * Error handling. SWAPOUT is not needed because it was done above.
  2189. */
  2190. ASSERT(c_p->stop == E);
  2191. reg[0] = r(0);
  2192. I = handle_error(c_p, I, reg, bf);
  2193. goto post_error_handling;
  2194. }
  2195. OpCase(call_bif2_e):
  2196. {
  2197. Eterm (*bf)(Process*, Eterm, Eterm, BeamInstr*) = GET_BIF_ADDRESS(Arg(0));
  2198. Eterm result;
  2199. BeamInstr *next;
  2200. PRE_BIF_SWAPOUT(c_p);
  2201. c_p->fcalls = FCALLS - 1;
  2202. if (FCALLS <= 0) {
  2203. save_calls(c_p, (Export *) Arg(0));
  2204. }
  2205. PreFetch(1, next);
  2206. CHECK_TERM(r(0));
  2207. CHECK_TERM(x(1));
  2208. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2209. result = (*bf)(c_p, r(0), x(1), I);
  2210. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
  2211. ERTS_HOLE_CHECK(c_p);
  2212. POST_BIF_GC_SWAPIN(c_p, result, reg, 2);
  2213. FCALLS = c_p->fcalls;
  2214. if (is_value(result)) {
  2215. r(0) = result;
  2216. CHECK_TERM(r(0));
  2217. NextPF(1, next);
  2218. } else if (c_p->freason == TRAP) {
  2219. goto call_bif_trap3;
  2220. }
  2221. /*
  2222. * Error handling. SWAPOUT is not needed because it was done above.
  2223. */
  2224. ASSERT(c_p->stop == E);
  2225. reg[0] = r(0);
  2226. I = handle_error(c_p, I, reg, bf);
  2227. goto post_error_handling;
  2228. }
  2229. OpCase(call_bif3_e):
  2230. {
  2231. Eterm (*bf)(Process*, Eterm, Eterm, Eterm, BeamInstr*) = GET_BIF_ADDRESS(Arg(0));
  2232. Eterm result;
  2233. BeamInstr *next;
  2234. PRE_BIF_SWAPOUT(c_p);
  2235. c_p->fcalls = FCALLS - 1;
  2236. if (FCALLS <= 0) {
  2237. save_calls(c_p, (Export *) Arg(0));
  2238. }
  2239. PreFetch(1, next);
  2240. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2241. result = (*bf)(c_p, r(0), x(1), x(2), I);
  2242. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(result));
  2243. ERTS_HOLE_CHECK(c_p);
  2244. POST_BIF_GC_SWAPIN(c_p, result, reg, 3);
  2245. FCALLS = c_p->fcalls;
  2246. if (is_value(result)) {
  2247. r(0) = result;
  2248. CHECK_TERM(r(0));
  2249. NextPF(1, next);
  2250. } else if (c_p->freason == TRAP) {
  2251. call_bif_trap3:
  2252. SET_CP(c_p, I+2);
  2253. SET_I(*((BeamInstr **) (UWord) ((c_p)->def_arg_reg + 3)));
  2254. SWAPIN;
  2255. r(0) = c_p->def_arg_reg[0];
  2256. x(1) = c_p->def_arg_reg[1];
  2257. x(2) = c_p->def_arg_reg[2];
  2258. Dispatch();
  2259. }
  2260. /*
  2261. * Error handling. SWAPOUT is not needed because it was done above.
  2262. */
  2263. ASSERT(c_p->stop == E);
  2264. reg[0] = r(0);
  2265. I = handle_error(c_p, I, reg, bf);
  2266. goto post_error_handling;
  2267. }
  2268. /*
  2269. * Arithmetic operations.
  2270. */
  2271. OpCase(i_times_jId):
  2272. {
  2273. arith_func = ARITH_FUNC(mixed_times);
  2274. goto do_big_arith2;
  2275. }
  2276. OpCase(i_m_div_jId):
  2277. {
  2278. arith_func = ARITH_FUNC(mixed_div);
  2279. goto do_big_arith2;
  2280. }
  2281. OpCase(i_int_div_jId):
  2282. {
  2283. Eterm result;
  2284. if (tmp_arg2 == SMALL_ZERO) {
  2285. goto badarith;
  2286. } else if (is_both_small(tmp_arg1, tmp_arg2)) {
  2287. Sint ires = signed_val(tmp_arg1) / signed_val(tmp_arg2);
  2288. if (MY_IS_SSMALL(ires)) {
  2289. result = make_small(ires);
  2290. STORE_ARITH_RESULT(result);
  2291. }
  2292. }
  2293. arith_func = ARITH_FUNC(int_div);
  2294. goto do_big_arith2;
  2295. }
  2296. OpCase(i_rem_jId):
  2297. {
  2298. Eterm result;
  2299. if (tmp_arg2 == SMALL_ZERO) {
  2300. goto badarith;
  2301. } else if (is_both_small(tmp_arg1, tmp_arg2)) {
  2302. result = make_small(signed_val(tmp_arg1) % signed_val(tmp_arg2));
  2303. STORE_ARITH_RESULT(result);
  2304. } else {
  2305. arith_func = ARITH_FUNC(int_rem);
  2306. goto do_big_arith2;
  2307. }
  2308. }
  2309. OpCase(i_band_jId):
  2310. {
  2311. Eterm result;
  2312. if (is_both_small(tmp_arg1, tmp_arg2)) {
  2313. /*
  2314. * No need to untag -- TAG & TAG == TAG.
  2315. */
  2316. result = tmp_arg1 & tmp_arg2;
  2317. STORE_ARITH_RESULT(result);
  2318. }
  2319. arith_func = ARITH_FUNC(band);
  2320. goto do_big_arith2;
  2321. }
  2322. do_big_arith2:
  2323. {
  2324. Eterm result;
  2325. Uint live = Arg(1);
  2326. SWAPOUT;
  2327. reg[0] = r(0);
  2328. reg[live] = tmp_arg1;
  2329. reg[live+1] = tmp_arg2;
  2330. result = arith_func(c_p, reg, live);
  2331. r(0) = reg[0];
  2332. SWAPIN;
  2333. ERTS_HOLE_CHECK(c_p);
  2334. if (is_value(result)) {
  2335. STORE_ARITH_RESULT(result);
  2336. }
  2337. goto lb_Cl_error;
  2338. }
  2339. /*
  2340. * An error occured in an arithmetic operation or test that could
  2341. * appear either in a head or in a body.
  2342. * In a head, execution should continue at failure address in Arg(0).
  2343. * In a body, Arg(0) == 0 and an exception should be raised.
  2344. */
  2345. lb_Cl_error: {
  2346. if (Arg(0) != 0) {
  2347. OpCase(jump_f): {
  2348. SET_I((BeamInstr *) Arg(0));
  2349. Goto(*I);
  2350. }
  2351. }
  2352. ASSERT(c_p->freason != BADMATCH || is_value(c_p->fvalue));
  2353. goto find_func_info;
  2354. }
  2355. OpCase(i_bor_jId):
  2356. {
  2357. Eterm result;
  2358. if (is_both_small(tmp_arg1, tmp_arg2)) {
  2359. /*
  2360. * No need to untag -- TAG | TAG == TAG.
  2361. */
  2362. result = tmp_arg1 | tmp_arg2;
  2363. STORE_ARITH_RESULT(result);
  2364. }
  2365. arith_func = ARITH_FUNC(bor);
  2366. goto do_big_arith2;
  2367. }
  2368. OpCase(i_bxor_jId):
  2369. {
  2370. Eterm result;
  2371. if (is_both_small(tmp_arg1, tmp_arg2)) {
  2372. /*
  2373. * We could extract the tag from one argument, but a tag extraction
  2374. * could mean a shift. Therefore, play it safe here.
  2375. */
  2376. result = make_small(signed_val(tmp_arg1) ^ signed_val(tmp_arg2));
  2377. STORE_ARITH_RESULT(result);
  2378. }
  2379. arith_func = ARITH_FUNC(bxor);
  2380. goto do_big_arith2;
  2381. }
  2382. {
  2383. Sint i;
  2384. Sint ires;
  2385. Eterm* bigp;
  2386. OpCase(i_bsr_jId):
  2387. if (is_small(tmp_arg2)) {
  2388. i = -signed_val(tmp_arg2);
  2389. if (is_small(tmp_arg1)) {
  2390. goto small_shift;
  2391. } else if (is_big(tmp_arg1)) {
  2392. if (i == 0) {
  2393. StoreBifResult(2, tmp_arg1);
  2394. }
  2395. goto big_shift;
  2396. }
  2397. } else if (is_big(tmp_arg2)) {
  2398. /*
  2399. * N bsr NegativeBigNum == N bsl MAX_SMALL
  2400. * N bsr PositiveBigNum == N bsl MIN_SMALL
  2401. */
  2402. tmp_arg2 = make_small(bignum_header_is_neg(*big_val(tmp_arg2)) ?
  2403. MAX_SMALL : MIN_SMALL);
  2404. goto do_bsl;
  2405. }
  2406. goto badarith;
  2407. OpCase(i_bsl_jId):
  2408. do_bsl:
  2409. if (is_small(tmp_arg2)) {
  2410. i = signed_val(tmp_arg2);
  2411. if (is_small(tmp_arg1)) {
  2412. small_shift:
  2413. ires = signed_val(tmp_arg1);
  2414. if (i == 0 || ires == 0) {
  2415. StoreBifResult(2, tmp_arg1);
  2416. } else if (i < 0) { /* Right shift */
  2417. i = -i;
  2418. if (i >= SMALL_BITS-1) {
  2419. tmp_arg1 = (ires < 0) ? SMALL_MINUS_ONE : SMALL_ZERO;
  2420. } else {
  2421. tmp_arg1 = make_small(ires >> i);
  2422. }
  2423. StoreBifResult(2, tmp_arg1);
  2424. } else if (i < SMALL_BITS-1) { /* Left shift */
  2425. if ((ires > 0 && ((~(Uint)0 << ((SMALL_BITS-1)-i)) & ires) == 0) ||
  2426. ((~(Uint)0 << ((SMALL_BITS-1)-i)) & ~ires) == 0) {
  2427. tmp_arg1 = make_small(ires << i);
  2428. StoreBifResult(2, tmp_arg1);
  2429. }
  2430. }
  2431. tmp_arg1 = small_to_big(ires, tmp_big);
  2432. big_shift:
  2433. if (i > 0) { /* Left shift. */
  2434. ires = big_size(tmp_arg1) + (i / D_EXP);
  2435. } else { /* Right shift. */
  2436. ires = big_size(tmp_arg1);
  2437. if (ires <= (-i / D_EXP))
  2438. ires = 3; /* ??? */
  2439. else
  2440. ires -= (-i / D_EXP);
  2441. }
  2442. {
  2443. ires = BIG_NEED_SIZE(ires+1);
  2444. /*
  2445. * Slightly conservative check the size to avoid
  2446. * allocating huge amounts of memory for bignums that
  2447. * clearly would overflow the arity in the header
  2448. * word.
  2449. */
  2450. if (ires-8 > BIG_ARITY_MAX) {
  2451. c_p->freason = SYSTEM_LIMIT;
  2452. goto lb_Cl_error;
  2453. }
  2454. TestHeapPreserve(ires+1, Arg(1), tmp_arg1);
  2455. bigp = HTOP;
  2456. tmp_arg1 = big_lshift(tmp_arg1, i, bigp);
  2457. if (is_big(tmp_arg1)) {
  2458. HTOP += bignum_header_arity(*HTOP) + 1;
  2459. }
  2460. HEAP_SPACE_VERIFIED(0);
  2461. if (is_nil(tmp_arg1)) {
  2462. /*
  2463. * This result must have been only slight larger
  2464. * than allowed since it wasn't caught by the
  2465. * previous test.
  2466. */
  2467. c_p->freason = SYSTEM_LIMIT;
  2468. goto lb_Cl_error;
  2469. }
  2470. ERTS_HOLE_CHECK(c_p);
  2471. StoreBifResult(2, tmp_arg1);
  2472. }
  2473. } else if (is_big(tmp_arg1)) {
  2474. if (i == 0) {
  2475. StoreBifResult(2, tmp_arg1);
  2476. }
  2477. goto big_shift;
  2478. }
  2479. } else if (is_big(tmp_arg2)) {
  2480. if (bignum_header_is_neg(*big_val(tmp_arg2))) {
  2481. /*
  2482. * N bsl NegativeBigNum is either 0 or -1, depending on
  2483. * the sign of N. Since we don't believe this case
  2484. * is common, do the calculation with the minimum
  2485. * amount of code.
  2486. */
  2487. tmp_arg2 = make_small(MIN_SMALL);
  2488. goto do_bsl;
  2489. } else if (is_small(tmp_arg1) || is_big(tmp_arg1)) {
  2490. /*
  2491. * N bsl PositiveBigNum is too large to represent.
  2492. */
  2493. c_p->freason = SYSTEM_LIMIT;
  2494. goto lb_Cl_error;
  2495. }
  2496. /* Fall through if the left argument is not an integer. */
  2497. }
  2498. /*
  2499. * One or more non-integer arguments.
  2500. */
  2501. goto badarith;
  2502. }
  2503. OpCase(i_int_bnot_jsId):
  2504. {
  2505. Eterm bnot_val;
  2506. GetArg1(1, bnot_val);
  2507. if (is_small(bnot_val)) {
  2508. bnot_val = make_small(~signed_val(bnot_val));
  2509. } else {
  2510. Uint live = Arg(2);
  2511. SWAPOUT;
  2512. reg[0] = r(0);
  2513. reg[live] = bnot_val;
  2514. bnot_val = erts_gc_bnot(c_p, reg, live);
  2515. r(0) = reg[0];
  2516. SWAPIN;
  2517. ERTS_HOLE_CHECK(c_p);
  2518. if (is_nil(bnot_val)) {
  2519. goto lb_Cl_error;
  2520. }
  2521. }
  2522. StoreBifResult(3, bnot_val);
  2523. }
  2524. badarith:
  2525. c_p->freason = BADARITH;
  2526. goto lb_Cl_error;
  2527. OpCase(i_apply): {
  2528. BeamInstr *next;
  2529. SWAPOUT;
  2530. next = apply(c_p, r(0), x(1), x(2), reg);
  2531. SWAPIN;
  2532. if (next != NULL) {
  2533. r(0) = reg[0];
  2534. SET_CP(c_p, I+1);
  2535. SET_I(next);
  2536. Dispatch();
  2537. }
  2538. I = handle_error(c_p, I, reg, apply_3);
  2539. goto post_error_handling;
  2540. }
  2541. OpCase(i_apply_last_P): {
  2542. BeamInstr *next;
  2543. SWAPOUT;
  2544. next = apply(c_p, r(0), x(1), x(2), reg);
  2545. SWAPIN;
  2546. if (next != NULL) {
  2547. r(0) = reg[0];
  2548. SET_CP(c_p, (BeamInstr *) EXPAND_POINTER(E[0]));
  2549. E = ADD_BYTE_OFFSET(E, Arg(0));
  2550. SET_I(next);
  2551. Dispatch();
  2552. }
  2553. I = handle_error(c_p, I, reg, apply_3);
  2554. goto post_error_handling;
  2555. }
  2556. OpCase(i_apply_only): {
  2557. BeamInstr *next;
  2558. SWAPOUT;
  2559. next = apply(c_p, r(0), x(1), x(2), reg);
  2560. SWAPIN;
  2561. if (next != NULL) {
  2562. r(0) = reg[0];
  2563. SET_I(next);
  2564. Dispatch();
  2565. }
  2566. I = handle_error(c_p, I, reg, apply_3);
  2567. goto post_error_handling;
  2568. }
  2569. OpCase(apply_I): {
  2570. BeamInstr *next;
  2571. reg[0] = r(0);
  2572. SWAPOUT;
  2573. next = fixed_apply(c_p, reg, Arg(0));
  2574. SWAPIN;
  2575. if (next != NULL) {
  2576. r(0) = reg[0];
  2577. SET_CP(c_p, I+2);
  2578. SET_I(next);
  2579. Dispatch();
  2580. }
  2581. I = handle_error(c_p, I, reg, apply_3);
  2582. goto post_error_handling;
  2583. }
  2584. OpCase(apply_last_IP): {
  2585. BeamInstr *next;
  2586. reg[0] = r(0);
  2587. SWAPOUT;
  2588. next = fixed_apply(c_p, reg, Arg(0));
  2589. SWAPIN;
  2590. if (next != NULL) {
  2591. r(0) = reg[0];
  2592. SET_CP(c_p, (BeamInstr *) EXPAND_POINTER(E[0]));
  2593. E = ADD_BYTE_OFFSET(E, Arg(1));
  2594. SET_I(next);
  2595. Dispatch();
  2596. }
  2597. I = handle_error(c_p, I, reg, apply_3);
  2598. goto post_error_handling;
  2599. }
  2600. OpCase(i_apply_fun): {
  2601. BeamInstr *next;
  2602. SWAPOUT;
  2603. next = apply_fun(c_p, r(0), x(1), reg);
  2604. SWAPIN;
  2605. if (next != NULL) {
  2606. r(0) = reg[0];
  2607. SET_CP(c_p, I+1);
  2608. SET_I(next);
  2609. Dispatchfun();
  2610. }
  2611. goto find_func_info;
  2612. }
  2613. OpCase(i_apply_fun_last_P): {
  2614. BeamInstr *next;
  2615. SWAPOUT;
  2616. next = apply_fun(c_p, r(0), x(1), reg);
  2617. SWAPIN;
  2618. if (next != NULL) {
  2619. r(0) = reg[0];
  2620. SET_CP(c_p, (BeamInstr *) EXPAND_POINTER(E[0]));
  2621. E = ADD_BYTE_OFFSET(E, Arg(0));
  2622. SET_I(next);
  2623. Dispatchfun();
  2624. }
  2625. goto find_func_info;
  2626. }
  2627. OpCase(i_apply_fun_only): {
  2628. BeamInstr *next;
  2629. SWAPOUT;
  2630. next = apply_fun(c_p, r(0), x(1), reg);
  2631. SWAPIN;
  2632. if (next != NULL) {
  2633. r(0) = reg[0];
  2634. SET_I(next);
  2635. Dispatchfun();
  2636. }
  2637. goto find_func_info;
  2638. }
  2639. OpCase(i_call_fun_I): {
  2640. BeamInstr *next;
  2641. SWAPOUT;
  2642. reg[0] = r(0);
  2643. next = call_fun(c_p, Arg(0), reg, THE_NON_VALUE);
  2644. SWAPIN;
  2645. if (next != NULL) {
  2646. r(0) = reg[0];
  2647. SET_CP(c_p, I+2);
  2648. SET_I(next);
  2649. Dispatchfun();
  2650. }
  2651. goto find_func_info;
  2652. }
  2653. OpCase(i_call_fun_last_IP): {
  2654. BeamInstr *next;
  2655. SWAPOUT;
  2656. reg[0] = r(0);
  2657. next = call_fun(c_p, Arg(0), reg, THE_NON_VALUE);
  2658. SWAPIN;
  2659. if (next != NULL) {
  2660. r(0) = reg[0];
  2661. SET_CP(c_p, (BeamInstr *) EXPAND_POINTER(E[0]));
  2662. E = ADD_BYTE_OFFSET(E, Arg(1));
  2663. SET_I(next);
  2664. Dispatchfun();
  2665. }
  2666. goto find_func_info;
  2667. }
  2668. #ifdef DEBUG
  2669. /*
  2670. * Set a breakpoint here to get control just after a call instruction.
  2671. * I points to the first instruction in the called function.
  2672. *
  2673. * In gdb, use 'call dis(I-5, 1)' to show the name of the function.
  2674. */
  2675. do_dispatch:
  2676. DispatchMacro();
  2677. do_dispatchx:
  2678. DispatchMacrox();
  2679. do_dispatchfun:
  2680. DispatchMacroFun();
  2681. #endif
  2682. /*
  2683. * Jumped to from the Dispatch() macro when the reductions are used up.
  2684. *
  2685. * Since the I register points just beyond the FuncBegin instruction, we
  2686. * can get the module, function, and arity for the function being
  2687. * called from I[-3], I[-2], and I[-1] respectively.
  2688. */
  2689. context_switch_fun:
  2690. c_p->arity = I[-1] + 1;
  2691. goto context_switch2;
  2692. context_switch:
  2693. c_p->arity = I[-1];
  2694. context_switch2: /* Entry for fun calls. */
  2695. c_p->current = I-3; /* Pointer to Mod, Func, Arity */
  2696. {
  2697. Eterm* argp;
  2698. int i;
  2699. /*
  2700. * Make sure that there is enough room for the argument registers to be saved.
  2701. */
  2702. if (c_p->arity > c_p->max_arg_reg) {
  2703. /*
  2704. * Yes, this is an expensive operation, but you only pay it the first
  2705. * time you call a function with more than 6 arguments which is
  2706. * scheduled out. This is better than paying for 26 words of wasted
  2707. * space for most processes which never call functions with more than
  2708. * 6 arguments.
  2709. */
  2710. Uint size = c_p->arity * sizeof(c_p->arg_reg[0]);
  2711. if (c_p->arg_reg != c_p->def_arg_reg) {
  2712. c_p->arg_reg = (Eterm *) erts_realloc(ERTS_ALC_T_ARG_REG,
  2713. (void *) c_p->arg_reg,
  2714. size);
  2715. } else {
  2716. c_p->arg_reg = (Eterm *) erts_alloc(ERTS_ALC_T_ARG_REG, size);
  2717. }
  2718. c_p->max_arg_reg = c_p->arity;
  2719. }
  2720. /*
  2721. * Since REDS_IN(c_p) is stored in the save area (c_p->arg_reg) we must read it
  2722. * now before saving registers.
  2723. *
  2724. * The '+ 1' compensates for the last increment which was not done
  2725. * (beacuse the code for the Dispatch() macro becomes shorter that way).
  2726. */
  2727. reds_used = REDS_IN(c_p) - FCALLS + 1;
  2728. /*
  2729. * Save the argument registers and everything else.
  2730. */
  2731. argp = c_p->arg_reg;
  2732. for (i = c_p->arity - 1; i > 0; i--) {
  2733. argp[i] = reg[i];
  2734. }
  2735. c_p->arg_reg[0] = r(0);
  2736. SWAPOUT;
  2737. c_p->i = I;
  2738. erts_smp_proc_lock(c_p, ERTS_PROC_LOCK_STATUS);
  2739. if (c_p->status != P_SUSPENDED)
  2740. erts_add_to_runq(c_p);
  2741. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCK_STATUS);
  2742. goto do_schedule1;
  2743. }
  2744. OpCase(set_tuple_element_sdP): {
  2745. Eterm element;
  2746. Eterm tuple;
  2747. BeamInstr *next;
  2748. Eterm* p;
  2749. PreFetch(3, next);
  2750. GetArg2(0, element, tuple);
  2751. ASSERT(is_tuple(tuple));
  2752. p = (Eterm *) ((unsigned char *) tuple_val(tuple) + Arg(2));
  2753. *p = element;
  2754. NextPF(3, next);
  2755. }
  2756. OpCase(i_is_ne_exact_f):
  2757. if (EQ(tmp_arg1, tmp_arg2)) {
  2758. ClauseFail();
  2759. }
  2760. Next(1);
  2761. OpCase(normal_exit): {
  2762. SWAPOUT;
  2763. c_p->freason = EXC_NORMAL;
  2764. c_p->arity = 0; /* In case this process will ever be garbed again. */
  2765. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  2766. erts_do_exit_process(c_p, am_normal);
  2767. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  2768. goto do_schedule;
  2769. }
  2770. OpCase(continue_exit): {
  2771. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  2772. erts_continue_exit_process(c_p);
  2773. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  2774. goto do_schedule;
  2775. }
  2776. OpCase(raise_ss): {
  2777. /* This was not done very well in R10-0; then, we passed the tag in
  2778. the first argument and hoped that the existing c_p->ftrace was
  2779. still correct. But the ftrace-object already includes the tag
  2780. (or rather, the freason). Now, we pass the original ftrace in
  2781. the first argument. We also handle atom tags in the first
  2782. argument for backwards compatibility.
  2783. */
  2784. Eterm raise_val1;
  2785. Eterm raise_val2;
  2786. GetArg2(0, raise_val1, raise_val2);
  2787. c_p->fvalue = raise_val2;
  2788. if (c_p->freason == EXC_NULL) {
  2789. /* a safety check for the R10-0 case; should not happen */
  2790. c_p->ftrace = NIL;
  2791. c_p->freason = EXC_ERROR;
  2792. }
  2793. /* for R10-0 code, keep existing c_p->ftrace and hope it's correct */
  2794. switch (raise_val1) {
  2795. case am_throw:
  2796. c_p->freason = EXC_THROWN & ~EXF_SAVETRACE;
  2797. break;
  2798. case am_error:
  2799. c_p->freason = EXC_ERROR & ~EXF_SAVETRACE;
  2800. break;
  2801. case am_exit:
  2802. c_p->freason = EXC_EXIT & ~EXF_SAVETRACE;
  2803. break;
  2804. default:
  2805. {/* R10-1 and later
  2806. XXX note: should do sanity check on given trace if it can be
  2807. passed from a user! Currently only expecting generated calls.
  2808. */
  2809. struct StackTrace *s;
  2810. c_p->ftrace = raise_val1;
  2811. s = get_trace_from_exc(raise_val1);
  2812. if (s == NULL) {
  2813. c_p->freason = EXC_ERROR;
  2814. } else {
  2815. c_p->freason = PRIMARY_EXCEPTION(s->freason);
  2816. }
  2817. }
  2818. }
  2819. goto find_func_info;
  2820. }
  2821. {
  2822. Eterm badmatch_val;
  2823. OpCase(badmatch_y):
  2824. badmatch_val = yb(Arg(0));
  2825. goto do_badmatch;
  2826. OpCase(badmatch_x):
  2827. badmatch_val = xb(Arg(0));
  2828. goto do_badmatch;
  2829. OpCase(badmatch_r):
  2830. badmatch_val = r(0);
  2831. do_badmatch:
  2832. c_p->fvalue = badmatch_val;
  2833. c_p->freason = BADMATCH;
  2834. }
  2835. /* Fall through here */
  2836. find_func_info: {
  2837. reg[0] = r(0);
  2838. SWAPOUT;
  2839. I = handle_error(c_p, I, reg, NULL);
  2840. goto post_error_handling;
  2841. }
  2842. OpCase(call_error_handler):
  2843. /*
  2844. * At this point, I points to the code[3] in the export entry for
  2845. * a function which is not loaded.
  2846. *
  2847. * code[0]: Module
  2848. * code[1]: Function
  2849. * code[2]: Arity
  2850. * code[3]: &&call_error_handler
  2851. * code[4]: Not used
  2852. */
  2853. SWAPOUT;
  2854. reg[0] = r(0);
  2855. I = call_error_handler(c_p, I-3, reg, am_undefined_function);
  2856. r(0) = reg[0];
  2857. SWAPIN;
  2858. if (I) {
  2859. Goto(*I);
  2860. }
  2861. /* Fall through */
  2862. OpCase(error_action_code): {
  2863. no_error_handler:
  2864. reg[0] = r(0);
  2865. SWAPOUT;
  2866. I = handle_error(c_p, NULL, reg, NULL);
  2867. post_error_handling:
  2868. if (I == 0) {
  2869. goto do_schedule;
  2870. } else {
  2871. r(0) = reg[0];
  2872. ASSERT(!is_value(r(0)));
  2873. if (c_p->mbuf) {
  2874. erts_garbage_collect(c_p, 0, reg+1, 3);
  2875. }
  2876. SWAPIN;
  2877. Goto(*I);
  2878. }
  2879. }
  2880. {
  2881. Eterm nif_bif_result;
  2882. Eterm bif_nif_arity;
  2883. OpCase(call_nif):
  2884. {
  2885. /*
  2886. * call_nif is always first instruction in function:
  2887. *
  2888. * I[-3]: Module
  2889. * I[-2]: Function
  2890. * I[-1]: Arity
  2891. * I[0]: &&call_nif
  2892. * I[1]: Function pointer to NIF function
  2893. * I[2]: Pointer to erl_module_nif
  2894. */
  2895. BifFunction vbf;
  2896. c_p->current = I-3; /* current and vbf set to please handle_error */
  2897. SWAPOUT;
  2898. c_p->fcalls = FCALLS - 1;
  2899. PROCESS_MAIN_CHK_LOCKS(c_p);
  2900. bif_nif_arity = I[-1];
  2901. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  2902. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2903. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2904. {
  2905. typedef Eterm NifF(struct enif_environment_t*, int argc, Eterm argv[]);
  2906. NifF* fp = vbf = (NifF*) I[1];
  2907. struct enif_environment_t env;
  2908. erts_pre_nif(&env, c_p, (struct erl_module_nif*)I[2]);
  2909. reg[0] = r(0);
  2910. nif_bif_result = (*fp)(&env, bif_nif_arity, reg);
  2911. erts_post_nif(&env);
  2912. }
  2913. ASSERT(!ERTS_PROC_IS_EXITING(c_p) || is_non_value(nif_bif_result));
  2914. PROCESS_MAIN_CHK_LOCKS(c_p);
  2915. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2916. goto apply_bif_or_nif_epilogue;
  2917. OpCase(apply_bif):
  2918. /*
  2919. * At this point, I points to the code[3] in the export entry for
  2920. * the BIF:
  2921. *
  2922. * code[0]: Module
  2923. * code[1]: Function
  2924. * code[2]: Arity
  2925. * code[3]: &&apply_bif
  2926. * code[4]: Function pointer to BIF function
  2927. */
  2928. c_p->current = I-3; /* In case we apply process_info/1,2 or load_nif/1 */
  2929. c_p->i = I; /* In case we apply check_process_code/2. */
  2930. c_p->arity = 0; /* To allow garbage collection on ourselves
  2931. * (check_process_code/2).
  2932. */
  2933. SWAPOUT;
  2934. c_p->fcalls = FCALLS - 1;
  2935. vbf = (BifFunction) Arg(0);
  2936. PROCESS_MAIN_CHK_LOCKS(c_p);
  2937. bif_nif_arity = I[-1];
  2938. ASSERT(bif_nif_arity <= 3);
  2939. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  2940. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2941. switch (bif_nif_arity) {
  2942. case 3:
  2943. {
  2944. Eterm (*bf)(Process*, Eterm, Eterm, Eterm, BeamInstr*) = vbf;
  2945. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2946. nif_bif_result = (*bf)(c_p, r(0), x(1), x(2), I);
  2947. ASSERT(!ERTS_PROC_IS_EXITING(c_p) ||
  2948. is_non_value(nif_bif_result));
  2949. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2950. PROCESS_MAIN_CHK_LOCKS(c_p);
  2951. }
  2952. break;
  2953. case 2:
  2954. {
  2955. Eterm (*bf)(Process*, Eterm, Eterm, BeamInstr*) = vbf;
  2956. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2957. nif_bif_result = (*bf)(c_p, r(0), x(1), I);
  2958. ASSERT(!ERTS_PROC_IS_EXITING(c_p) ||
  2959. is_non_value(nif_bif_result));
  2960. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2961. PROCESS_MAIN_CHK_LOCKS(c_p);
  2962. }
  2963. break;
  2964. case 1:
  2965. {
  2966. Eterm (*bf)(Process*, Eterm, BeamInstr*) = vbf;
  2967. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2968. nif_bif_result = (*bf)(c_p, r(0), I);
  2969. ASSERT(!ERTS_PROC_IS_EXITING(c_p) ||
  2970. is_non_value(nif_bif_result));
  2971. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2972. PROCESS_MAIN_CHK_LOCKS(c_p);
  2973. }
  2974. break;
  2975. case 0:
  2976. {
  2977. Eterm (*bf)(Process*, BeamInstr*) = vbf;
  2978. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  2979. nif_bif_result = (*bf)(c_p, I);
  2980. ASSERT(!ERTS_PROC_IS_EXITING(c_p) ||
  2981. is_non_value(nif_bif_result));
  2982. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  2983. PROCESS_MAIN_CHK_LOCKS(c_p);
  2984. break;
  2985. }
  2986. default:
  2987. erl_exit(1, "apply_bif: invalid arity: %u\n",
  2988. bif_nif_arity);
  2989. }
  2990. apply_bif_or_nif_epilogue:
  2991. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  2992. ERTS_HOLE_CHECK(c_p);
  2993. if (c_p->mbuf) {
  2994. reg[0] = r(0);
  2995. nif_bif_result = erts_gc_after_bif_call(c_p, nif_bif_result,
  2996. reg, bif_nif_arity);
  2997. r(0) = reg[0];
  2998. }
  2999. SWAPIN; /* There might have been a garbage collection. */
  3000. FCALLS = c_p->fcalls;
  3001. if (is_value(nif_bif_result)) {
  3002. r(0) = nif_bif_result;
  3003. CHECK_TERM(r(0));
  3004. SET_I(c_p->cp);
  3005. Goto(*I);
  3006. } else if (c_p->freason == TRAP) {
  3007. SET_I(*((BeamInstr **) (UWord) ((c_p)->def_arg_reg + 3)));
  3008. r(0) = c_p->def_arg_reg[0];
  3009. x(1) = c_p->def_arg_reg[1];
  3010. x(2) = c_p->def_arg_reg[2];
  3011. Dispatch();
  3012. }
  3013. reg[0] = r(0);
  3014. I = handle_error(c_p, c_p->cp, reg, vbf);
  3015. goto post_error_handling;
  3016. }
  3017. }
  3018. OpCase(i_get_sd):
  3019. {
  3020. Eterm arg;
  3021. Eterm result;
  3022. GetArg1(0, arg);
  3023. result = erts_pd_hash_get(c_p, arg);
  3024. StoreBifResult(1, result);
  3025. }
  3026. {
  3027. Eterm case_end_val;
  3028. OpCase(case_end_x):
  3029. case_end_val = xb(Arg(0));
  3030. goto do_case_end;
  3031. OpCase(case_end_y):
  3032. case_end_val = yb(Arg(0));
  3033. goto do_case_end;
  3034. OpCase(case_end_r):
  3035. case_end_val = r(0);
  3036. do_case_end:
  3037. c_p->fvalue = case_end_val;
  3038. c_p->freason = EXC_CASE_CLAUSE;
  3039. goto find_func_info;
  3040. }
  3041. OpCase(if_end):
  3042. c_p->freason = EXC_IF_CLAUSE;
  3043. goto find_func_info;
  3044. OpCase(i_func_info_IaaI): {
  3045. c_p->freason = EXC_FUNCTION_CLAUSE;
  3046. c_p->current = I + 2;
  3047. goto lb_error_action_code;
  3048. }
  3049. OpCase(try_case_end_s):
  3050. {
  3051. Eterm try_case_end_val;
  3052. GetArg1(0, try_case_end_val);
  3053. c_p->fvalue = try_case_end_val;
  3054. c_p->freason = EXC_TRY_CLAUSE;
  3055. goto find_func_info;
  3056. }
  3057. /*
  3058. * Construction of binaries using new instructions.
  3059. */
  3060. {
  3061. Eterm new_binary;
  3062. Eterm num_bits_term;
  3063. Uint num_bits;
  3064. Uint alloc;
  3065. Uint num_bytes;
  3066. OpCase(i_bs_init_bits_heap_IIId): {
  3067. num_bits = Arg(0);
  3068. alloc = Arg(1);
  3069. I++;
  3070. goto do_bs_init_bits_known;
  3071. }
  3072. OpCase(i_bs_init_bits_IId): {
  3073. num_bits = Arg(0);
  3074. alloc = 0;
  3075. goto do_bs_init_bits_known;
  3076. }
  3077. OpCase(i_bs_init_bits_fail_heap_IjId): {
  3078. /* tmp_arg1 was fetched by an i_fetch instruction */
  3079. num_bits_term = tmp_arg1;
  3080. alloc = Arg(0);
  3081. I++;
  3082. goto do_bs_init_bits;
  3083. }
  3084. OpCase(i_bs_init_bits_fail_rjId): {
  3085. num_bits_term = r(0);
  3086. alloc = 0;
  3087. goto do_bs_init_bits;
  3088. }
  3089. OpCase(i_bs_init_bits_fail_yjId): {
  3090. num_bits_term = yb(Arg(0));
  3091. I++;
  3092. alloc = 0;
  3093. goto do_bs_init_bits;
  3094. }
  3095. OpCase(i_bs_init_bits_fail_xjId): {
  3096. num_bits_term = xb(Arg(0));
  3097. I++;
  3098. alloc = 0;
  3099. /* FALL THROUGH */
  3100. }
  3101. /* num_bits_term = Term for number of bits to build (small/big)
  3102. * alloc = Number of words to allocate on heap
  3103. * Operands: Fail Live Dst
  3104. */
  3105. do_bs_init_bits:
  3106. if (is_small(num_bits_term)) {
  3107. Sint size = signed_val(num_bits_term);
  3108. if (size < 0) {
  3109. goto badarg;
  3110. }
  3111. num_bits = (Uint) size;
  3112. } else {
  3113. Uint bits;
  3114. if (!term_to_Uint(num_bits_term, &bits)) {
  3115. c_p->freason = bits;
  3116. goto lb_Cl_error;
  3117. }
  3118. num_bits = (Eterm) bits;
  3119. }
  3120. /* num_bits = Number of bits to build
  3121. * alloc = Number of extra words to allocate on heap
  3122. * Operands: NotUsed Live Dst
  3123. */
  3124. do_bs_init_bits_known:
  3125. num_bytes = (num_bits+7) >> 3;
  3126. if (num_bits & 7) {
  3127. alloc += ERL_SUB_BIN_SIZE;
  3128. }
  3129. if (num_bytes <= ERL_ONHEAP_BIN_LIMIT) {
  3130. alloc += heap_bin_size(num_bytes);
  3131. } else {
  3132. alloc += PROC_BIN_SIZE;
  3133. }
  3134. TestHeap(alloc, Arg(1));
  3135. /* num_bits = Number of bits to build
  3136. * num_bytes = Number of bytes to allocate in the binary
  3137. * alloc = Total number of words to allocate on heap
  3138. * Operands: NotUsed NotUsed Dst
  3139. */
  3140. if (num_bytes <= ERL_ONHEAP_BIN_LIMIT) {
  3141. ErlHeapBin* hb;
  3142. erts_bin_offset = 0;
  3143. erts_writable_bin = 0;
  3144. hb = (ErlHeapBin *) HTOP;
  3145. HTOP += heap_bin_size(num_bytes);
  3146. hb->thing_word = header_heap_bin(num_bytes);
  3147. hb->size = num_bytes;
  3148. erts_current_bin = (byte *) hb->data;
  3149. new_binary = make_binary(hb);
  3150. do_bits_sub_bin:
  3151. if (num_bits & 7) {
  3152. ErlSubBin* sb;
  3153. sb = (ErlSubBin *) HTOP;
  3154. HTOP += ERL_SUB_BIN_SIZE;
  3155. sb->thing_word = HEADER_SUB_BIN;
  3156. sb->size = num_bytes - 1;
  3157. sb->bitsize = num_bits & 7;
  3158. sb->offs = 0;
  3159. sb->bitoffs = 0;
  3160. sb->is_writable = 0;
  3161. sb->orig = new_binary;
  3162. new_binary = make_binary(sb);
  3163. }
  3164. HEAP_SPACE_VERIFIED(0);
  3165. StoreBifResult(2, new_binary);
  3166. } else {
  3167. Binary* bptr;
  3168. ProcBin* pb;
  3169. erts_bin_offset = 0;
  3170. erts_writable_bin = 0;
  3171. /*
  3172. * Allocate the binary struct itself.
  3173. */
  3174. bptr = erts_bin_nrml_alloc(num_bytes);
  3175. bptr->flags = 0;
  3176. bptr->orig_size = num_bytes;
  3177. erts_refc_init(&bptr->refc, 1);
  3178. erts_current_bin = (byte *) bptr->orig_bytes;
  3179. /*
  3180. * Now allocate the ProcBin on the heap.
  3181. */
  3182. pb = (ProcBin *) HTOP;
  3183. HTOP += PROC_BIN_SIZE;
  3184. pb->thing_word = HEADER_PROC_BIN;
  3185. pb->size = num_bytes;
  3186. pb->next = MSO(c_p).first;
  3187. MSO(c_p).first = (struct erl_off_heap_header*) pb;
  3188. pb->val = bptr;
  3189. pb->bytes = (byte*) bptr->orig_bytes;
  3190. pb->flags = 0;
  3191. OH_OVERHEAD(&(MSO(c_p)), pb->size / sizeof(Eterm));
  3192. new_binary = make_binary(pb);
  3193. goto do_bits_sub_bin;
  3194. }
  3195. }
  3196. {
  3197. OpCase(i_bs_init_fail_heap_IjId): {
  3198. /* tmp_arg1 was fetched by an i_fetch instruction */
  3199. tmp_arg2 = Arg(0);
  3200. I++;
  3201. goto do_bs_init;
  3202. }
  3203. OpCase(i_bs_init_fail_rjId): {
  3204. tmp_arg1 = r(0);
  3205. tmp_arg2 = 0;
  3206. goto do_bs_init;
  3207. }
  3208. OpCase(i_bs_init_fail_yjId): {
  3209. tmp_arg1 = yb(Arg(0));
  3210. tmp_arg2 = 0;
  3211. I++;
  3212. goto do_bs_init;
  3213. }
  3214. OpCase(i_bs_init_fail_xjId): {
  3215. tmp_arg1 = xb(Arg(0));
  3216. tmp_arg2 = 0;
  3217. I++;
  3218. }
  3219. /* FALL THROUGH */
  3220. do_bs_init:
  3221. if (is_small(tmp_arg1)) {
  3222. Sint size = signed_val(tmp_arg1);
  3223. if (size < 0) {
  3224. goto badarg;
  3225. }
  3226. tmp_arg1 = (Eterm) size;
  3227. } else {
  3228. Uint bytes;
  3229. if (!term_to_Uint(tmp_arg1, &bytes)) {
  3230. c_p->freason = bytes;
  3231. goto lb_Cl_error;
  3232. }
  3233. if ((bytes >> (8*sizeof(Uint)-3)) != 0) {
  3234. goto system_limit;
  3235. }
  3236. tmp_arg1 = (Eterm) bytes;
  3237. }
  3238. if (tmp_arg1 <= ERL_ONHEAP_BIN_LIMIT) {
  3239. goto do_heap_bin_alloc;
  3240. } else {
  3241. goto do_proc_bin_alloc;
  3242. }
  3243. OpCase(i_bs_init_heap_IIId): {
  3244. tmp_arg1 = Arg(0);
  3245. tmp_arg2 = Arg(1);
  3246. I++;
  3247. goto do_proc_bin_alloc;
  3248. }
  3249. OpCase(i_bs_init_IId): {
  3250. tmp_arg1 = Arg(0);
  3251. tmp_arg2 = 0;
  3252. }
  3253. /* FALL THROUGH */
  3254. do_proc_bin_alloc: {
  3255. Binary* bptr;
  3256. ProcBin* pb;
  3257. erts_bin_offset = 0;
  3258. erts_writable_bin = 0;
  3259. TestBinVHeap(tmp_arg1 / sizeof(Eterm),
  3260. tmp_arg2 + PROC_BIN_SIZE + ERL_SUB_BIN_SIZE, Arg(1));
  3261. /*
  3262. * Allocate the binary struct itself.
  3263. */
  3264. bptr = erts_bin_nrml_alloc(tmp_arg1);
  3265. bptr->flags = 0;
  3266. bptr->orig_size = tmp_arg1;
  3267. erts_refc_init(&bptr->refc, 1);
  3268. erts_current_bin = (byte *) bptr->orig_bytes;
  3269. /*
  3270. * Now allocate the ProcBin on the heap.
  3271. */
  3272. pb = (ProcBin *) HTOP;
  3273. HTOP += PROC_BIN_SIZE;
  3274. pb->thing_word = HEADER_PROC_BIN;
  3275. pb->size = tmp_arg1;
  3276. pb->next = MSO(c_p).first;
  3277. MSO(c_p).first = (struct erl_off_heap_header*) pb;
  3278. pb->val = bptr;
  3279. pb->bytes = (byte*) bptr->orig_bytes;
  3280. pb->flags = 0;
  3281. OH_OVERHEAD(&(MSO(c_p)), tmp_arg1 / sizeof(Eterm));
  3282. StoreBifResult(2, make_binary(pb));
  3283. }
  3284. OpCase(i_bs_init_heap_bin_heap_IIId): {
  3285. tmp_arg1 = Arg(0);
  3286. tmp_arg2 = Arg(1);
  3287. I++;
  3288. goto do_heap_bin_alloc;
  3289. }
  3290. OpCase(i_bs_init_heap_bin_IId): {
  3291. tmp_arg1 = Arg(0);
  3292. tmp_arg2 = 0;
  3293. }
  3294. /* Fall through */
  3295. do_heap_bin_alloc:
  3296. {
  3297. ErlHeapBin* hb;
  3298. Uint bin_need;
  3299. bin_need = heap_bin_size(tmp_arg1);
  3300. erts_bin_offset = 0;
  3301. erts_writable_bin = 0;
  3302. TestHeap(bin_need+tmp_arg2+ERL_SUB_BIN_SIZE, Arg(1));
  3303. hb = (ErlHeapBin *) HTOP;
  3304. HTOP += bin_need;
  3305. hb->thing_word = header_heap_bin(tmp_arg1);
  3306. hb->size = tmp_arg1;
  3307. erts_current_bin = (byte *) hb->data;
  3308. tmp_arg1 = make_binary(hb);
  3309. StoreBifResult(2, tmp_arg1);
  3310. }
  3311. }
  3312. OpCase(i_bs_add_jId): {
  3313. Uint Unit = Arg(1);
  3314. if (is_both_small(tmp_arg1, tmp_arg2)) {
  3315. Sint Arg1 = signed_val(tmp_arg1);
  3316. Sint Arg2 = signed_val(tmp_arg2);
  3317. if (Arg1 >= 0 && Arg2 >= 0) {
  3318. BsSafeMul(Arg2, Unit, goto system_limit, tmp_arg1);
  3319. tmp_arg1 += Arg1;
  3320. store_bs_add_result:
  3321. if (MY_IS_SSMALL((Sint) tmp_arg1)) {
  3322. tmp_arg1 = make_small(tmp_arg1);
  3323. } else {
  3324. /*
  3325. * May generate a heap fragment, but in this
  3326. * particular case it is OK, since the value will be
  3327. * stored into an x register (the GC will scan x
  3328. * registers for references to heap fragments) and
  3329. * there is no risk that value can be stored into a
  3330. * location that is not scanned for heap-fragment
  3331. * references (such as the heap).
  3332. */
  3333. SWAPOUT;
  3334. tmp_arg1 = erts_make_integer(tmp_arg1, c_p);
  3335. HTOP = HEAP_TOP(c_p);
  3336. }
  3337. StoreBifResult(2, tmp_arg1);
  3338. }
  3339. goto badarg;
  3340. } else {
  3341. Uint a;
  3342. Uint b;
  3343. Uint c;
  3344. /*
  3345. * Now we know that one of the arguments is
  3346. * not a small. We must convert both arguments
  3347. * to Uints and check for errors at the same time.
  3348. *
  3349. * Error checking is tricky.
  3350. *
  3351. * If one of the arguments is not numeric or
  3352. * not positive, the error reason is BADARG.
  3353. *
  3354. * Otherwise if both arguments are numeric,
  3355. * but at least one argument does not fit in
  3356. * an Uint, the reason is SYSTEM_LIMIT.
  3357. */
  3358. if (!term_to_Uint(tmp_arg1, &a)) {
  3359. if (a == BADARG) {
  3360. goto badarg;
  3361. }
  3362. if (!term_to_Uint(tmp_arg2, &b)) {
  3363. c_p->freason = b;
  3364. goto lb_Cl_error;
  3365. }
  3366. goto system_limit;
  3367. } else if (!term_to_Uint(tmp_arg2, &b)) {
  3368. c_p->freason = b;
  3369. goto lb_Cl_error;
  3370. }
  3371. /*
  3372. * The arguments are now correct and stored in a and b.
  3373. */
  3374. BsSafeMul(b, Unit, goto system_limit, c);
  3375. tmp_arg1 = a + c;
  3376. if (tmp_arg1 < a) {
  3377. /*
  3378. * If the result is less than one of the
  3379. * arguments, there must have been an overflow.
  3380. */
  3381. goto system_limit;
  3382. }
  3383. goto store_bs_add_result;
  3384. }
  3385. /* No fallthrough */
  3386. ASSERT(0);
  3387. }
  3388. OpCase(bs_put_string_II):
  3389. {
  3390. BeamInstr *next;
  3391. PreFetch(2, next);
  3392. erts_new_bs_put_string(ERL_BITS_ARGS_2((byte *) Arg(1), Arg(0)));
  3393. NextPF(2, next);
  3394. }
  3395. /*
  3396. * tmp_arg1 = Number of bytes to build
  3397. * tmp_arg2 = Source binary
  3398. * Operands: Fail ExtraHeap Live Unit Dst
  3399. */
  3400. OpCase(i_bs_append_jIIId): {
  3401. Uint live = Arg(2);
  3402. Uint res;
  3403. SWAPOUT;
  3404. reg[0] = r(0);
  3405. reg[live] = tmp_arg2;
  3406. res = erts_bs_append(c_p, reg, live, tmp_arg1, Arg(1), Arg(3));
  3407. r(0) = reg[0];
  3408. SWAPIN;
  3409. if (is_non_value(res)) {
  3410. /* c_p->freason is already set (may be either BADARG or SYSTEM_LIMIT). */
  3411. goto lb_Cl_error;
  3412. }
  3413. StoreBifResult(4, res);
  3414. }
  3415. /*
  3416. * tmp_arg1 = Number of bytes to build
  3417. * tmp_arg2 = Source binary
  3418. * Operands: Fail Unit Dst
  3419. */
  3420. OpCase(i_bs_private_append_jId): {
  3421. Eterm res;
  3422. res = erts_bs_private_append(c_p, tmp_arg2, tmp_arg1, Arg(1));
  3423. if (is_non_value(res)) {
  3424. /* c_p->freason is already set (may be either BADARG or SYSTEM_LIMIT). */
  3425. goto lb_Cl_error;
  3426. }
  3427. StoreBifResult(2, res);
  3428. }
  3429. /*
  3430. * tmp_arg1 = Initial size of writable binary
  3431. * Operands: Live Dst
  3432. */
  3433. OpCase(bs_init_writable): {
  3434. SWAPOUT;
  3435. r(0) = erts_bs_init_writable(c_p, r(0));
  3436. SWAPIN;
  3437. Next(0);
  3438. }
  3439. /*
  3440. * Calculate the number of bytes needed to encode the source
  3441. * operarand to UTF-8. If the source operand is invalid (e.g. wrong
  3442. * type or range) we return a nonsense integer result (0 or 4). We
  3443. * can get away with that because we KNOW that bs_put_utf8 will do
  3444. * full error checking.
  3445. */
  3446. OpCase(i_bs_utf8_size_sd): {
  3447. Eterm arg;
  3448. Eterm result;
  3449. GetArg1(0, arg);
  3450. if (arg < make_small(0x80UL)) {
  3451. result = make_small(1);
  3452. } else if (arg < make_small(0x800UL)) {
  3453. result = make_small(2);
  3454. } else if (arg < make_small(0x10000UL)) {
  3455. result = make_small(3);
  3456. } else {
  3457. result = make_small(4);
  3458. }
  3459. StoreBifResult(1, result);
  3460. }
  3461. OpCase(i_bs_put_utf8_js): {
  3462. Eterm arg;
  3463. GetArg1(1, arg);
  3464. if (!erts_bs_put_utf8(ERL_BITS_ARGS_1(arg))) {
  3465. goto badarg;
  3466. }
  3467. Next(2);
  3468. }
  3469. /*
  3470. * Calculate the number of bytes needed to encode the source
  3471. * operarand to UTF-8. If the source operand is invalid (e.g. wrong
  3472. * type or range) we return a nonsense integer result (2 or 4). We
  3473. * can get away with that because we KNOW that bs_put_utf16 will do
  3474. * full error checking.
  3475. */
  3476. OpCase(i_bs_utf16_size_sd): {
  3477. Eterm arg;
  3478. Eterm result = make_small(2);
  3479. GetArg1(0, arg);
  3480. if (arg >= make_small(0x10000UL)) {
  3481. result = make_small(4);
  3482. }
  3483. StoreBifResult(1, result);
  3484. }
  3485. OpCase(i_bs_put_utf16_jIs): {
  3486. Eterm arg;
  3487. GetArg1(2, arg);
  3488. if (!erts_bs_put_utf16(ERL_BITS_ARGS_2(arg, Arg(1)))) {
  3489. goto badarg;
  3490. }
  3491. Next(3);
  3492. }
  3493. /*
  3494. * Only used for validating a value about to be stored in a binary.
  3495. */
  3496. OpCase(i_bs_validate_unicode_js): {
  3497. Eterm val;
  3498. GetArg1(1, val);
  3499. /*
  3500. * There is no need to untag the integer, but it IS necessary
  3501. * to make sure it is small (if the term is a bignum, it could
  3502. * slip through the test, and there is no further test that
  3503. * would catch it, since bit syntax construction silently masks
  3504. * too big numbers).
  3505. */
  3506. if (is_not_small(val) || val > make_small(0x10FFFFUL) ||
  3507. (make_small(0xD800UL) <= val && val <= make_small(0xDFFFUL)) ||
  3508. val == make_small(0xFFFEUL) || val == make_small(0xFFFFUL)) {
  3509. goto badarg;
  3510. }
  3511. Next(2);
  3512. }
  3513. /*
  3514. * Only used for validating a value matched out.
  3515. *
  3516. * tmp_arg1 = Integer to validate
  3517. * tmp_arg2 = Match context
  3518. */
  3519. OpCase(i_bs_validate_unicode_retract_j): {
  3520. /*
  3521. * There is no need to untag the integer, but it IS necessary
  3522. * to make sure it is small (a bignum pointer could fall in
  3523. * the valid range).
  3524. */
  3525. if (is_not_small(tmp_arg1) || tmp_arg1 > make_small(0x10FFFFUL) ||
  3526. (make_small(0xD800UL) <= tmp_arg1 && tmp_arg1 <= make_small(0xDFFFUL)) ||
  3527. tmp_arg1 == make_small(0xFFFEUL) || tmp_arg1 == make_small(0xFFFFUL)) {
  3528. ErlBinMatchBuffer *mb = ms_matchbuffer(tmp_arg2);
  3529. mb->offset -= 32;
  3530. goto badarg;
  3531. }
  3532. Next(1);
  3533. }
  3534. /*
  3535. * Matching of binaries.
  3536. */
  3537. {
  3538. Eterm header;
  3539. BeamInstr *next;
  3540. Uint slots;
  3541. Eterm context;
  3542. OpCase(i_bs_start_match2_rfIId): {
  3543. context = r(0);
  3544. do_start_match:
  3545. slots = Arg(2);
  3546. if (!is_boxed(context)) {
  3547. ClauseFail();
  3548. }
  3549. PreFetch(4, next);
  3550. header = *boxed_val(context);
  3551. if (header_is_bin_matchstate(header)) {
  3552. ErlBinMatchState* ms = (ErlBinMatchState *) boxed_val(context);
  3553. Uint actual_slots = HEADER_NUM_SLOTS(header);
  3554. ms->save_offset[0] = ms->mb.offset;
  3555. if (actual_slots < slots) {
  3556. ErlBinMatchState* dst;
  3557. Uint live = Arg(1);
  3558. Uint wordsneeded = ERL_BIN_MATCHSTATE_SIZE(slots);
  3559. TestHeapPreserve(wordsneeded, live, context);
  3560. ms = (ErlBinMatchState *) boxed_val(context);
  3561. dst = (ErlBinMatchState *) HTOP;
  3562. *dst = *ms;
  3563. *HTOP = HEADER_BIN_MATCHSTATE(slots);
  3564. HTOP += wordsneeded;
  3565. HEAP_SPACE_VERIFIED(0);
  3566. StoreResult(make_matchstate(dst), Arg(3));
  3567. }
  3568. } else if (is_binary_header(header)) {
  3569. Eterm result;
  3570. Uint live = Arg(1);
  3571. Uint wordsneeded = ERL_BIN_MATCHSTATE_SIZE(slots);
  3572. TestHeapPreserve(wordsneeded, live, context);
  3573. HEAP_TOP(c_p) = HTOP;
  3574. #ifdef DEBUG
  3575. c_p->stop = E; /* Needed for checking in HeapOnlyAlloc(). */
  3576. #endif
  3577. result = erts_bs_start_match_2(c_p, context, slots);
  3578. HTOP = HEAP_TOP(c_p);
  3579. HEAP_SPACE_VERIFIED(0);
  3580. if (is_non_value(result)) {
  3581. ClauseFail();
  3582. } else {
  3583. StoreResult(result, Arg(3));
  3584. }
  3585. } else {
  3586. ClauseFail();
  3587. }
  3588. NextPF(4, next);
  3589. }
  3590. OpCase(i_bs_start_match2_xfIId): {
  3591. context = xb(Arg(0));
  3592. I++;
  3593. goto do_start_match;
  3594. }
  3595. OpCase(i_bs_start_match2_yfIId): {
  3596. context = yb(Arg(0));
  3597. I++;
  3598. goto do_start_match;
  3599. }
  3600. }
  3601. OpCase(bs_test_zero_tail2_fr): {
  3602. BeamInstr *next;
  3603. ErlBinMatchBuffer *_mb;
  3604. PreFetch(1, next);
  3605. _mb = (ErlBinMatchBuffer*) ms_matchbuffer(r(0));
  3606. if (_mb->size != _mb->offset) {
  3607. ClauseFail();
  3608. }
  3609. NextPF(1, next);
  3610. }
  3611. OpCase(bs_test_zero_tail2_fx): {
  3612. BeamInstr *next;
  3613. ErlBinMatchBuffer *_mb;
  3614. PreFetch(2, next);
  3615. _mb = (ErlBinMatchBuffer*) ms_matchbuffer(xb(Arg(1)));
  3616. if (_mb->size != _mb->offset) {
  3617. ClauseFail();
  3618. }
  3619. NextPF(2, next);
  3620. }
  3621. OpCase(bs_test_tail_imm2_frI): {
  3622. BeamInstr *next;
  3623. ErlBinMatchBuffer *_mb;
  3624. PreFetch(2, next);
  3625. _mb = ms_matchbuffer(r(0));
  3626. if (_mb->size - _mb->offset != Arg(1)) {
  3627. ClauseFail();
  3628. }
  3629. NextPF(2, next);
  3630. }
  3631. OpCase(bs_test_tail_imm2_fxI): {
  3632. BeamInstr *next;
  3633. ErlBinMatchBuffer *_mb;
  3634. PreFetch(3, next);
  3635. _mb = ms_matchbuffer(xb(Arg(1)));
  3636. if (_mb->size - _mb->offset != Arg(2)) {
  3637. ClauseFail();
  3638. }
  3639. NextPF(3, next);
  3640. }
  3641. OpCase(bs_test_unit_frI): {
  3642. BeamInstr *next;
  3643. ErlBinMatchBuffer *_mb;
  3644. PreFetch(2, next);
  3645. _mb = ms_matchbuffer(r(0));
  3646. if ((_mb->size - _mb->offset) % Arg(1)) {
  3647. ClauseFail();
  3648. }
  3649. NextPF(2, next);
  3650. }
  3651. OpCase(bs_test_unit_fxI): {
  3652. BeamInstr *next;
  3653. ErlBinMatchBuffer *_mb;
  3654. PreFetch(3, next);
  3655. _mb = ms_matchbuffer(xb(Arg(1)));
  3656. if ((_mb->size - _mb->offset) % Arg(2)) {
  3657. ClauseFail();
  3658. }
  3659. NextPF(3, next);
  3660. }
  3661. OpCase(bs_test_unit8_fr): {
  3662. BeamInstr *next;
  3663. ErlBinMatchBuffer *_mb;
  3664. PreFetch(1, next);
  3665. _mb = ms_matchbuffer(r(0));
  3666. if ((_mb->size - _mb->offset) & 7) {
  3667. ClauseFail();
  3668. }
  3669. NextPF(1, next);
  3670. }
  3671. OpCase(bs_test_unit8_fx): {
  3672. BeamInstr *next;
  3673. ErlBinMatchBuffer *_mb;
  3674. PreFetch(2, next);
  3675. _mb = ms_matchbuffer(xb(Arg(1)));
  3676. if ((_mb->size - _mb->offset) & 7) {
  3677. ClauseFail();
  3678. }
  3679. NextPF(2, next);
  3680. }
  3681. {
  3682. Eterm bs_get_integer8_context;
  3683. OpCase(i_bs_get_integer_8_rfd): {
  3684. bs_get_integer8_context = r(0);
  3685. goto do_bs_get_integer_8;
  3686. }
  3687. OpCase(i_bs_get_integer_8_xfd): {
  3688. bs_get_integer8_context = xb(Arg(0));
  3689. I++;
  3690. }
  3691. do_bs_get_integer_8: {
  3692. ErlBinMatchBuffer *_mb;
  3693. Eterm _result;
  3694. _mb = ms_matchbuffer(bs_get_integer8_context);
  3695. if (_mb->size - _mb->offset < 8) {
  3696. ClauseFail();
  3697. }
  3698. if (BIT_OFFSET(_mb->offset) != 0) {
  3699. _result = erts_bs_get_integer_2(c_p, 8, 0, _mb);
  3700. } else {
  3701. _result = make_small(_mb->base[BYTE_OFFSET(_mb->offset)]);
  3702. _mb->offset += 8;
  3703. }
  3704. StoreBifResult(1, _result);
  3705. }
  3706. }
  3707. {
  3708. Eterm bs_get_integer_16_context;
  3709. OpCase(i_bs_get_integer_16_rfd):
  3710. bs_get_integer_16_context = r(0);
  3711. goto do_bs_get_integer_16;
  3712. OpCase(i_bs_get_integer_16_xfd):
  3713. bs_get_integer_16_context = xb(Arg(0));
  3714. I++;
  3715. do_bs_get_integer_16:
  3716. {
  3717. ErlBinMatchBuffer *_mb;
  3718. Eterm _result;
  3719. _mb = ms_matchbuffer(bs_get_integer_16_context);
  3720. if (_mb->size - _mb->offset < 16) {
  3721. ClauseFail();
  3722. }
  3723. if (BIT_OFFSET(_mb->offset) != 0) {
  3724. _result = erts_bs_get_integer_2(c_p, 16, 0, _mb);
  3725. } else {
  3726. _result = make_small(get_int16(_mb->base+BYTE_OFFSET(_mb->offset)));
  3727. _mb->offset += 16;
  3728. }
  3729. StoreBifResult(1, _result);
  3730. }
  3731. }
  3732. {
  3733. Eterm bs_get_integer_32_context;
  3734. OpCase(i_bs_get_integer_32_rfId):
  3735. bs_get_integer_32_context = r(0);
  3736. goto do_bs_get_integer_32;
  3737. OpCase(i_bs_get_integer_32_xfId):
  3738. bs_get_integer_32_context = xb(Arg(0));
  3739. I++;
  3740. do_bs_get_integer_32:
  3741. {
  3742. ErlBinMatchBuffer *_mb;
  3743. Uint32 _integer;
  3744. Eterm _result;
  3745. _mb = ms_matchbuffer(bs_get_integer_32_context);
  3746. if (_mb->size - _mb->offset < 32) { ClauseFail(); }
  3747. if (BIT_OFFSET(_mb->offset) != 0) {
  3748. _integer = erts_bs_get_unaligned_uint32(_mb);
  3749. } else {
  3750. _integer = get_int32(_mb->base + _mb->offset/8);
  3751. }
  3752. _mb->offset += 32;
  3753. #if !defined(ARCH_64) || HALFWORD_HEAP
  3754. if (IS_USMALL(0, _integer)) {
  3755. #endif
  3756. _result = make_small(_integer);
  3757. #if !defined(ARCH_64) || HALFWORD_HEAP
  3758. } else {
  3759. TestHeap(BIG_UINT_HEAP_SIZE, Arg(1));
  3760. _result = uint_to_big((Uint) _integer, HTOP);
  3761. HTOP += BIG_UINT_HEAP_SIZE;
  3762. HEAP_SPACE_VERIFIED(0);
  3763. }
  3764. #endif
  3765. StoreBifResult(2, _result);
  3766. }
  3767. }
  3768. /* Operands: Size Live Fail Flags Dst */
  3769. OpCase(i_bs_get_integer_imm_rIIfId): {
  3770. tmp_arg1 = r(0);
  3771. /* Operands: Size Live Fail Flags Dst */
  3772. goto do_bs_get_integer_imm_test_heap;
  3773. }
  3774. /* Operands: x(Reg) Size Live Fail Flags Dst */
  3775. OpCase(i_bs_get_integer_imm_xIIfId): {
  3776. tmp_arg1 = xb(Arg(0));
  3777. I++;
  3778. /* Operands: Size Live Fail Flags Dst */
  3779. goto do_bs_get_integer_imm_test_heap;
  3780. }
  3781. /*
  3782. * tmp_arg1 = match context
  3783. * Operands: Size Live Fail Flags Dst
  3784. */
  3785. do_bs_get_integer_imm_test_heap: {
  3786. Uint wordsneeded;
  3787. tmp_arg2 = Arg(0);
  3788. wordsneeded = 1+WSIZE(NBYTES(tmp_arg2));
  3789. TestHeapPreserve(wordsneeded, Arg(1), tmp_arg1);
  3790. I += 2;
  3791. /* Operands: Fail Flags Dst */
  3792. goto do_bs_get_integer_imm;
  3793. }
  3794. /* Operands: Size Fail Flags Dst */
  3795. OpCase(i_bs_get_integer_small_imm_rIfId): {
  3796. tmp_arg1 = r(0);
  3797. tmp_arg2 = Arg(0);
  3798. I++;
  3799. /* Operands: Fail Flags Dst */
  3800. goto do_bs_get_integer_imm;
  3801. }
  3802. /* Operands: x(Reg) Size Fail Flags Dst */
  3803. OpCase(i_bs_get_integer_small_imm_xIfId): {
  3804. tmp_arg1 = xb(Arg(0));
  3805. tmp_arg2 = Arg(1);
  3806. I += 2;
  3807. /* Operands: Fail Flags Dst */
  3808. goto do_bs_get_integer_imm;
  3809. }
  3810. /*
  3811. * tmp_arg1 = match context
  3812. * tmp_arg2 = size of field
  3813. * Operands: Fail Flags Dst
  3814. */
  3815. do_bs_get_integer_imm: {
  3816. ErlBinMatchBuffer* mb;
  3817. Eterm result;
  3818. mb = ms_matchbuffer(tmp_arg1);
  3819. LIGHT_SWAPOUT;
  3820. result = erts_bs_get_integer_2(c_p, tmp_arg2, Arg(1), mb);
  3821. LIGHT_SWAPIN;
  3822. HEAP_SPACE_VERIFIED(0);
  3823. if (is_non_value(result)) {
  3824. ClauseFail();
  3825. }
  3826. StoreBifResult(2, result);
  3827. }
  3828. /*
  3829. * tmp_arg1 = Match context
  3830. * tmp_arg2 = Size field
  3831. * Operands: Fail Live FlagsAndUnit Dst
  3832. */
  3833. OpCase(i_bs_get_integer_fIId): {
  3834. Uint flags;
  3835. Uint size;
  3836. ErlBinMatchBuffer* mb;
  3837. Eterm result;
  3838. flags = Arg(2);
  3839. BsGetFieldSize(tmp_arg2, (flags >> 3), ClauseFail(), size);
  3840. if (size >= SMALL_BITS) {
  3841. Uint wordsneeded = 1+WSIZE(NBYTES((Uint) size));
  3842. TestHeapPreserve(wordsneeded, Arg(1), tmp_arg1);
  3843. }
  3844. mb = ms_matchbuffer(tmp_arg1);
  3845. LIGHT_SWAPOUT;
  3846. result = erts_bs_get_integer_2(c_p, size, flags, mb);
  3847. LIGHT_SWAPIN;
  3848. HEAP_SPACE_VERIFIED(0);
  3849. if (is_non_value(result)) {
  3850. ClauseFail();
  3851. }
  3852. StoreBifResult(3, result);
  3853. }
  3854. {
  3855. Eterm get_utf8_context;
  3856. /* Operands: MatchContext Fail Dst */
  3857. OpCase(i_bs_get_utf8_rfd): {
  3858. get_utf8_context = r(0);
  3859. goto do_bs_get_utf8;
  3860. }
  3861. OpCase(i_bs_get_utf8_xfd): {
  3862. get_utf8_context = xb(Arg(0));
  3863. I++;
  3864. }
  3865. /*
  3866. * get_utf8_context = match_context
  3867. * Operands: Fail Dst
  3868. */
  3869. do_bs_get_utf8: {
  3870. Eterm result = erts_bs_get_utf8(ms_matchbuffer(get_utf8_context));
  3871. if (is_non_value(result)) {
  3872. ClauseFail();
  3873. }
  3874. StoreBifResult(1, result);
  3875. }
  3876. }
  3877. {
  3878. Eterm get_utf16_context;
  3879. /* Operands: MatchContext Fail Flags Dst */
  3880. OpCase(i_bs_get_utf16_rfId): {
  3881. get_utf16_context = r(0);
  3882. goto do_bs_get_utf16;
  3883. }
  3884. OpCase(i_bs_get_utf16_xfId): {
  3885. get_utf16_context = xb(Arg(0));
  3886. I++;
  3887. }
  3888. /*
  3889. * get_utf16_context = match_context
  3890. * Operands: Fail Flags Dst
  3891. */
  3892. do_bs_get_utf16: {
  3893. Eterm result = erts_bs_get_utf16(ms_matchbuffer(get_utf16_context),
  3894. Arg(1));
  3895. if (is_non_value(result)) {
  3896. ClauseFail();
  3897. }
  3898. StoreBifResult(2, result);
  3899. }
  3900. }
  3901. {
  3902. Eterm context_to_binary_context;
  3903. ErlBinMatchBuffer* mb;
  3904. ErlSubBin* sb;
  3905. Uint size;
  3906. Uint offs;
  3907. Uint orig;
  3908. Uint hole_size;
  3909. OpCase(bs_context_to_binary_r): {
  3910. context_to_binary_context = x0;
  3911. I -= 2;
  3912. goto do_context_to_binary;
  3913. }
  3914. /* Unfortunately, inlining can generate this instruction. */
  3915. OpCase(bs_context_to_binary_y): {
  3916. context_to_binary_context = yb(Arg(0));
  3917. goto do_context_to_binary0;
  3918. }
  3919. OpCase(bs_context_to_binary_x): {
  3920. context_to_binary_context = xb(Arg(0));
  3921. do_context_to_binary0:
  3922. I--;
  3923. }
  3924. do_context_to_binary:
  3925. if (is_boxed(context_to_binary_context) &&
  3926. header_is_bin_matchstate(*boxed_val(context_to_binary_context))) {
  3927. ErlBinMatchState* ms;
  3928. ms = (ErlBinMatchState *) boxed_val(context_to_binary_context);
  3929. mb = &ms->mb;
  3930. offs = ms->save_offset[0];
  3931. size = mb->size - offs;
  3932. goto do_bs_get_binary_all_reuse_common;
  3933. }
  3934. Next(2);
  3935. OpCase(i_bs_get_binary_all_reuse_rfI): {
  3936. context_to_binary_context = x0;
  3937. goto do_bs_get_binary_all_reuse;
  3938. }
  3939. OpCase(i_bs_get_binary_all_reuse_xfI): {
  3940. context_to_binary_context = xb(Arg(0));
  3941. I++;
  3942. }
  3943. do_bs_get_binary_all_reuse:
  3944. mb = ms_matchbuffer(context_to_binary_context);
  3945. size = mb->size - mb->offset;
  3946. if (size % Arg(1) != 0) {
  3947. ClauseFail();
  3948. }
  3949. offs = mb->offset;
  3950. do_bs_get_binary_all_reuse_common:
  3951. orig = mb->orig;
  3952. sb = (ErlSubBin *) boxed_val(context_to_binary_context);
  3953. hole_size = 1 + header_arity(sb->thing_word) - ERL_SUB_BIN_SIZE;
  3954. sb->thing_word = HEADER_SUB_BIN;
  3955. sb->size = BYTE_OFFSET(size);
  3956. sb->bitsize = BIT_OFFSET(size);
  3957. sb->offs = BYTE_OFFSET(offs);
  3958. sb->bitoffs = BIT_OFFSET(offs);
  3959. sb->is_writable = 0;
  3960. sb->orig = orig;
  3961. if (hole_size) {
  3962. sb[1].thing_word = make_pos_bignum_header(hole_size-1);
  3963. }
  3964. Next(2);
  3965. }
  3966. {
  3967. Eterm match_string_context;
  3968. OpCase(i_bs_match_string_rfII): {
  3969. match_string_context = r(0);
  3970. goto do_bs_match_string;
  3971. }
  3972. OpCase(i_bs_match_string_xfII): {
  3973. match_string_context = xb(Arg(0));
  3974. I++;
  3975. }
  3976. do_bs_match_string:
  3977. {
  3978. BeamInstr *next;
  3979. byte* bytes;
  3980. Uint bits;
  3981. ErlBinMatchBuffer* mb;
  3982. Uint offs;
  3983. PreFetch(3, next);
  3984. bits = Arg(1);
  3985. bytes = (byte *) Arg(2);
  3986. mb = ms_matchbuffer(match_string_context);
  3987. if (mb->size - mb->offset < bits) {
  3988. ClauseFail();
  3989. }
  3990. offs = mb->offset & 7;
  3991. if (offs == 0 && (bits & 7) == 0) {
  3992. if (sys_memcmp(bytes, mb->base+(mb->offset>>3), bits>>3)) {
  3993. ClauseFail();
  3994. }
  3995. } else if (erts_cmp_bits(bytes, 0, mb->base+(mb->offset>>3), mb->offset & 7, bits)) {
  3996. ClauseFail();
  3997. }
  3998. mb->offset += bits;
  3999. NextPF(3, next);
  4000. }
  4001. }
  4002. OpCase(i_bs_save2_rI): {
  4003. BeamInstr *next;
  4004. ErlBinMatchState *_ms;
  4005. PreFetch(1, next);
  4006. _ms = (ErlBinMatchState*) boxed_val((Eterm) r(0));
  4007. _ms->save_offset[Arg(0)] = _ms->mb.offset;
  4008. NextPF(1, next);
  4009. }
  4010. OpCase(i_bs_save2_xI): {
  4011. BeamInstr *next;
  4012. ErlBinMatchState *_ms;
  4013. PreFetch(2, next);
  4014. _ms = (ErlBinMatchState*) boxed_val((Eterm) xb(Arg(0)));
  4015. _ms->save_offset[Arg(1)] = _ms->mb.offset;
  4016. NextPF(2, next);
  4017. }
  4018. OpCase(i_bs_restore2_rI): {
  4019. BeamInstr *next;
  4020. ErlBinMatchState *_ms;
  4021. PreFetch(1, next);
  4022. _ms = (ErlBinMatchState*) boxed_val((Eterm) r(0));
  4023. _ms->mb.offset = _ms->save_offset[Arg(0)];
  4024. NextPF(1, next);
  4025. }
  4026. OpCase(i_bs_restore2_xI): {
  4027. BeamInstr *next;
  4028. ErlBinMatchState *_ms;
  4029. PreFetch(2, next);
  4030. _ms = (ErlBinMatchState*) boxed_val((Eterm) xb(Arg(0)));
  4031. _ms->mb.offset = _ms->save_offset[Arg(1)];
  4032. NextPF(2, next);
  4033. }
  4034. #include "beam_cold.h"
  4035. /*
  4036. * This instruction is probably never used (because it is combined with a
  4037. * a return). However, a future compiler might for some reason emit a
  4038. * deallocate not followed by a return, and that should work.
  4039. */
  4040. OpCase(deallocate_I): {
  4041. BeamInstr *next;
  4042. PreFetch(1, next);
  4043. D(Arg(0));
  4044. NextPF(1, next);
  4045. }
  4046. /*
  4047. * Trace and debugging support.
  4048. */
  4049. /*
  4050. * At this point, I points to the code[3] in the export entry for
  4051. * a trace-enabled function.
  4052. *
  4053. * code[0]: Module
  4054. * code[1]: Function
  4055. * code[2]: Arity
  4056. * code[3]: &&call_traced_function
  4057. * code[4]: Address of function.
  4058. */
  4059. OpCase(call_traced_function): {
  4060. if (IS_TRACED_FL(c_p, F_TRACE_CALLS)) {
  4061. unsigned offset = offsetof(Export, code) + 3*sizeof(BeamInstr);
  4062. Export* ep = (Export *) (((char *)I)-offset);
  4063. Uint32 flags;
  4064. SWAPOUT;
  4065. reg[0] = r(0);
  4066. PROCESS_MAIN_CHK_LOCKS(c_p);
  4067. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  4068. flags = erts_call_trace(c_p, ep->code, ep->match_prog_set, reg,
  4069. 0, &c_p->tracer_proc);
  4070. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  4071. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  4072. PROCESS_MAIN_CHK_LOCKS(c_p);
  4073. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  4074. SWAPIN;
  4075. if (flags & MATCH_SET_RX_TRACE) {
  4076. ASSERT(c_p->htop <= E && E <= c_p->hend);
  4077. if (E - 3 < HTOP) {
  4078. /* SWAPOUT, SWAPIN was done and r(0) was saved above */
  4079. PROCESS_MAIN_CHK_LOCKS(c_p);
  4080. FCALLS -= erts_garbage_collect(c_p, 3, reg, ep->code[2]);
  4081. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  4082. PROCESS_MAIN_CHK_LOCKS(c_p);
  4083. r(0) = reg[0];
  4084. SWAPIN;
  4085. }
  4086. E -= 3;
  4087. ASSERT(c_p->htop <= E && E <= c_p->hend);
  4088. ASSERT(is_CP((BeamInstr)(ep->code)));
  4089. ASSERT(is_internal_pid(c_p->tracer_proc) ||
  4090. is_internal_port(c_p->tracer_proc));
  4091. E[2] = make_cp(c_p->cp); /* Code in lower range on halfword */
  4092. E[1] = am_true; /* Process tracer */
  4093. E[0] = make_cp(ep->code);
  4094. c_p->cp = (flags & MATCH_SET_EXCEPTION_TRACE)
  4095. ? beam_exception_trace : beam_return_trace;
  4096. erts_smp_proc_lock(c_p, ERTS_PROC_LOCKS_ALL_MINOR);
  4097. c_p->trace_flags |= F_EXCEPTION_TRACE;
  4098. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR);
  4099. }
  4100. }
  4101. SET_I((BeamInstr *)Arg(0));
  4102. Dispatch();
  4103. }
  4104. OpCase(return_trace): {
  4105. BeamInstr* code = (BeamInstr *) (UWord) E[0];
  4106. SWAPOUT; /* Needed for shared heap */
  4107. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  4108. erts_trace_return(c_p, code, r(0), E+1/*Process tracer*/);
  4109. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  4110. SWAPIN;
  4111. c_p->cp = NULL;
  4112. SET_I((BeamInstr *) cp_val(E[2]));
  4113. E += 3;
  4114. Goto(*I);
  4115. }
  4116. OpCase(i_count_breakpoint): {
  4117. BeamInstr real_I;
  4118. ErtsCountBreak(c_p, (BeamInstr *) I, &real_I);
  4119. ASSERT(VALID_INSTR(real_I));
  4120. Goto(real_I);
  4121. }
  4122. /* need to send mfa instead of bdt pointer
  4123. * the pointer might be deallocated.
  4124. */
  4125. OpCase(i_time_breakpoint): {
  4126. BeamInstr real_I;
  4127. BpData **bds = (BpData **) (I)[-4];
  4128. BpDataTime *bdt = NULL;
  4129. Uint ix = 0;
  4130. #ifdef ERTS_SMP
  4131. ix = c_p->scheduler_data->no - 1;
  4132. #else
  4133. ix = 0;
  4134. #endif
  4135. bdt = (BpDataTime *)bds[ix];
  4136. ASSERT((I)[-5] == (BeamInstr) BeamOp(op_i_func_info_IaaI));
  4137. ASSERT(bdt);
  4138. bdt = (BpDataTime *) bdt->next;
  4139. ASSERT(bdt);
  4140. bds[ix] = (BpData *) bdt;
  4141. real_I = bdt->orig_instr;
  4142. ASSERT(VALID_INSTR(real_I));
  4143. if (IS_TRACED_FL(c_p, F_TRACE_CALLS) && !(bdt->pause)) {
  4144. if ( (*(c_p->cp) == (BeamInstr) OpCode(i_return_time_trace)) ||
  4145. (*(c_p->cp) == (BeamInstr) OpCode(return_trace)) ||
  4146. (*(c_p->cp) == (BeamInstr) OpCode(i_return_to_trace))) {
  4147. /* This _IS_ a tail recursive call */
  4148. SWAPOUT;
  4149. erts_trace_time_break(c_p, I, bdt, ERTS_BP_CALL_TIME_TAIL_CALL);
  4150. SWAPIN;
  4151. } else {
  4152. SWAPOUT;
  4153. erts_trace_time_break(c_p, I, bdt, ERTS_BP_CALL_TIME_CALL);
  4154. /* r register needs to be copied to the array
  4155. * for the garbage collector
  4156. */
  4157. ASSERT(c_p->htop <= E && E <= c_p->hend);
  4158. if (E - 2 < HTOP) {
  4159. reg[0] = r(0);
  4160. PROCESS_MAIN_CHK_LOCKS(c_p);
  4161. FCALLS -= erts_garbage_collect(c_p, 2, reg, I[-1]);
  4162. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  4163. PROCESS_MAIN_CHK_LOCKS(c_p);
  4164. r(0) = reg[0];
  4165. }
  4166. SWAPIN;
  4167. ASSERT(c_p->htop <= E && E <= c_p->hend);
  4168. E -= 2;
  4169. E[0] = make_cp(I);
  4170. E[1] = make_cp(c_p->cp); /* original return address */
  4171. c_p->cp = beam_return_time_trace;
  4172. }
  4173. }
  4174. Goto(real_I);
  4175. }
  4176. OpCase(i_return_time_trace): {
  4177. BeamInstr *pc = (BeamInstr *) (UWord) E[0];
  4178. SWAPOUT;
  4179. erts_trace_time_break(c_p, pc, NULL, ERTS_BP_CALL_TIME_RETURN);
  4180. SWAPIN;
  4181. c_p->cp = NULL;
  4182. SET_I((BeamInstr *) cp_val(E[1]));
  4183. E += 2;
  4184. Goto(*I);
  4185. }
  4186. OpCase(i_trace_breakpoint):
  4187. if (! IS_TRACED_FL(c_p, F_TRACE_CALLS)) {
  4188. BeamInstr real_I;
  4189. ErtsBreakSkip(c_p, (BeamInstr *) I, &real_I);
  4190. Goto(real_I);
  4191. }
  4192. /* Fall through to next case */
  4193. OpCase(i_mtrace_breakpoint): {
  4194. BeamInstr real_I;
  4195. Uint32 flags;
  4196. Eterm tracer_pid;
  4197. Uint* cpp;
  4198. int return_to_trace = 0, need = 0;
  4199. flags = 0;
  4200. SWAPOUT;
  4201. reg[0] = r(0);
  4202. if (*(c_p->cp) == (BeamInstr) OpCode(return_trace)) {
  4203. cpp = &E[2];
  4204. } else if (*(c_p->cp) == (BeamInstr) OpCode(i_return_to_trace)) {
  4205. return_to_trace = !0;
  4206. cpp = &E[0];
  4207. } else if (*(c_p->cp) == (BeamInstr) OpCode(i_return_time_trace)) {
  4208. return_to_trace = !0;
  4209. cpp = &E[0];
  4210. } else {
  4211. cpp = NULL;
  4212. }
  4213. if (cpp) {
  4214. /* This _IS_ a tail recursive call, if there are
  4215. * return_trace and/or i_return_to_trace stackframes
  4216. * on the stack, they are not intermixed with y registers
  4217. */
  4218. BeamInstr *cp_save = c_p->cp;
  4219. for (;;) {
  4220. ASSERT(is_CP(*cpp));
  4221. if (*cp_val(*cpp) == (BeamInstr) OpCode(return_trace)) {
  4222. cpp += 3;
  4223. } else if (*cp_val(*cpp) == (BeamInstr) OpCode(i_return_to_trace)) {
  4224. return_to_trace = !0;
  4225. cpp += 1;
  4226. } else if (*cp_val(*cpp) == (BeamInstr) OpCode(i_return_time_trace)) {
  4227. cpp += 2;
  4228. } else
  4229. break;
  4230. }
  4231. c_p->cp = (BeamInstr *) cp_val(*cpp);
  4232. ASSERT(is_CP(*cpp));
  4233. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  4234. real_I = erts_trace_break(c_p, I, reg, &flags, &tracer_pid);
  4235. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  4236. SWAPIN; /* Needed by shared heap. */
  4237. c_p->cp = cp_save;
  4238. } else {
  4239. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  4240. real_I = erts_trace_break(c_p, I, reg, &flags, &tracer_pid);
  4241. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  4242. SWAPIN; /* Needed by shared heap. */
  4243. }
  4244. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  4245. if ((flags & MATCH_SET_RETURN_TO_TRACE) && !return_to_trace) {
  4246. need += 1;
  4247. }
  4248. if (flags & MATCH_SET_RX_TRACE) {
  4249. need += 3;
  4250. }
  4251. if (need) {
  4252. ASSERT(c_p->htop <= E && E <= c_p->hend);
  4253. if (E - need < HTOP) {
  4254. /* SWAPOUT was done and r(0) was saved above */
  4255. PROCESS_MAIN_CHK_LOCKS(c_p);
  4256. FCALLS -= erts_garbage_collect(c_p, need, reg, I[-1]);
  4257. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  4258. PROCESS_MAIN_CHK_LOCKS(c_p);
  4259. r(0) = reg[0];
  4260. SWAPIN;
  4261. }
  4262. }
  4263. if ((flags & MATCH_SET_RETURN_TO_TRACE) && !return_to_trace) {
  4264. E -= 1;
  4265. ASSERT(c_p->htop <= E && E <= c_p->hend);
  4266. E[0] = make_cp(c_p->cp);
  4267. c_p->cp = (BeamInstr *) beam_return_to_trace;
  4268. }
  4269. if (flags & MATCH_SET_RX_TRACE) {
  4270. E -= 3;
  4271. ASSERT(c_p->htop <= E && E <= c_p->hend);
  4272. ASSERT(is_CP((Eterm) (UWord) (I - 3)));
  4273. ASSERT(am_true == tracer_pid ||
  4274. is_internal_pid(tracer_pid) || is_internal_port(tracer_pid));
  4275. E[2] = make_cp(c_p->cp);
  4276. E[1] = tracer_pid;
  4277. E[0] = make_cp(I - 3); /* We ARE at the beginning of an
  4278. instruction,
  4279. the funcinfo is above i. */
  4280. c_p->cp =
  4281. (flags & MATCH_SET_EXCEPTION_TRACE)
  4282. ? beam_exception_trace : beam_return_trace;
  4283. erts_smp_proc_lock(c_p, ERTS_PROC_LOCKS_ALL_MINOR);
  4284. c_p->trace_flags |= F_EXCEPTION_TRACE;
  4285. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR);
  4286. }
  4287. Goto(real_I);
  4288. }
  4289. OpCase(i_return_to_trace): {
  4290. if (IS_TRACED_FL(c_p, F_TRACE_RETURN_TO)) {
  4291. Uint *cpp = (Uint*) E;
  4292. for(;;) {
  4293. ASSERT(is_CP(*cpp));
  4294. if (*cp_val(*cpp) == (BeamInstr) OpCode(return_trace)) {
  4295. do ++cpp; while(is_not_CP(*cpp));
  4296. cpp += 2;
  4297. } else if (*cp_val(*cpp) == (BeamInstr) OpCode(i_return_to_trace)) {
  4298. do ++cpp; while(is_not_CP(*cpp));
  4299. } else break;
  4300. }
  4301. SWAPOUT; /* Needed for shared heap */
  4302. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  4303. erts_trace_return_to(c_p, cp_val(*cpp));
  4304. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  4305. SWAPIN;
  4306. }
  4307. c_p->cp = NULL;
  4308. SET_I((BeamInstr *) cp_val(E[0]));
  4309. E += 1;
  4310. Goto(*I);
  4311. }
  4312. /*
  4313. * Instructions for allocating on the message area.
  4314. */
  4315. OpCase(i_global_cons):
  4316. {
  4317. BeamInstr *next;
  4318. #ifdef HYBRID
  4319. Eterm *hp;
  4320. PreFetch(0,next);
  4321. TestGlobalHeap(2,2,hp);
  4322. hp[0] = r(0);
  4323. hp[1] = x(1);
  4324. r(0) = make_list(hp);
  4325. #ifndef INCREMENTAL
  4326. global_htop += 2;
  4327. #endif
  4328. NextPF(0,next);
  4329. #else
  4330. PreFetch(0,next);
  4331. c_p->freason = EXC_INTERNAL_ERROR;
  4332. goto find_func_info;
  4333. #endif
  4334. }
  4335. OpCase(i_global_tuple):
  4336. {
  4337. BeamInstr *next;
  4338. int len;
  4339. #ifdef HYBRID
  4340. Eterm list;
  4341. Eterm *hp;
  4342. #endif
  4343. if ((len = list_length(r(0))) < 0) {
  4344. goto badarg;
  4345. }
  4346. PreFetch(0,next);
  4347. #ifdef HYBRID
  4348. TestGlobalHeap(len + 1,1,hp);
  4349. list = r(0);
  4350. r(0) = make_tuple(hp);
  4351. *hp++ = make_arityval(len);
  4352. while(is_list(list))
  4353. {
  4354. Eterm* cons = list_val(list);
  4355. *hp++ = CAR(cons);
  4356. list = CDR(cons);
  4357. }
  4358. #ifndef INCREMENTAL
  4359. global_htop += len + 1;
  4360. #endif
  4361. NextPF(0,next);
  4362. #else
  4363. c_p->freason = EXC_INTERNAL_ERROR;
  4364. goto find_func_info;
  4365. #endif
  4366. }
  4367. OpCase(i_global_copy):
  4368. {
  4369. BeamInstr *next;
  4370. PreFetch(0,next);
  4371. #ifdef HYBRID
  4372. if (!IS_CONST(r(0)))
  4373. {
  4374. BM_SWAP_TIMER(system,copy);
  4375. SWAPOUT;
  4376. reg[0] = r(0);
  4377. reg[1] = NIL;
  4378. r(0) = copy_struct_lazy(c_p,r(0),0);
  4379. ASSERT(ma_src_top == 0);
  4380. ASSERT(ma_dst_top == 0);
  4381. ASSERT(ma_offset_top == 0);
  4382. SWAPIN;
  4383. BM_SWAP_TIMER(copy,system);
  4384. }
  4385. NextPF(0,next);
  4386. #else
  4387. c_p->freason = EXC_INTERNAL_ERROR;
  4388. goto find_func_info;
  4389. #endif
  4390. }
  4391. /*
  4392. * New floating point instructions.
  4393. */
  4394. OpCase(fmove_ql): {
  4395. Eterm fr = Arg(1);
  4396. BeamInstr *next;
  4397. PreFetch(2, next);
  4398. GET_DOUBLE(Arg(0), *(FloatDef*)ADD_BYTE_OFFSET(freg, fr));
  4399. NextPF(2, next);
  4400. }
  4401. OpCase(fmove_dl): {
  4402. Eterm targ1;
  4403. Eterm fr = Arg(1);
  4404. BeamInstr *next;
  4405. PreFetch(2, next);
  4406. GetR(0, targ1);
  4407. /* Arg(0) == HEADER_FLONUM */
  4408. GET_DOUBLE(targ1, *(FloatDef*)ADD_BYTE_OFFSET(freg, fr));
  4409. NextPF(2, next);
  4410. }
  4411. OpCase(fmove_ld): {
  4412. Eterm fr = Arg(0);
  4413. Eterm dest = make_float(HTOP);
  4414. PUT_DOUBLE(*(FloatDef*)ADD_BYTE_OFFSET(freg, fr), HTOP);
  4415. HTOP += FLOAT_SIZE_OBJECT;
  4416. StoreBifResult(1, dest);
  4417. }
  4418. OpCase(fconv_dl): {
  4419. Eterm targ1;
  4420. Eterm fr = Arg(1);
  4421. BeamInstr *next;
  4422. GetR(0, targ1);
  4423. PreFetch(2, next);
  4424. if (is_small(targ1)) {
  4425. fb(fr) = (double) signed_val(targ1);
  4426. } else if (is_big(targ1)) {
  4427. if (big_to_double(targ1, &fb(fr)) < 0) {
  4428. goto fbadarith;
  4429. }
  4430. } else if (is_float(targ1)) {
  4431. GET_DOUBLE(targ1, *(FloatDef*)ADD_BYTE_OFFSET(freg, fr));
  4432. } else {
  4433. goto fbadarith;
  4434. }
  4435. NextPF(2, next);
  4436. }
  4437. #ifdef NO_FPE_SIGNALS
  4438. OpCase(fclearerror):
  4439. OpCase(i_fcheckerror):
  4440. erl_exit(1, "fclearerror/i_fcheckerror without fpe signals (beam_emu)");
  4441. #else
  4442. OpCase(fclearerror): {
  4443. BeamInstr *next;
  4444. PreFetch(0, next);
  4445. ERTS_FP_CHECK_INIT(c_p);
  4446. NextPF(0, next);
  4447. }
  4448. OpCase(i_fcheckerror): {
  4449. BeamInstr *next;
  4450. PreFetch(0, next);
  4451. ERTS_FP_ERROR(c_p, freg[0].fd, goto fbadarith);
  4452. NextPF(0, next);
  4453. }
  4454. # undef ERTS_FP_CHECK_INIT
  4455. # undef ERTS_FP_ERROR
  4456. # define ERTS_FP_CHECK_INIT(p)
  4457. # define ERTS_FP_ERROR(p, a, b)
  4458. #endif
  4459. OpCase(i_fadd_lll): {
  4460. BeamInstr *next;
  4461. PreFetch(3, next);
  4462. ERTS_FP_CHECK_INIT(c_p);
  4463. fb(Arg(2)) = fb(Arg(0)) + fb(Arg(1));
  4464. ERTS_FP_ERROR(c_p, fb(Arg(2)), goto fbadarith);
  4465. NextPF(3, next);
  4466. }
  4467. OpCase(i_fsub_lll): {
  4468. BeamInstr *next;
  4469. PreFetch(3, next);
  4470. ERTS_FP_CHECK_INIT(c_p);
  4471. fb(Arg(2)) = fb(Arg(0)) - fb(Arg(1));
  4472. ERTS_FP_ERROR(c_p, fb(Arg(2)), goto fbadarith);
  4473. NextPF(3, next);
  4474. }
  4475. OpCase(i_fmul_lll): {
  4476. BeamInstr *next;
  4477. PreFetch(3, next);
  4478. ERTS_FP_CHECK_INIT(c_p);
  4479. fb(Arg(2)) = fb(Arg(0)) * fb(Arg(1));
  4480. ERTS_FP_ERROR(c_p, fb(Arg(2)), goto fbadarith);
  4481. NextPF(3, next);
  4482. }
  4483. OpCase(i_fdiv_lll): {
  4484. BeamInstr *next;
  4485. PreFetch(3, next);
  4486. ERTS_FP_CHECK_INIT(c_p);
  4487. fb(Arg(2)) = fb(Arg(0)) / fb(Arg(1));
  4488. ERTS_FP_ERROR(c_p, fb(Arg(2)), goto fbadarith);
  4489. NextPF(3, next);
  4490. }
  4491. OpCase(i_fnegate_ll): {
  4492. BeamInstr *next;
  4493. PreFetch(2, next);
  4494. ERTS_FP_CHECK_INIT(c_p);
  4495. fb(Arg(1)) = -fb(Arg(0));
  4496. ERTS_FP_ERROR(c_p, fb(Arg(1)), goto fbadarith);
  4497. NextPF(2, next);
  4498. fbadarith:
  4499. c_p->freason = BADARITH;
  4500. goto find_func_info;
  4501. }
  4502. #ifdef HIPE
  4503. {
  4504. unsigned cmd;
  4505. OpCase(hipe_trap_call): {
  4506. /*
  4507. * I[-5]: &&lb_i_func_info_IaaI
  4508. * I[-4]: Native code callee (inserted by HiPE)
  4509. * I[-3]: Module (tagged atom)
  4510. * I[-2]: Function (tagged atom)
  4511. * I[-1]: Arity (untagged integer)
  4512. * I[ 0]: &&lb_hipe_trap_call
  4513. * ... remainder of original BEAM code
  4514. */
  4515. ASSERT(I[-5] == (Uint) OpCode(i_func_info_IaaI));
  4516. c_p->hipe.ncallee = (void(*)(void)) I[-4];
  4517. cmd = HIPE_MODE_SWITCH_CMD_CALL | (I[-1] << 8);
  4518. ++hipe_trap_count;
  4519. goto L_hipe_mode_switch;
  4520. }
  4521. OpCase(hipe_trap_call_closure): {
  4522. ASSERT(I[-5] == (Uint) OpCode(i_func_info_IaaI));
  4523. c_p->hipe.ncallee = (void(*)(void)) I[-4];
  4524. cmd = HIPE_MODE_SWITCH_CMD_CALL_CLOSURE | (I[-1] << 8);
  4525. ++hipe_trap_count;
  4526. goto L_hipe_mode_switch;
  4527. }
  4528. OpCase(hipe_trap_return): {
  4529. cmd = HIPE_MODE_SWITCH_CMD_RETURN;
  4530. goto L_hipe_mode_switch;
  4531. }
  4532. OpCase(hipe_trap_throw): {
  4533. cmd = HIPE_MODE_SWITCH_CMD_THROW;
  4534. goto L_hipe_mode_switch;
  4535. }
  4536. OpCase(hipe_trap_resume): {
  4537. cmd = HIPE_MODE_SWITCH_CMD_RESUME;
  4538. goto L_hipe_mode_switch;
  4539. }
  4540. L_hipe_mode_switch:
  4541. /* XXX: this abuse of def_arg_reg[] is horrid! */
  4542. SWAPOUT;
  4543. c_p->fcalls = FCALLS;
  4544. c_p->def_arg_reg[4] = -neg_o_reds;
  4545. reg[0] = r(0);
  4546. c_p = hipe_mode_switch(c_p, cmd, reg);
  4547. #ifdef ERTS_SMP
  4548. reg = c_p->scheduler_data->save_reg;
  4549. freg = c_p->scheduler_data->freg;
  4550. #endif
  4551. ERL_BITS_RELOAD_STATEP(c_p);
  4552. neg_o_reds = -c_p->def_arg_reg[4];
  4553. FCALLS = c_p->fcalls;
  4554. SWAPIN;
  4555. switch( c_p->def_arg_reg[3] ) { /* Halfword wont work with hipe yet! */
  4556. case HIPE_MODE_SWITCH_RES_RETURN:
  4557. ASSERT(is_value(reg[0]));
  4558. MoveReturn(reg[0], r(0));
  4559. case HIPE_MODE_SWITCH_RES_CALL:
  4560. SET_I(c_p->i);
  4561. r(0) = reg[0];
  4562. Dispatch();
  4563. case HIPE_MODE_SWITCH_RES_CALL_CLOSURE:
  4564. /* This can be used to call any function value, but currently it's
  4565. only used to call closures referring to unloaded modules. */
  4566. {
  4567. BeamInstr *next;
  4568. next = call_fun(c_p, c_p->arity - 1, reg, THE_NON_VALUE);
  4569. SWAPIN;
  4570. if (next != NULL) {
  4571. r(0) = reg[0];
  4572. SET_I(next);
  4573. Dispatchfun();
  4574. }
  4575. goto find_func_info;
  4576. }
  4577. case HIPE_MODE_SWITCH_RES_THROW:
  4578. c_p->cp = NULL;
  4579. I = handle_error(c_p, I, reg, NULL);
  4580. goto post_error_handling;
  4581. default:
  4582. erl_exit(1, "hipe_mode_switch: result %u\n", c_p->def_arg_reg[3]);
  4583. }
  4584. }
  4585. OpCase(hipe_call_count): {
  4586. /*
  4587. * I[-5]: &&lb_i_func_info_IaaI
  4588. * I[-4]: pointer to struct hipe_call_count (inserted by HiPE)
  4589. * I[-3]: Module (tagged atom)
  4590. * I[-2]: Function (tagged atom)
  4591. * I[-1]: Arity (untagged integer)
  4592. * I[ 0]: &&lb_hipe_call_count
  4593. * ... remainder of original BEAM code
  4594. */
  4595. struct hipe_call_count *hcc = (struct hipe_call_count*)I[-4];
  4596. ASSERT(I[-5] == (Uint) OpCode(i_func_info_IaaI));
  4597. ASSERT(hcc != NULL);
  4598. ASSERT(VALID_INSTR(hcc->opcode));
  4599. ++(hcc->count);
  4600. Goto(hcc->opcode);
  4601. }
  4602. #endif /* HIPE */
  4603. OpCase(i_yield):
  4604. {
  4605. /* This is safe as long as REDS_IN(c_p) is never stored
  4606. * in c_p->arg_reg[0]. It is currently stored in c_p->def_arg_reg[5],
  4607. * which may be c_p->arg_reg[5], which is close, but no banana.
  4608. */
  4609. c_p->arg_reg[0] = am_true;
  4610. c_p->arity = 1; /* One living register (the 'true' return value) */
  4611. SWAPOUT;
  4612. c_p->i = I + 1; /* Next instruction */
  4613. erts_smp_proc_lock(c_p, ERTS_PROC_LOCK_STATUS);
  4614. erts_add_to_runq(c_p);
  4615. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCK_STATUS);
  4616. c_p->current = NULL;
  4617. goto do_schedule;
  4618. }
  4619. OpCase(i_hibernate): {
  4620. SWAPOUT;
  4621. if (hibernate(c_p, r(0), x(1), x(2), reg)) {
  4622. goto do_schedule;
  4623. } else {
  4624. I = handle_error(c_p, I, reg, hibernate_3);
  4625. goto post_error_handling;
  4626. }
  4627. }
  4628. OpCase(i_debug_breakpoint): {
  4629. SWAPOUT;
  4630. reg[0] = r(0);
  4631. I = call_error_handler(c_p, I-3, reg, am_breakpoint);
  4632. r(0) = reg[0];
  4633. SWAPIN;
  4634. if (I) {
  4635. Goto(*I);
  4636. }
  4637. goto no_error_handler;
  4638. }
  4639. OpCase(system_limit_j):
  4640. system_limit:
  4641. c_p->freason = SYSTEM_LIMIT;
  4642. goto lb_Cl_error;
  4643. #ifdef ERTS_OPCODE_COUNTER_SUPPORT
  4644. DEFINE_COUNTING_LABELS;
  4645. #endif
  4646. #ifndef NO_JUMP_TABLE
  4647. #ifdef DEBUG
  4648. end_emulator_loop:
  4649. #endif
  4650. #endif
  4651. OpCase(int_code_end):
  4652. OpCase(label_L):
  4653. OpCase(too_old_compiler):
  4654. OpCase(on_load):
  4655. erl_exit(1, "meta op\n");
  4656. /*
  4657. * One-time initialization of Beam emulator.
  4658. */
  4659. init_emulator:
  4660. {
  4661. int i;
  4662. Export* ep;
  4663. #ifndef NO_JUMP_TABLE
  4664. #ifdef ERTS_OPCODE_COUNTER_SUPPORT
  4665. /* Are tables correctly generated by beam_makeops? */
  4666. ASSERT(sizeof(counting_opcodes) == sizeof(opcodes));
  4667. if (count_instructions) {
  4668. #ifdef DEBUG
  4669. counting_opcodes[op_catch_end_y] = LabelAddr(lb_catch_end_y);
  4670. #endif
  4671. counting_opcodes[op_i_func_info_IaaI] = LabelAddr(lb_i_func_info_IaaI);
  4672. beam_ops = counting_opcodes;
  4673. }
  4674. else
  4675. #endif /* #ifndef ERTS_OPCODE_COUNTER_SUPPORT */
  4676. {
  4677. beam_ops = opcodes;
  4678. }
  4679. #endif /* NO_JUMP_TABLE */
  4680. em_call_error_handler = OpCode(call_error_handler);
  4681. em_call_traced_function = OpCode(call_traced_function);
  4682. em_apply_bif = OpCode(apply_bif);
  4683. beam_apply[0] = (BeamInstr) OpCode(i_apply);
  4684. beam_apply[1] = (BeamInstr) OpCode(normal_exit);
  4685. beam_exit[0] = (BeamInstr) OpCode(error_action_code);
  4686. beam_continue_exit[0] = (BeamInstr) OpCode(continue_exit);
  4687. beam_return_to_trace[0] = (BeamInstr) OpCode(i_return_to_trace);
  4688. beam_return_trace[0] = (BeamInstr) OpCode(return_trace);
  4689. beam_exception_trace[0] = (BeamInstr) OpCode(return_trace); /* UGLY */
  4690. beam_return_time_trace[0] = (BeamInstr) OpCode(i_return_time_trace);
  4691. /*
  4692. * Enter all BIFs into the export table.
  4693. */
  4694. for (i = 0; i < BIF_SIZE; i++) {
  4695. ep = erts_export_put(bif_table[i].module,
  4696. bif_table[i].name,
  4697. bif_table[i].arity);
  4698. bif_export[i] = ep;
  4699. ep->code[3] = (BeamInstr) OpCode(apply_bif);
  4700. ep->code[4] = (BeamInstr) bif_table[i].f;
  4701. /* XXX: set func info for bifs */
  4702. ((BeamInstr*)ep->code + 3)[-5] = (BeamInstr) BeamOp(op_i_func_info_IaaI);
  4703. }
  4704. return;
  4705. }
  4706. #ifdef NO_JUMP_TABLE
  4707. default:
  4708. erl_exit(1, "unexpected op code %d\n",Go);
  4709. }
  4710. #endif
  4711. return; /* Never executed */
  4712. save_calls1:
  4713. {
  4714. Eterm* dis_next;
  4715. save_calls(c_p, (Export *) Arg(0));
  4716. SET_I(((Export *) Arg(0))->address);
  4717. dis_next = (Eterm *) *I;
  4718. FCALLS--;
  4719. Goto(dis_next);
  4720. }
  4721. }
  4722. static BifFunction
  4723. translate_gc_bif(void* gcf)
  4724. {
  4725. if (gcf == erts_gc_length_1) {
  4726. return length_1;
  4727. } else if (gcf == erts_gc_size_1) {
  4728. return size_1;
  4729. } else if (gcf == erts_gc_bit_size_1) {
  4730. return bit_size_1;
  4731. } else if (gcf == erts_gc_byte_size_1) {
  4732. return byte_size_1;
  4733. } else if (gcf == erts_gc_abs_1) {
  4734. return abs_1;
  4735. } else if (gcf == erts_gc_float_1) {
  4736. return float_1;
  4737. } else if (gcf == erts_gc_round_1) {
  4738. return round_1;
  4739. } else if (gcf == erts_gc_trunc_1) {
  4740. return round_1;
  4741. } else if (gcf == erts_gc_binary_part_2) {
  4742. return binary_part_2;
  4743. } else if (gcf == erts_gc_binary_part_3) {
  4744. return binary_part_3;
  4745. } else {
  4746. erl_exit(1, "bad gc bif");
  4747. }
  4748. }
  4749. /*
  4750. * Mapping from the error code 'class tag' to atoms.
  4751. */
  4752. Eterm exception_tag[NUMBER_EXC_TAGS] = {
  4753. am_error, /* 0 */
  4754. am_exit, /* 1 */
  4755. am_throw, /* 2 */
  4756. };
  4757. /*
  4758. * Mapping from error code 'index' to atoms.
  4759. */
  4760. Eterm error_atom[NUMBER_EXIT_CODES] = {
  4761. am_internal_error, /* 0 */
  4762. am_normal, /* 1 */
  4763. am_internal_error, /* 2 */
  4764. am_badarg, /* 3 */
  4765. am_badarith, /* 4 */
  4766. am_badmatch, /* 5 */
  4767. am_function_clause, /* 6 */
  4768. am_case_clause, /* 7 */
  4769. am_if_clause, /* 8 */
  4770. am_undef, /* 9 */
  4771. am_badfun, /* 10 */
  4772. am_badarity, /* 11 */
  4773. am_timeout_value, /* 12 */
  4774. am_noproc, /* 13 */
  4775. am_notalive, /* 14 */
  4776. am_system_limit, /* 15 */
  4777. am_try_clause, /* 16 */
  4778. am_notsup /* 17 */
  4779. };
  4780. /*
  4781. * To fully understand the error handling, one must keep in mind that
  4782. * when an exception is thrown, the search for a handler can jump back
  4783. * and forth between Beam and native code. Upon each mode switch, a
  4784. * dummy handler is inserted so that if an exception reaches that point,
  4785. * the handler is invoked (like any handler) and transfers control so
  4786. * that the search for a real handler is continued in the other mode.
  4787. * Therefore, c_p->freason and c_p->fvalue must still hold the exception
  4788. * info when the handler is executed, but normalized so that creation of
  4789. * error terms and saving of the stack trace is only done once, even if
  4790. * we pass through the error handling code several times.
  4791. *
  4792. * When a new exception is raised, the current stack trace information
  4793. * is quick-saved in a small structure allocated on the heap. Depending
  4794. * on how the exception is eventually caught (perhaps by causing the
  4795. * current process to terminate), the saved information may be used to
  4796. * create a symbolic (human-readable) representation of the stack trace
  4797. * at the point of the original exception.
  4798. */
  4799. static BeamInstr*
  4800. handle_error(Process* c_p, BeamInstr* pc, Eterm* reg, BifFunction bf)
  4801. {
  4802. Eterm* hp;
  4803. Eterm Value = c_p->fvalue;
  4804. Eterm Args = am_true;
  4805. c_p->i = pc; /* In case we call erl_exit(). */
  4806. ASSERT(c_p->freason != TRAP); /* Should have been handled earlier. */
  4807. /*
  4808. * Check if we have an arglist for the top level call. If so, this
  4809. * is encoded in Value, so we have to dig out the real Value as well
  4810. * as the Arglist.
  4811. */
  4812. if (c_p->freason & EXF_ARGLIST) {
  4813. Eterm* tp;
  4814. ASSERT(is_tuple(Value));
  4815. tp = tuple_val(Value);
  4816. Value = tp[1];
  4817. Args = tp[2];
  4818. }
  4819. /*
  4820. * Save the stack trace info if the EXF_SAVETRACE flag is set. The
  4821. * main reason for doing this separately is to allow throws to later
  4822. * become promoted to errors without losing the original stack
  4823. * trace, even if they have passed through one or more catch and
  4824. * rethrow. It also makes the creation of symbolic stack traces much
  4825. * more modular.
  4826. */
  4827. if (c_p->freason & EXF_SAVETRACE) {
  4828. save_stacktrace(c_p, pc, reg, bf, Args);
  4829. }
  4830. /*
  4831. * Throws that are not caught are turned into 'nocatch' errors
  4832. */
  4833. if ((c_p->freason & EXF_THROWN) && (c_p->catches <= 0) ) {
  4834. hp = HAlloc(c_p, 3);
  4835. Value = TUPLE2(hp, am_nocatch, Value);
  4836. c_p->freason = EXC_ERROR;
  4837. }
  4838. /* Get the fully expanded error term */
  4839. Value = expand_error_value(c_p, c_p->freason, Value);
  4840. /* Save final error term and stabilize the exception flags so no
  4841. further expansion is done. */
  4842. c_p->fvalue = Value;
  4843. c_p->freason = PRIMARY_EXCEPTION(c_p->freason);
  4844. /* Find a handler or die */
  4845. if ((c_p->catches > 0 || IS_TRACED_FL(c_p, F_EXCEPTION_TRACE))
  4846. && !(c_p->freason & EXF_PANIC)) {
  4847. BeamInstr *new_pc;
  4848. /* The Beam handler code (catch_end or try_end) checks reg[0]
  4849. for THE_NON_VALUE to see if the previous code finished
  4850. abnormally. If so, reg[1], reg[2] and reg[3] should hold the
  4851. exception class, term and trace, respectively. (If the
  4852. handler is just a trap to native code, these registers will
  4853. be ignored.) */
  4854. reg[0] = THE_NON_VALUE;
  4855. reg[1] = exception_tag[GET_EXC_CLASS(c_p->freason)];
  4856. reg[2] = Value;
  4857. reg[3] = c_p->ftrace;
  4858. if ((new_pc = next_catch(c_p, reg))) {
  4859. c_p->cp = 0; /* To avoid keeping stale references. */
  4860. return new_pc;
  4861. }
  4862. if (c_p->catches > 0) erl_exit(1, "Catch not found");
  4863. }
  4864. ERTS_SMP_UNREQ_PROC_MAIN_LOCK(c_p);
  4865. terminate_proc(c_p, Value);
  4866. ERTS_SMP_REQ_PROC_MAIN_LOCK(c_p);
  4867. return NULL;
  4868. }
  4869. /*
  4870. * Find the nearest catch handler
  4871. */
  4872. static BeamInstr*
  4873. next_catch(Process* c_p, Eterm *reg) {
  4874. int active_catches = c_p->catches > 0;
  4875. int have_return_to_trace = 0;
  4876. Eterm *ptr, *prev, *return_to_trace_ptr = NULL;
  4877. BeamInstr i_return_trace = beam_return_trace[0];
  4878. BeamInstr i_return_to_trace = beam_return_to_trace[0];
  4879. BeamInstr i_return_time_trace = beam_return_time_trace[0];
  4880. ptr = prev = c_p->stop;
  4881. ASSERT(is_CP(*ptr));
  4882. ASSERT(ptr <= STACK_START(c_p));
  4883. if (ptr == STACK_START(c_p)) return NULL;
  4884. if ((is_not_CP(*ptr) || (*cp_val(*ptr) != i_return_trace &&
  4885. *cp_val(*ptr) != i_return_to_trace &&
  4886. *cp_val(*ptr) != i_return_time_trace ))
  4887. && c_p->cp) {
  4888. /* Can not follow cp here - code may be unloaded */
  4889. BeamInstr *cpp = c_p->cp;
  4890. if (cpp == beam_exception_trace) {
  4891. erts_trace_exception(c_p, cp_val(ptr[0]),
  4892. reg[1], reg[2], ptr+1);
  4893. /* Skip return_trace parameters */
  4894. ptr += 2;
  4895. } else if (cpp == beam_return_trace) {
  4896. /* Skip return_trace parameters */
  4897. ptr += 2;
  4898. } else if (cpp == beam_return_time_trace) {
  4899. /* Skip return_trace parameters */
  4900. ptr += 1;
  4901. } else if (cpp == beam_return_to_trace) {
  4902. have_return_to_trace = !0; /* Record next cp */
  4903. }
  4904. }
  4905. while (ptr < STACK_START(c_p)) {
  4906. if (is_catch(*ptr)) {
  4907. if (active_catches) goto found_catch;
  4908. ptr++;
  4909. }
  4910. else if (is_CP(*ptr)) {
  4911. prev = ptr;
  4912. if (*cp_val(*prev) == i_return_trace) {
  4913. /* Skip stack frame variables */
  4914. while (++ptr, ptr < STACK_START(c_p) && is_not_CP(*ptr)) {
  4915. if (is_catch(*ptr) && active_catches) goto found_catch;
  4916. }
  4917. if (cp_val(*prev) == beam_exception_trace) {
  4918. erts_trace_exception(c_p, cp_val(ptr[0]),
  4919. reg[1], reg[2], ptr+1);
  4920. }
  4921. /* Skip return_trace parameters */
  4922. ptr += 2;
  4923. } else if (*cp_val(*prev) == i_return_to_trace) {
  4924. /* Skip stack frame variables */
  4925. while (++ptr, ptr < STACK_START(c_p) && is_not_CP(*ptr)) {
  4926. if (is_catch(*ptr) && active_catches) goto found_catch;
  4927. }
  4928. have_return_to_trace = !0; /* Record next cp */
  4929. return_to_trace_ptr = NULL;
  4930. } else if (*cp_val(*prev) == i_return_time_trace) {
  4931. /* Skip stack frame variables */
  4932. while (++ptr, ptr < STACK_START(c_p) && is_not_CP(*ptr)) {
  4933. if (is_catch(*ptr) && active_catches) goto found_catch;
  4934. }
  4935. /* Skip return_trace parameters */
  4936. ptr += 1;
  4937. } else {
  4938. if (have_return_to_trace) {
  4939. /* Record this cp as possible return_to trace cp */
  4940. have_return_to_trace = 0;
  4941. return_to_trace_ptr = ptr;
  4942. } else return_to_trace_ptr = NULL;
  4943. ptr++;
  4944. }
  4945. } else ptr++;
  4946. }
  4947. return NULL;
  4948. found_catch:
  4949. ASSERT(ptr < STACK_START(c_p));
  4950. c_p->stop = prev;
  4951. if (IS_TRACED_FL(c_p, F_TRACE_RETURN_TO) && return_to_trace_ptr) {
  4952. /* The stackframe closest to the catch contained an
  4953. * return_to_trace entry, so since the execution now
  4954. * continues after the catch, a return_to trace message
  4955. * would be appropriate.
  4956. */
  4957. erts_trace_return_to(c_p, cp_val(*return_to_trace_ptr));
  4958. }
  4959. return catch_pc(*ptr);
  4960. }
  4961. /*
  4962. * Terminating the process when an exception is not caught
  4963. */
  4964. static void
  4965. terminate_proc(Process* c_p, Eterm Value)
  4966. {
  4967. /* Add a stacktrace if this is an error. */
  4968. if (GET_EXC_CLASS(c_p->freason) == EXTAG_ERROR) {
  4969. Value = add_stacktrace(c_p, Value, c_p->ftrace);
  4970. }
  4971. /* EXF_LOG is a primary exception flag */
  4972. if (c_p->freason & EXF_LOG) {
  4973. erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf();
  4974. erts_dsprintf(dsbufp, "Error in process %T ", c_p->id);
  4975. if (erts_is_alive)
  4976. erts_dsprintf(dsbufp, "on node %T ", erts_this_node->sysname);
  4977. erts_dsprintf(dsbufp,"with exit value: %0.*T\n", display_items, Value);
  4978. erts_send_error_to_logger(c_p->group_leader, dsbufp);
  4979. }
  4980. /*
  4981. * If we use a shared heap, the process will be garbage-collected.
  4982. * Must zero c_p->arity to indicate that there are no live registers.
  4983. */
  4984. c_p->arity = 0;
  4985. erts_do_exit_process(c_p, Value);
  4986. }
  4987. /*
  4988. * Build and add a symbolic stack trace to the error value.
  4989. */
  4990. static Eterm
  4991. add_stacktrace(Process* c_p, Eterm Value, Eterm exc) {
  4992. Eterm Where = build_stacktrace(c_p, exc);
  4993. Eterm* hp = HAlloc(c_p, 3);
  4994. return TUPLE2(hp, Value, Where);
  4995. }
  4996. /*
  4997. * Forming the correct error value from the internal error code.
  4998. * This does not update c_p->fvalue or c_p->freason.
  4999. */
  5000. Eterm
  5001. expand_error_value(Process* c_p, Uint freason, Eterm Value) {
  5002. Eterm* hp;
  5003. Uint r;
  5004. r = GET_EXC_INDEX(freason);
  5005. ASSERT(r < NUMBER_EXIT_CODES); /* range check */
  5006. ASSERT(is_value(Value));
  5007. switch (r) {
  5008. case (GET_EXC_INDEX(EXC_PRIMARY)):
  5009. /* Primary exceptions use fvalue as it is */
  5010. break;
  5011. case (GET_EXC_INDEX(EXC_BADMATCH)):
  5012. case (GET_EXC_INDEX(EXC_CASE_CLAUSE)):
  5013. case (GET_EXC_INDEX(EXC_TRY_CLAUSE)):
  5014. case (GET_EXC_INDEX(EXC_BADFUN)):
  5015. case (GET_EXC_INDEX(EXC_BADARITY)):
  5016. /* Some common exceptions: value -> {atom, value} */
  5017. ASSERT(is_value(Value));
  5018. hp = HAlloc(c_p, 3);
  5019. Value = TUPLE2(hp, error_atom[r], Value);
  5020. break;
  5021. default:
  5022. /* Other exceptions just use an atom as descriptor */
  5023. Value = error_atom[r];
  5024. break;
  5025. }
  5026. #ifdef DEBUG
  5027. ASSERT(Value != am_internal_error);
  5028. #endif
  5029. return Value;
  5030. }
  5031. /*
  5032. * Quick-saving the stack trace in an internal form on the heap. Note
  5033. * that c_p->ftrace will point to a cons cell which holds the given args
  5034. * and the saved data (encoded as a bignum).
  5035. *
  5036. * (It would be much better to put the arglist - when it exists - in the
  5037. * error value instead of in the actual trace; e.g. '{badarg, Args}'
  5038. * instead of using 'badarg' with Args in the trace. The arglist may
  5039. * contain very large values, and right now they will be kept alive as
  5040. * long as the stack trace is live. Preferably, the stack trace should
  5041. * always be small, so that it does not matter if it is long-lived.
  5042. * However, it is probably not possible to ever change the format of
  5043. * error terms.)
  5044. */
  5045. static void
  5046. save_stacktrace(Process* c_p, BeamInstr* pc, Eterm* reg, BifFunction bf,
  5047. Eterm args) {
  5048. struct StackTrace* s;
  5049. int sz;
  5050. int depth = erts_backtrace_depth; /* max depth (never negative) */
  5051. if (depth > 0) {
  5052. /* There will always be a current function */
  5053. depth --;
  5054. }
  5055. /* Create a container for the exception data */
  5056. sz = (offsetof(struct StackTrace, trace) + sizeof(BeamInstr *)*depth
  5057. + sizeof(Eterm) - 1) / sizeof(Eterm);
  5058. s = (struct StackTrace *) HAlloc(c_p, 1 + sz);
  5059. /* The following fields are inside the bignum */
  5060. s->header = make_pos_bignum_header(sz);
  5061. s->freason = c_p->freason;
  5062. s->depth = 0;
  5063. /*
  5064. * If the failure was in a BIF other than 'error', 'exit' or
  5065. * 'throw', find the bif-table index and save the argument
  5066. * registers by consing up an arglist.
  5067. */
  5068. if (bf != NULL && bf != error_1 && bf != error_2 &&
  5069. bf != exit_1 && bf != throw_1) {
  5070. int i;
  5071. int a = 0;
  5072. for (i = 0; i < BIF_SIZE; i++) {
  5073. if (bf == bif_table[i].f || bf == bif_table[i].traced) {
  5074. Export *ep = bif_export[i];
  5075. s->current = ep->code;
  5076. a = bif_table[i].arity;
  5077. break;
  5078. }
  5079. }
  5080. if (i >= BIF_SIZE) {
  5081. /*
  5082. * The Bif does not really exist (no BIF entry). It is a
  5083. * TRAP and traps are called through apply_bif, which also
  5084. * sets c_p->current (luckily).
  5085. * OR it is a NIF called by call_nif where current is also set.
  5086. */
  5087. ASSERT(c_p->current);
  5088. s->current = c_p->current;
  5089. a = s->current[2];
  5090. }
  5091. /* Save first stack entry */
  5092. ASSERT(pc);
  5093. if (depth > 0) {
  5094. s->trace[s->depth++] = pc;
  5095. depth--;
  5096. }
  5097. /* Save second stack entry if CP is valid and different from pc */
  5098. if (depth > 0 && c_p->cp != 0 && c_p->cp != pc) {
  5099. s->trace[s->depth++] = c_p->cp;
  5100. depth--;
  5101. }
  5102. s->pc = NULL;
  5103. args = make_arglist(c_p, reg, a); /* Overwrite CAR(c_p->ftrace) */
  5104. } else {
  5105. s->current = c_p->current;
  5106. /*
  5107. * For a function_clause error, the arguments are in the beam
  5108. * registers, c_p->cp is valid, and c_p->current is set.
  5109. */
  5110. if ( (GET_EXC_INDEX(s->freason)) ==
  5111. (GET_EXC_INDEX(EXC_FUNCTION_CLAUSE)) ) {
  5112. int a;
  5113. ASSERT(s->current);
  5114. a = s->current[2];
  5115. args = make_arglist(c_p, reg, a); /* Overwrite CAR(c_p->ftrace) */
  5116. /* Save first stack entry */
  5117. ASSERT(c_p->cp);
  5118. if (depth > 0) {
  5119. s->trace[s->depth++] = c_p->cp;
  5120. depth--;
  5121. }
  5122. s->pc = NULL; /* Ignore pc */
  5123. } else {
  5124. if (depth > 0 && c_p->cp != 0 && c_p->cp != pc) {
  5125. s->trace[s->depth++] = c_p->cp;
  5126. depth--;
  5127. }
  5128. s->pc = pc;
  5129. }
  5130. }
  5131. /* Package args and stack trace */
  5132. {
  5133. Eterm *hp;
  5134. hp = HAlloc(c_p, 2);
  5135. c_p->ftrace = CONS(hp, args, make_big((Eterm *) s));
  5136. }
  5137. /* Save the actual stack trace */
  5138. if (depth > 0) {
  5139. Eterm *ptr;
  5140. BeamInstr *prev = s->depth ? s->trace[s->depth-1] : NULL;
  5141. BeamInstr i_return_trace = beam_return_trace[0];
  5142. BeamInstr i_return_to_trace = beam_return_to_trace[0];
  5143. /*
  5144. * Traverse the stack backwards and add all unique continuation
  5145. * pointers to the buffer, up to the maximum stack trace size.
  5146. *
  5147. * Skip trace stack frames.
  5148. */
  5149. ptr = c_p->stop;
  5150. if (ptr < STACK_START(c_p)
  5151. && (is_not_CP(*ptr)|| (*cp_val(*ptr) != i_return_trace &&
  5152. *cp_val(*ptr) != i_return_to_trace))
  5153. && c_p->cp) {
  5154. /* Can not follow cp here - code may be unloaded */
  5155. BeamInstr *cpp = c_p->cp;
  5156. if (cpp == beam_exception_trace || cpp == beam_return_trace) {
  5157. /* Skip return_trace parameters */
  5158. ptr += 2;
  5159. } else if (cpp == beam_return_to_trace) {
  5160. /* Skip return_to_trace parameters */
  5161. ptr += 1;
  5162. }
  5163. }
  5164. while (ptr < STACK_START(c_p) && depth > 0) {
  5165. if (is_CP(*ptr)) {
  5166. if (*cp_val(*ptr) == i_return_trace) {
  5167. /* Skip stack frame variables */
  5168. do ++ptr; while (is_not_CP(*ptr));
  5169. /* Skip return_trace parameters */
  5170. ptr += 2;
  5171. } else if (*cp_val(*ptr) == i_return_to_trace) {
  5172. /* Skip stack frame variables */
  5173. do ++ptr; while (is_not_CP(*ptr));
  5174. } else {
  5175. BeamInstr *cp = cp_val(*ptr);
  5176. if (cp != prev) {
  5177. /* Record non-duplicates only */
  5178. prev = cp;
  5179. s->trace[s->depth++] = cp;
  5180. depth--;
  5181. }
  5182. ptr++;
  5183. }
  5184. } else ptr++;
  5185. }
  5186. }
  5187. }
  5188. /*
  5189. * Getting the relevant fields from the term pointed to by ftrace
  5190. */
  5191. static struct StackTrace *get_trace_from_exc(Eterm exc) {
  5192. if (exc == NIL) {
  5193. return NULL;
  5194. } else {
  5195. ASSERT(is_list(exc));
  5196. return (struct StackTrace *) big_val(CDR(list_val(exc)));
  5197. }
  5198. }
  5199. static Eterm get_args_from_exc(Eterm exc) {
  5200. if (exc == NIL) {
  5201. return NIL;
  5202. } else {
  5203. ASSERT(is_list(exc));
  5204. return CAR(list_val(exc));
  5205. }
  5206. }
  5207. static int is_raised_exc(Eterm exc) {
  5208. if (exc == NIL) {
  5209. return 0;
  5210. } else {
  5211. ASSERT(is_list(exc));
  5212. return bignum_header_is_neg(*big_val(CDR(list_val(exc))));
  5213. }
  5214. }
  5215. /*
  5216. * Creating a list with the argument registers
  5217. */
  5218. static Eterm
  5219. make_arglist(Process* c_p, Eterm* reg, int a) {
  5220. Eterm args = NIL;
  5221. Eterm* hp = HAlloc(c_p, 2*a);
  5222. while (a > 0) {
  5223. args = CONS(hp, reg[a-1], args);
  5224. hp += 2;
  5225. a--;
  5226. }
  5227. return args;
  5228. }
  5229. /*
  5230. * Building a symbolic representation of a saved stack trace. Note that
  5231. * the exception object 'exc', unless NIL, points to a cons cell which
  5232. * holds the given args and the quick-saved data (encoded as a bignum).
  5233. *
  5234. * If the bignum is negative, the given args is a complete stacktrace.
  5235. */
  5236. Eterm
  5237. build_stacktrace(Process* c_p, Eterm exc) {
  5238. struct StackTrace* s;
  5239. Eterm args;
  5240. int depth;
  5241. BeamInstr* current;
  5242. Eterm Where = NIL;
  5243. Eterm *next_p = &Where;
  5244. if (! (s = get_trace_from_exc(exc))) {
  5245. return NIL;
  5246. }
  5247. #ifdef HIPE
  5248. if (s->freason & EXF_NATIVE) {
  5249. return hipe_build_stacktrace(c_p, s);
  5250. }
  5251. #endif
  5252. if (is_raised_exc(exc)) {
  5253. return get_args_from_exc(exc);
  5254. }
  5255. /*
  5256. * Find the current function. If the saved s->pc is null, then the
  5257. * saved s->current should already contain the proper value.
  5258. */
  5259. if (s->pc != NULL) {
  5260. current = find_function_from_pc(s->pc);
  5261. } else {
  5262. current = s->current;
  5263. }
  5264. /*
  5265. * If current is still NULL, default to the initial function
  5266. * (e.g. spawn_link(erlang, abs, [1])).
  5267. */
  5268. if (current == NULL) {
  5269. current = c_p->initial;
  5270. args = am_true; /* Just in case */
  5271. } else {
  5272. args = get_args_from_exc(exc);
  5273. }
  5274. depth = s->depth;
  5275. /*
  5276. * Add the {M,F,A} for the current function
  5277. * (where A is arity or [Argument]).
  5278. */
  5279. {
  5280. int i;
  5281. Eterm mfa;
  5282. Uint heap_size = 6*(depth+1);
  5283. Eterm* hp = HAlloc(c_p, heap_size);
  5284. Eterm* hp_end = hp + heap_size;
  5285. if (args != am_true) {
  5286. /* We have an arglist - use it */
  5287. mfa = TUPLE3(hp, current[0], current[1], args);
  5288. } else {
  5289. Eterm arity = make_small(current[2]);
  5290. mfa = TUPLE3(hp, current[0], current[1], arity);
  5291. }
  5292. hp += 4;
  5293. ASSERT(*next_p == NIL);
  5294. *next_p = CONS(hp, mfa, NIL);
  5295. next_p = &CDR(list_val(*next_p));
  5296. hp += 2;
  5297. /*
  5298. * Finally, we go through the saved continuation pointers.
  5299. */
  5300. for (i = 0; i < depth; i++) {
  5301. BeamInstr *fi = find_function_from_pc((BeamInstr *) s->trace[i]);
  5302. if (fi == NULL) continue;
  5303. mfa = TUPLE3(hp, fi[0], fi[1], make_small(fi[2]));
  5304. hp += 4;
  5305. ASSERT(*next_p == NIL);
  5306. *next_p = CONS(hp, mfa, NIL);
  5307. next_p = &CDR(list_val(*next_p));
  5308. hp += 2;
  5309. }
  5310. ASSERT(hp <= hp_end);
  5311. HRelease(c_p, hp_end, hp);
  5312. }
  5313. return Where;
  5314. }
  5315. static BeamInstr*
  5316. call_error_handler(Process* p, BeamInstr* fi, Eterm* reg, Eterm func)
  5317. {
  5318. Eterm* hp;
  5319. Export* ep;
  5320. int arity;
  5321. Eterm args;
  5322. Uint sz;
  5323. int i;
  5324. /*
  5325. * Search for the error_handler module.
  5326. */
  5327. ep = erts_find_function(erts_proc_get_error_handler(p), func, 3);
  5328. if (ep == NULL) { /* No error handler */
  5329. p->current = fi;
  5330. p->freason = EXC_UNDEF;
  5331. return 0;
  5332. }
  5333. /*
  5334. * Create a list with all arguments in the x registers.
  5335. */
  5336. arity = fi[2];
  5337. sz = 2 * arity;
  5338. if (HeapWordsLeft(p) < sz) {
  5339. erts_garbage_collect(p, sz, reg, arity);
  5340. }
  5341. hp = HEAP_TOP(p);
  5342. HEAP_TOP(p) += sz;
  5343. args = NIL;
  5344. for (i = arity-1; i >= 0; i--) {
  5345. args = CONS(hp, reg[i], args);
  5346. hp += 2;
  5347. }
  5348. /*
  5349. * Set up registers for call to error_handler:<func>/3.
  5350. */
  5351. reg[0] = fi[0];
  5352. reg[1] = fi[1];
  5353. reg[2] = args;
  5354. return ep->address;
  5355. }
  5356. static Export*
  5357. apply_setup_error_handler(Process* p, Eterm module, Eterm function, Uint arity, Eterm* reg)
  5358. {
  5359. Export* ep;
  5360. /*
  5361. * Find the export table index for the error handler. Return NULL if
  5362. * there is no error handler module.
  5363. */
  5364. if ((ep = erts_find_export_entry(erts_proc_get_error_handler(p),
  5365. am_undefined_function, 3)) == NULL) {
  5366. return NULL;
  5367. } else {
  5368. int i;
  5369. Uint sz = 2*arity;
  5370. Eterm* hp;
  5371. Eterm args = NIL;
  5372. /*
  5373. * Always copy args from registers to a new list; this ensures
  5374. * that we have the same behaviour whether or not this was
  5375. * called from apply or fixed_apply (any additional last
  5376. * THIS-argument will be included, assuming that arity has been
  5377. * properly adjusted).
  5378. */
  5379. if (HeapWordsLeft(p) < sz) {
  5380. erts_garbage_collect(p, sz, reg, arity);
  5381. }
  5382. hp = HEAP_TOP(p);
  5383. HEAP_TOP(p) += sz;
  5384. for (i = arity-1; i >= 0; i--) {
  5385. args = CONS(hp, reg[i], args);
  5386. hp += 2;
  5387. }
  5388. reg[0] = module;
  5389. reg[1] = function;
  5390. reg[2] = args;
  5391. }
  5392. return ep;
  5393. }
  5394. static BeamInstr*
  5395. apply(Process* p, Eterm module, Eterm function, Eterm args, Eterm* reg)
  5396. {
  5397. int arity;
  5398. Export* ep;
  5399. Eterm tmp, this;
  5400. /*
  5401. * Check the arguments which should be of the form apply(Module,
  5402. * Function, Arguments) where Function is an atom and
  5403. * Arguments is an arity long list of terms.
  5404. */
  5405. if (is_not_atom(function)) {
  5406. /*
  5407. * No need to test args here -- done below.
  5408. */
  5409. error:
  5410. p->freason = BADARG;
  5411. error2:
  5412. reg[0] = module;
  5413. reg[1] = function;
  5414. reg[2] = args;
  5415. return 0;
  5416. }
  5417. /* The module argument may be either an atom or an abstract module
  5418. * (currently implemented using tuples, but this might change).
  5419. */
  5420. this = THE_NON_VALUE;
  5421. if (is_not_atom(module)) {
  5422. Eterm* tp;
  5423. if (is_not_tuple(module)) goto error;
  5424. tp = tuple_val(module);
  5425. if (arityval(tp[0]) < 1) goto error;
  5426. this = module;
  5427. module = tp[1];
  5428. if (is_not_atom(module)) goto error;
  5429. }
  5430. /*
  5431. * Walk down the 3rd parameter of apply (the argument list) and copy
  5432. * the parameters to the x registers (reg[]). If the module argument
  5433. * was an abstract module, add 1 to the function arity and put the
  5434. * module argument in the n+1st x register as a THIS reference.
  5435. */
  5436. tmp = args;
  5437. arity = 0;
  5438. while (is_list(tmp)) {
  5439. if (arity < (MAX_REG - 1)) {
  5440. reg[arity++] = CAR(list_val(tmp));
  5441. tmp = CDR(list_val(tmp));
  5442. } else {
  5443. p->freason = SYSTEM_LIMIT;
  5444. goto error2;
  5445. }
  5446. }
  5447. if (is_not_nil(tmp)) { /* Must be well-formed list */
  5448. goto error;
  5449. }
  5450. if (this != THE_NON_VALUE) {
  5451. reg[arity++] = this;
  5452. }
  5453. /*
  5454. * Get the index into the export table, or failing that the export
  5455. * entry for the error handler.
  5456. *
  5457. * Note: All BIFs have export entries; thus, no special case is needed.
  5458. */
  5459. if ((ep = erts_find_export_entry(module, function, arity)) == NULL) {
  5460. if ((ep = apply_setup_error_handler(p, module, function, arity, reg)) == NULL) goto error;
  5461. } else if (ERTS_PROC_GET_SAVED_CALLS_BUF(p)) {
  5462. save_calls(p, ep);
  5463. }
  5464. return ep->address;
  5465. }
  5466. static BeamInstr*
  5467. fixed_apply(Process* p, Eterm* reg, Uint arity)
  5468. {
  5469. Export* ep;
  5470. Eterm module;
  5471. Eterm function;
  5472. module = reg[arity]; /* The THIS pointer already in place */
  5473. function = reg[arity+1];
  5474. if (is_not_atom(function)) {
  5475. error:
  5476. p->freason = BADARG;
  5477. reg[0] = module;
  5478. reg[1] = function;
  5479. reg[2] = NIL;
  5480. return 0;
  5481. }
  5482. /* The module argument may be either an atom or an abstract module
  5483. * (currently implemented using tuples, but this might change).
  5484. */
  5485. if (is_not_atom(module)) {
  5486. Eterm* tp;
  5487. if (is_not_tuple(module)) goto error;
  5488. tp = tuple_val(module);
  5489. if (arityval(tp[0]) < 1) goto error;
  5490. module = tp[1];
  5491. if (is_not_atom(module)) goto error;
  5492. ++arity;
  5493. }
  5494. /*
  5495. * Get the index into the export table, or failing that the export
  5496. * entry for the error handler module.
  5497. *
  5498. * Note: All BIFs have export entries; thus, no special case is needed.
  5499. */
  5500. if ((ep = erts_find_export_entry(module, function, arity)) == NULL) {
  5501. if ((ep = apply_setup_error_handler(p, module, function, arity, reg)) == NULL)
  5502. goto error;
  5503. } else if (ERTS_PROC_GET_SAVED_CALLS_BUF(p)) {
  5504. save_calls(p, ep);
  5505. }
  5506. return ep->address;
  5507. }
  5508. static int
  5509. hibernate(Process* c_p, Eterm module, Eterm function, Eterm args, Eterm* reg)
  5510. {
  5511. int arity;
  5512. Eterm tmp;
  5513. if (is_not_atom(module) || is_not_atom(function)) {
  5514. /*
  5515. * No need to test args here -- done below.
  5516. */
  5517. error:
  5518. c_p->freason = BADARG;
  5519. error2:
  5520. reg[0] = module;
  5521. reg[1] = function;
  5522. reg[2] = args;
  5523. return 0;
  5524. }
  5525. arity = 0;
  5526. tmp = args;
  5527. while (is_list(tmp)) {
  5528. if (arity < MAX_REG) {
  5529. tmp = CDR(list_val(tmp));
  5530. arity++;
  5531. } else {
  5532. c_p->freason = SYSTEM_LIMIT;
  5533. goto error2;
  5534. }
  5535. }
  5536. if (is_not_nil(tmp)) { /* Must be well-formed list */
  5537. goto error;
  5538. }
  5539. /*
  5540. * At this point, arguments are known to be good.
  5541. */
  5542. if (c_p->arg_reg != c_p->def_arg_reg) {
  5543. /* Save some memory */
  5544. erts_free(ERTS_ALC_T_ARG_REG, c_p->arg_reg);
  5545. c_p->arg_reg = c_p->def_arg_reg;
  5546. c_p->max_arg_reg = sizeof(c_p->def_arg_reg)/sizeof(c_p->def_arg_reg[0]);
  5547. }
  5548. /*
  5549. * Arrange for the process to be resumed at the given MFA with
  5550. * the stack cleared.
  5551. */
  5552. c_p->arity = 3;
  5553. c_p->arg_reg[0] = module;
  5554. c_p->arg_reg[1] = function;
  5555. c_p->arg_reg[2] = args;
  5556. c_p->stop = STACK_START(c_p);
  5557. c_p->catches = 0;
  5558. c_p->i = beam_apply;
  5559. c_p->cp = (BeamInstr *) beam_apply+1;
  5560. /*
  5561. * If there are no waiting messages, garbage collect and
  5562. * shrink the heap.
  5563. */
  5564. erts_smp_proc_lock(c_p, ERTS_PROC_LOCK_MSGQ|ERTS_PROC_LOCK_STATUS);
  5565. ERTS_SMP_MSGQ_MV_INQ2PRIVQ(c_p);
  5566. if (c_p->msg.len > 0) {
  5567. erts_add_to_runq(c_p);
  5568. } else {
  5569. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCK_MSGQ|ERTS_PROC_LOCK_STATUS);
  5570. c_p->fvalue = NIL;
  5571. PROCESS_MAIN_CHK_LOCKS(c_p);
  5572. erts_garbage_collect_hibernate(c_p);
  5573. ERTS_VERIFY_UNUSED_TEMP_ALLOC(c_p);
  5574. PROCESS_MAIN_CHK_LOCKS(c_p);
  5575. erts_smp_proc_lock(c_p, ERTS_PROC_LOCK_MSGQ|ERTS_PROC_LOCK_STATUS);
  5576. ASSERT(!ERTS_PROC_IS_EXITING(c_p));
  5577. c_p->status = P_WAITING;
  5578. #ifdef ERTS_SMP
  5579. ERTS_SMP_MSGQ_MV_INQ2PRIVQ(c_p);
  5580. if (c_p->msg.len > 0)
  5581. erts_add_to_runq(c_p);
  5582. #endif
  5583. }
  5584. erts_smp_proc_unlock(c_p, ERTS_PROC_LOCK_MSGQ|ERTS_PROC_LOCK_STATUS);
  5585. c_p->current = bif_export[BIF_hibernate_3]->code;
  5586. return 1;
  5587. }
  5588. static BeamInstr*
  5589. call_fun(Process* p, /* Current process. */
  5590. int arity, /* Number of arguments for Fun. */
  5591. Eterm* reg, /* Contents of registers. */
  5592. Eterm args) /* THE_NON_VALUE or pre-built list of arguments. */
  5593. {
  5594. Eterm fun = reg[arity];
  5595. Eterm hdr;
  5596. int i;
  5597. Eterm function;
  5598. Eterm* hp;
  5599. if (!is_boxed(fun)) {
  5600. goto badfun;
  5601. }
  5602. hdr = *boxed_val(fun);
  5603. if (is_fun_header(hdr)) {
  5604. ErlFunThing* funp = (ErlFunThing *) fun_val(fun);
  5605. ErlFunEntry* fe;
  5606. BeamInstr* code_ptr;
  5607. Eterm* var_ptr;
  5608. int actual_arity;
  5609. unsigned num_free;
  5610. fe = funp->fe;
  5611. num_free = funp->num_free;
  5612. code_ptr = fe->address;
  5613. actual_arity = (int) code_ptr[-1];
  5614. if (actual_arity == arity+num_free) {
  5615. if (num_free == 0) {
  5616. return code_ptr;
  5617. } else {
  5618. var_ptr = funp->env;
  5619. reg += arity;
  5620. i = 0;
  5621. do {
  5622. reg[i] = var_ptr[i];
  5623. i++;
  5624. } while (i < num_free);
  5625. reg[i] = fun;
  5626. return code_ptr;
  5627. }
  5628. return code_ptr;
  5629. } else {
  5630. /*
  5631. * Something wrong here. First build a list of the arguments.
  5632. */
  5633. if (is_non_value(args)) {
  5634. Uint sz = 2 * arity;
  5635. args = NIL;
  5636. if (HeapWordsLeft(p) < sz) {
  5637. erts_garbage_collect(p, sz, reg, arity+1);
  5638. fun = reg[arity];
  5639. }
  5640. hp = HEAP_TOP(p);
  5641. HEAP_TOP(p) += sz;
  5642. for (i = arity-1; i >= 0; i--) {
  5643. args = CONS(hp, reg[i], args);
  5644. hp += 2;
  5645. }
  5646. }
  5647. if (actual_arity >= 0) {
  5648. /*
  5649. * There is a fun defined, but the call has the wrong arity.
  5650. */
  5651. hp = HAlloc(p, 3);
  5652. p->freason = EXC_BADARITY;
  5653. p->fvalue = TUPLE2(hp, fun, args);
  5654. return NULL;
  5655. } else {
  5656. Export* ep;
  5657. Module* modp;
  5658. Eterm module;
  5659. /*
  5660. * No arity. There is no module loaded that defines the fun,
  5661. * either because the fun is newly created from the external
  5662. * representation (the module has never been loaded),
  5663. * or the module defining the fun has been unloaded.
  5664. */
  5665. module = fe->module;
  5666. if ((modp = erts_get_module(module)) != NULL && modp->code != NULL) {
  5667. /*
  5668. * There is a module loaded, but obviously the fun is not
  5669. * defined in it. We must not call the error_handler
  5670. * (or we will get into an infinite loop).
  5671. */
  5672. goto badfun;
  5673. }
  5674. /*
  5675. * No current code for this module. Call the error_handler module
  5676. * to attempt loading the module.
  5677. */
  5678. ep = erts_find_function(erts_proc_get_error_handler(p),
  5679. am_undefined_lambda, 3);
  5680. if (ep == NULL) { /* No error handler */
  5681. p->current = NULL;
  5682. p->freason = EXC_UNDEF;
  5683. return NULL;
  5684. }
  5685. reg[0] = module;
  5686. reg[1] = fun;
  5687. reg[2] = args;
  5688. return ep->address;
  5689. }
  5690. }
  5691. } else if (is_export_header(hdr)) {
  5692. Export *ep;
  5693. int actual_arity;
  5694. ep = *((Export **) (export_val(fun) + 1));
  5695. actual_arity = (int) ep->code[2];
  5696. if (arity == actual_arity) {
  5697. return ep->address;
  5698. } else {
  5699. /*
  5700. * Wrong arity. First build a list of the arguments.
  5701. */
  5702. if (is_non_value(args)) {
  5703. args = NIL;
  5704. hp = HAlloc(p, arity*2);
  5705. for (i = arity-1; i >= 0; i--) {
  5706. args = CONS(hp, reg[i], args);
  5707. hp += 2;
  5708. }
  5709. }
  5710. hp = HAlloc(p, 3);
  5711. p->freason = EXC_BADARITY;
  5712. p->fvalue = TUPLE2(hp, fun, args);
  5713. return NULL;
  5714. }
  5715. } else if (hdr == make_arityval(2)) {
  5716. Eterm* tp;
  5717. Export* ep;
  5718. Eterm module;
  5719. tp = tuple_val(fun);
  5720. module = tp[1];
  5721. function = tp[2];
  5722. if (!is_atom(module) || !is_atom(function)) {
  5723. goto badfun;
  5724. }
  5725. if ((ep = erts_find_export_entry(module, function, arity)) == NULL) {
  5726. ep = erts_find_export_entry(erts_proc_get_error_handler(p),
  5727. am_undefined_function, 3);
  5728. if (ep == NULL) {
  5729. p->freason = EXC_UNDEF;
  5730. return 0;
  5731. }
  5732. if (is_non_value(args)) {
  5733. Uint sz = 2 * arity;
  5734. if (HeapWordsLeft(p) < sz) {
  5735. erts_garbage_collect(p, sz, reg, arity);
  5736. }
  5737. hp = HEAP_TOP(p);
  5738. HEAP_TOP(p) += sz;
  5739. args = NIL;
  5740. while (arity-- > 0) {
  5741. args = CONS(hp, reg[arity], args);
  5742. hp += 2;
  5743. }
  5744. }
  5745. reg[0] = module;
  5746. reg[1] = function;
  5747. reg[2] = args;
  5748. }
  5749. return ep->address;
  5750. } else {
  5751. badfun:
  5752. p->current = NULL;
  5753. p->freason = EXC_BADFUN;
  5754. p->fvalue = fun;
  5755. return NULL;
  5756. }
  5757. }
  5758. static BeamInstr*
  5759. apply_fun(Process* p, Eterm fun, Eterm args, Eterm* reg)
  5760. {
  5761. int arity;
  5762. Eterm tmp;
  5763. /*
  5764. * Walk down the 3rd parameter of apply (the argument list) and copy
  5765. * the parameters to the x registers (reg[]).
  5766. */
  5767. tmp = args;
  5768. arity = 0;
  5769. while (is_list(tmp)) {
  5770. if (arity < MAX_REG-1) {
  5771. reg[arity++] = CAR(list_val(tmp));
  5772. tmp = CDR(list_val(tmp));
  5773. } else {
  5774. p->freason = SYSTEM_LIMIT;
  5775. return NULL;
  5776. }
  5777. }
  5778. if (is_not_nil(tmp)) { /* Must be well-formed list */
  5779. p->freason = EXC_UNDEF;
  5780. return NULL;
  5781. }
  5782. reg[arity] = fun;
  5783. return call_fun(p, arity, reg, args);
  5784. }
  5785. static Eterm
  5786. new_fun(Process* p, Eterm* reg, ErlFunEntry* fe, int num_free)
  5787. {
  5788. unsigned needed = ERL_FUN_SIZE + num_free;
  5789. ErlFunThing* funp;
  5790. Eterm* hp;
  5791. int i;
  5792. if (HEAP_LIMIT(p) - HEAP_TOP(p) <= needed) {
  5793. PROCESS_MAIN_CHK_LOCKS(p);
  5794. erts_garbage_collect(p, needed, reg, num_free);
  5795. ERTS_VERIFY_UNUSED_TEMP_ALLOC(p);
  5796. PROCESS_MAIN_CHK_LOCKS(p);
  5797. }
  5798. hp = p->htop;
  5799. p->htop = hp + needed;
  5800. funp = (ErlFunThing *) hp;
  5801. hp = funp->env;
  5802. erts_refc_inc(&fe->refc, 2);
  5803. funp->thing_word = HEADER_FUN;
  5804. #ifndef HYBRID /* FIND ME! */
  5805. funp->next = MSO(p).first;
  5806. MSO(p).first = (struct erl_off_heap_header*) funp;
  5807. #endif
  5808. funp->fe = fe;
  5809. funp->num_free = num_free;
  5810. funp->creator = p->id;
  5811. #ifdef HIPE
  5812. funp->native_address = fe->native_address;
  5813. #endif
  5814. funp->arity = (int)fe->address[-1] - num_free;
  5815. for (i = 0; i < num_free; i++) {
  5816. *hp++ = reg[i];
  5817. }
  5818. return make_fun(funp);
  5819. }
  5820. int catchlevel(Process *p)
  5821. {
  5822. return p->catches;
  5823. }
  5824. /*
  5825. * Check if the given function is built-in (i.e. a BIF implemented in C).
  5826. *
  5827. * Returns 0 if not built-in, and a non-zero value if built-in.
  5828. */
  5829. int
  5830. erts_is_builtin(Eterm Mod, Eterm Name, int arity)
  5831. {
  5832. Export e;
  5833. Export* ep;
  5834. e.code[0] = Mod;
  5835. e.code[1] = Name;
  5836. e.code[2] = arity;
  5837. if ((ep = export_get(&e)) == NULL) {
  5838. return 0;
  5839. }
  5840. return ep->address == ep->code+3 && (ep->code[3] == (BeamInstr) em_apply_bif);
  5841. }
  5842. /*
  5843. * Return the current number of reductions for the given process.
  5844. * To get the total number of reductions, p->reds must be added.
  5845. */
  5846. Uint
  5847. erts_current_reductions(Process *current, Process *p)
  5848. {
  5849. if (current != p) {
  5850. return 0;
  5851. } else if (current->fcalls < 0 && ERTS_PROC_GET_SAVED_CALLS_BUF(current)) {
  5852. return -current->fcalls;
  5853. } else {
  5854. return REDS_IN(current) - current->fcalls;
  5855. }
  5856. }