runtime/kp_vm.c - ktap

Global variables defined

Functions defined

Macros defined

Source code

  1. /*
  2. * kp_vm.c - ktap script virtual machine in Linux kernel
  3. *
  4. * This file is part of ktap by Jovi Zhangwei.
  5. *
  6. * Copyright (C) 2012-2013 Jovi Zhangwei <jovi.zhangwei@gmail.com>.
  7. *
  8. * Adapted from luajit and lua interpreter.
  9. * Copyright (C) 2005-2014 Mike Pall.
  10. * Copyright (C) 1994-2008 Lua.org, PUC-Rio.
  11. *
  12. * ktap is free software; you can redistribute it and/or modify it
  13. * under the terms and conditions of the GNU General Public License,
  14. * version 2, as published by the Free Software Foundation.
  15. *
  16. * ktap is distributed in the hope it will be useful, but WITHOUT
  17. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  18. * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  19. * more details.
  20. *
  21. * You should have received a copy of the GNU General Public License along with
  22. * this program; if not, write to the Free Software Foundation, Inc.,
  23. * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
  24. */

  25. #include <linux/slab.h>
  26. #include <linux/ftrace_event.h>
  27. #include <linux/signal.h>
  28. #include <linux/sched.h>
  29. #include <linux/uaccess.h>
  30. #include "../include/ktap_types.h"
  31. #include "../include/ktap_bc.h"
  32. #include "../include/ktap_ffi.h"
  33. #include "ktap.h"
  34. #include "kp_obj.h"
  35. #include "kp_str.h"
  36. #include "kp_mempool.h"
  37. #include "kp_tab.h"
  38. #include "kp_transport.h"
  39. #include "kp_vm.h"
  40. #include "kp_events.h"

  41. #define KTAP_MIN_RESERVED_STACK_SIZE 20
  42. #define KTAP_STACK_SIZE        120 /* enlarge this value for big stack */
  43. #define KTAP_STACK_SIZE_BYTES    (KTAP_STACK_SIZE * sizeof(ktap_val_t))

  44. #define KTAP_PERCPU_BUFFER_SIZE    (3 * PAGE_SIZE)

  45. static ktap_cfunction gfunc_get(ktap_state_t *ks, int idx);
  46. static int gfunc_getidx(ktap_global_state_t *g, ktap_cfunction cfunc);

  47. static ktap_str_t *str_concat(ktap_state_t *ks, StkId top, int start, int end)
  48. {
  49.     int i, len = 0;
  50.     ktap_str_t *ts;
  51.     char *ptr, *buffer;

  52.     for (i = start; i <= end; i++) {
  53.         if (!is_string(top + i)) {
  54.             kp_error(ks, "cannot concat non-string\n");
  55.             return NULL;
  56.         }

  57.         len += rawtsvalue(top + i)->len;
  58.     }

  59.     if (len >= KTAP_PERCPU_BUFFER_SIZE) {
  60.         kp_error(ks, "Error: too long string concatenation\n");
  61.         return NULL;
  62.     }

  63.     preempt_disable_notrace();

  64.     buffer = kp_this_cpu_print_buffer(ks);
  65.     ptr = buffer;

  66.     for (i = start; i <= end; i++) {
  67.         int len = rawtsvalue(top + i)->len;
  68.         strncpy(ptr, svalue(top + i), len);
  69.         ptr += len;
  70.     }
  71.     ts = kp_str_new(ks, buffer, len);

  72.     preempt_enable_notrace();

  73.     return ts;
  74. }

  75. static ktap_upval_t *findupval(ktap_state_t *ks, StkId slot)
  76. {
  77.     ktap_global_state_t *g = G(ks);
  78.     ktap_upval_t **pp = &ks->openupval;
  79.     ktap_upval_t *p;
  80.     ktap_upval_t *uv;

  81.     while (*pp != NULL && (p = *pp)->v >= slot) {
  82.         if (p->v == slot) {  /* found a corresponding upvalue? */
  83.             return p;
  84.         }
  85.         pp = (ktap_upval_t **)&p->nextgc;
  86.     }

  87.     /* not found: create a new one */
  88.     uv = (ktap_upval_t *)kp_malloc(ks, sizeof(ktap_upval_t));
  89.     if (!uv)
  90.         return NULL;
  91.     uv->gct = ~KTAP_TUPVAL;
  92.     uv->closed = 0; /* still open */
  93.     uv->v = slot;  /* current value lives in the stack */
  94.     /* Insert into sorted list of open upvalues. */
  95.     uv->nextgc = (ktap_obj_t *)*pp;
  96.     *pp = uv;
  97.     uv->prev = &g->uvhead;  /* double link it in `uvhead' list */
  98.     uv->next = g->uvhead.next;
  99.     uv->next->prev = uv;
  100.     g->uvhead.next = uv;
  101.     return uv;
  102. }

  103. static void unlinkupval(ktap_upval_t *uv)
  104. {
  105.     uv->next->prev = uv->prev;  /* remove from `uvhead' list */
  106.     uv->prev->next = uv->next;
  107. }

  108. void kp_freeupval(ktap_state_t *ks, ktap_upval_t *uv)
  109. {
  110.     if (!uv->closed)  /* is it open? */
  111.         unlinkupval(uv);  /* remove from open list */
  112.     kp_free(ks, uv);  /* free upvalue */
  113. }

  114. /* close upvals */
  115. static void func_closeuv(ktap_state_t *ks, StkId level)
  116. {
  117.     ktap_upval_t *uv;
  118.     ktap_global_state_t *g = G(ks);
  119.     while (ks->openupval != NULL &&
  120.         (uv = ks->openupval)->v >= level) {
  121.         ktap_obj_t *o = obj2gco(uv);
  122.         /* remove from `open' list */
  123.         ks->openupval = (ktap_upval_t *)uv->nextgc;
  124.         unlinkupval(uv);  /* remove upvalue from 'uvhead' list */
  125.         set_obj(&uv->tv, uv->v);  /* move value to upvalue slot */
  126.         uv->v = &uv->tv;  /* now current value lives here */
  127.         uv->closed = 1;
  128.         gch(o)->nextgc = g->allgc; /* link upvalue into 'allgc' list */
  129.         g->allgc = o;
  130.     }
  131. }

  132. #define SIZE_KTAP_FUNC(n) (sizeof(ktap_func_t) - sizeof(ktap_obj_t *) + \
  133.                sizeof(ktap_obj_t *) * (n))
  134. static ktap_func_t *func_new_empty(ktap_state_t *ks, ktap_proto_t *pt)
  135. {
  136.     ktap_func_t *fn;

  137.     /* only mainthread can create new function */
  138.     if (ks != G(ks)->mainthread) {
  139.         kp_error(ks, "only mainthread can create function\n");
  140.         return NULL;
  141.     }

  142.     fn = (ktap_func_t *)kp_obj_new(ks, SIZE_KTAP_FUNC(pt->sizeuv));
  143.     if (!fn)
  144.         return NULL;
  145.     fn->gct = ~KTAP_TFUNC;
  146.     fn->nupvalues = 0; /* Set to zero until upvalues are initialized. */
  147.     fn->pc = proto_bc(pt);
  148.     fn->p = pt;

  149.     return fn;
  150. }

  151. static ktap_func_t *func_new(ktap_state_t *ks, ktap_proto_t *pt,
  152.                  ktap_func_t *parent, ktap_val_t *base)
  153. {
  154.     ktap_func_t *fn;
  155.     int nuv = pt->sizeuv, i;

  156.     fn = func_new_empty(ks, pt);
  157.     if (!fn)
  158.         return NULL;

  159.     fn->nupvalues = nuv;
  160.     for (i = 0; i < nuv; i++) {
  161.         uint32_t v = proto_uv(pt)[i];
  162.         ktap_upval_t *uv;

  163.         if (v & PROTO_UV_LOCAL) {
  164.             uv = findupval(ks, base + (v & 0xff));
  165.             if (!uv)
  166.                 return NULL;
  167.             uv->immutable = ((v /PROTO_UV_IMMUTABLE) & 1);
  168.         } else {
  169.             uv = parent->upvals[v];
  170.         }
  171.         fn->upvals[i] = uv;
  172.     }
  173.     return fn;
  174. }

  175. static inline int checkstack(ktap_state_t *ks, int n)
  176. {
  177.     if (unlikely(ks->stack_last - ks->top <= n)) {
  178.         kp_error(ks, "stack overflow, please enlarge stack size\n");
  179.         return -1;
  180.     }
  181.     return 0;
  182. }

  183. static StkId adjust_varargs(ktap_state_t *ks, ktap_proto_t *p, int actual)
  184. {
  185.     int i;
  186.     int nfixargs = p->numparams;
  187.     StkId base, fixed;

  188.     /* move fixed parameters to final position */
  189.     fixed = ks->top - actual;  /* first fixed argument */
  190.     base = ks->top;  /* final position of first argument */

  191.     for (i=0; i < nfixargs; i++) {
  192.         set_obj(ks->top++, fixed + i);
  193.         set_nil(fixed + i);
  194.     }

  195.     return base;
  196. }

  197. static void poscall(ktap_state_t *ks, StkId func, StkId first_result,
  198.            int wanted)
  199. {
  200.     int i;

  201.     for (i = wanted; i != 0 && first_result < ks->top; i--)
  202.         set_obj(func++, first_result++);

  203.     while(i-- > 0)
  204.         set_nil(func++);
  205. }

  206. void kp_vm_call_proto(ktap_state_t *ks, ktap_proto_t *pt)
  207. {
  208.     ktap_func_t *fn;

  209.     fn = func_new_empty(ks, pt);
  210.     if (!fn)
  211.         return;
  212.     set_func(ks->top++, fn);
  213.     kp_vm_call(ks, ks->top - 1, 0);
  214. }

  215. /*
  216. * Hot loop detaction
  217. *
  218. * Check hot loop detaction in three cases:
  219. * 1. jmp -x: this happens in 'while (expr) { ... }'
  220. * 2. FORPREP-FORLOOP
  221. * 3. TFORCALL-TFORLOOP
  222. */
  223. static __always_inline int check_hot_loop(ktap_state_t *ks, int loop_count)
  224. {
  225.     if (unlikely(loop_count == kp_max_loop_count)) {
  226.         kp_error(ks, "loop execute count exceed max limit(%d)\n",
  227.                  kp_max_loop_count);
  228.         return -1;
  229.     }

  230.     return 0;
  231. }

  232. #define dojump(i, e) { pc += (int)bc_d(i) - BCBIAS_J + e; }
  233. #define donextjump  { instr = *pc; dojump(instr, 1); }

  234. #define NUMADD(a, b)    ((a) + (b))
  235. #define NUMSUB(a, b)    ((a) - (b))
  236. #define NUMMUL(a, b)    ((a) * (b))
  237. #define NUMDIV(a, b)    ((a) / (b))
  238. #define NUMUNM(a)       (-(a))
  239. #define NUMEQ(a, b)     ((a) == (b))
  240. #define NUMLT(a, b)     ((a) < (b))
  241. #define NUMLE(a, b)     ((a) <= (b))
  242. #define NUMMOD(a, b)    ((a) % (b))

  243. #define arith_VV(ks, op) { \
  244.     ktap_val_t *rb = RB; \
  245.     ktap_val_t *rc = RC; \
  246.     if (is_number(rb) && is_number(rc)) { \
  247.         ktap_number nb = nvalue(rb), nc = nvalue(rc); \
  248.         set_number(RA, op(nb, nc)); \
  249.     } else {    \
  250.         kp_puts(ks, "Error: Cannot make arith operation\n");    \
  251.         return;    \
  252.     } }

  253. #define arith_VN(ks, op) { \
  254.     ktap_val_t *rb = RB; \
  255.     if (is_number(rb)) { \
  256.         ktap_number nb = nvalue(rb);\
  257.         ktap_number nc = nvalue((ktap_val_t *)kbase + bc_c(instr));\
  258.         set_number(RA, op(nb, nc)); \
  259.     } else {    \
  260.         kp_puts(ks, "Error: Cannot make arith operation\n");    \
  261.         return;    \
  262.     } }

  263. #define arith_NV(ks, op) { \
  264.     ktap_val_t *rb = RB; \
  265.     if (is_number(rb)) { \
  266.         ktap_number nb = nvalue(rb);\
  267.         ktap_number nc = nvalue((ktap_val_t *)kbase + bc_c(instr));\
  268.         set_number(RA, op(nc, nb)); \
  269.     } else {    \
  270.         kp_puts(ks, "Error: Cannot make arith operation\n");    \
  271.         return;    \
  272.     } }


  273. static const char * const bc_names[] = {
  274. #define BCNAME(name, ma, mb, mc, mt)       #name,
  275.     BCDEF(BCNAME)
  276. #undef BCNAME
  277.     NULL
  278. };


  279. /*
  280. * ktap bytecode interpreter routine
  281. *
  282. *
  283. * kp_vm_call only can be used for:
  284. * 1). call ktap function, not light C function
  285. * 2). accept fixed argument function
  286. */
  287. void kp_vm_call(ktap_state_t *ks, StkId func, int nresults)
  288. {
  289.     int loop_count = 0;
  290.     ktap_func_t *fn;
  291.     ktap_proto_t *pt;
  292.     ktap_obj_t **kbase;
  293.     unsigned int instr, op;
  294.     const unsigned int *pc;
  295.     StkId base; /* stack pointer */
  296.     int multres = 0; /* temp varible */
  297.     ktap_tab_t *gtab = G(ks)->gtab;

  298.     /* use computed goto for opcode dispatch */

  299.     static void *dispatch_table[] = {
  300. #define BCNAME(name, ma, mb, mc, mt)       &&DO_BC_##name,
  301.         BCDEF(BCNAME)
  302. #undef BCNAME
  303.     };

  304. #define DISPATCH()                \
  305.     do {                    \
  306.         instr = *(pc++);        \
  307.         op = bc_op(instr);        \
  308.         goto *dispatch_table[op];    \
  309.     } while (0)

  310. #define RA    (base + bc_a(instr))
  311. #define RB    (base + bc_b(instr))
  312. #define RC    (base + bc_c(instr))
  313. #define RD    (base + bc_d(instr))
  314. #define RKD    ((ktap_val_t *)kbase + bc_d(instr))

  315.     /*TODO: fix argument number mismatch, example: sort cmp closure */

  316.     fn = clvalue(func);
  317.     pt = fn->p;
  318.     kbase = fn->p->k;
  319.     base = func + 1;
  320.     pc = proto_bc(pt) + 1;
  321.     ks->top = base + pt->framesize;
  322.     func->pcr = 0; /* no previous frame */

  323.     /* main loop of interpreter */
  324.     DISPATCH();

  325.     while (1) {
  326.     DO_BC_ISLT: /* Jump if A < D */
  327.         if (!is_number(RA) || !is_number(RD)) {
  328.             kp_error(ks, "compare with non-number\n");
  329.             return;
  330.         }

  331.         if (nvalue(RA) >= nvalue(RD))
  332.             pc++;
  333.         else
  334.             donextjump;
  335.         DISPATCH();
  336.     DO_BC_ISGE: /* Jump if A >= D */
  337.         if (!is_number(RA) || !is_number(RD)) {
  338.             kp_error(ks, "compare with non-number\n");
  339.             return;
  340.         }

  341.         if (nvalue(RA) < nvalue(RD))
  342.             pc++;
  343.         else
  344.             donextjump;
  345.         DISPATCH();
  346.     DO_BC_ISLE: /* Jump if A <= D */
  347.         if (!is_number(RA) || !is_number(RD)) {
  348.             kp_error(ks, "compare with non-number\n");
  349.             return;
  350.         }

  351.         if (nvalue(RA) > nvalue(RD))
  352.             pc++;
  353.         else
  354.             donextjump;
  355.         DISPATCH();
  356.     DO_BC_ISGT: /* Jump if A > D */
  357.         if (!is_number(RA) || !is_number(RD)) {
  358.             kp_error(ks, "compare with non-number\n");
  359.             return;
  360.         }

  361.         if (nvalue(RA) <= nvalue(RD))
  362.             pc++;
  363.         else
  364.             donextjump;
  365.         DISPATCH();
  366.     DO_BC_ISEQV: /* Jump if A = D */
  367.         if (!kp_obj_equal(RA, RD))
  368.             pc++;
  369.         else
  370.             donextjump;
  371.         DISPATCH();
  372.     DO_BC_ISNEV: /* Jump if A != D */
  373.         if (kp_obj_equal(RA, RD))
  374.             pc++;
  375.         else
  376.             donextjump;
  377.         DISPATCH();
  378.     DO_BC_ISEQS: { /* Jump if A = D */
  379.         int idx = ~bc_d(instr);

  380.         if (!is_string(RA) ||
  381.                 rawtsvalue(RA) != (ktap_str_t *)kbase[idx])
  382.             pc++;
  383.         else
  384.             donextjump;
  385.         DISPATCH();
  386.         }
  387.     DO_BC_ISNES: { /* Jump if A != D */
  388.         int idx = ~bc_d(instr);

  389.         if (is_string(RA) &&
  390.             rawtsvalue(RA) == (ktap_str_t *)kbase[idx])
  391.             pc++;
  392.         else
  393.             donextjump;
  394.         DISPATCH();
  395.         }
  396.     DO_BC_ISEQN: /* Jump if A = D */
  397.         if (!is_number(RA) || nvalue(RA) !=  nvalue(RKD))
  398.             pc++;
  399.         else
  400.             donextjump;
  401.         DISPATCH();
  402.     DO_BC_ISNEN: /* Jump if A != D */
  403.         if (is_number(RA) && nvalue(RA) ==  nvalue(RKD))
  404.             pc++;
  405.         else
  406.             donextjump;
  407.         DISPATCH();
  408.     DO_BC_ISEQP: /* Jump if A = D */
  409.         if (itype(RA) != ~bc_d(instr))
  410.             pc++;
  411.         else
  412.             donextjump;
  413.         DISPATCH();
  414.     DO_BC_ISNEP: /* Jump if A != D */
  415.         if (itype(RA) == ~bc_d(instr))
  416.             pc++;
  417.         else
  418.             donextjump;
  419.         DISPATCH();
  420.     DO_BC_ISTC: /* Copy D to A and jump, if D is true */
  421.         if (itype(RD) == KTAP_TNIL || itype(RD) == KTAP_TFALSE)
  422.             pc++;
  423.         else {
  424.             set_obj(RA, RD);
  425.             donextjump;
  426.         }
  427.         DISPATCH();
  428.     DO_BC_ISFC: /* Copy D to A and jump, if D is false */
  429.         if (itype(RD) != KTAP_TNIL && itype(RD) != KTAP_TFALSE)
  430.             pc++;
  431.         else {
  432.             set_obj(RA, RD);
  433.             donextjump;
  434.         }
  435.         DISPATCH();
  436.     DO_BC_IST: /* Jump if D is true */
  437.         if (itype(RD) == KTAP_TNIL || itype(RD) == KTAP_TFALSE)
  438.             pc++;
  439.         else
  440.             donextjump;
  441.         DISPATCH();
  442.     DO_BC_ISF: /* Jump if D is false */
  443.         /* only nil and false are considered false,
  444.          * all other values are true */
  445.         if (itype(RD) != KTAP_TNIL && itype(RD) != KTAP_TFALSE)
  446.             pc++;
  447.         else
  448.             donextjump;
  449.         DISPATCH();
  450.     DO_BC_ISTYPE: /* generated by genlibbc, not compiler; not used now */
  451.     DO_BC_ISNUM:
  452.         return;
  453.     DO_BC_MOV: /* Copy D to A */
  454.         set_obj(RA, RD);
  455.         DISPATCH();
  456.     DO_BC_NOT: /* Set A to boolean not of D */
  457.         if (itype(RD) == KTAP_TNIL || itype(RD) == KTAP_TFALSE)
  458.             setitype(RA, KTAP_TTRUE);
  459.         else
  460.             setitype(RA, KTAP_TFALSE);

  461.         DISPATCH();
  462.     DO_BC_UNM: /* Set A to -D (unary minus) */
  463.         if (!is_number(RD)) {
  464.             kp_error(ks, "use '-' operator on non-number\n");
  465.             return;
  466.         }

  467.         set_number(RA, -nvalue(RD));
  468.         DISPATCH();
  469.     DO_BC_ADDVN: /* A = B + C */
  470.         arith_VN(ks, NUMADD);
  471.         DISPATCH();
  472.     DO_BC_SUBVN: /* A = B - C */
  473.         arith_VN(ks, NUMSUB);
  474.         DISPATCH();
  475.     DO_BC_MULVN: /* A = B * C */
  476.         arith_VN(ks, NUMMUL);
  477.         DISPATCH();
  478.     DO_BC_DIVVN: /* A = B / C */
  479.         /* divide 0 checking */
  480.         if (!nvalue((ktap_val_t *)kbase + bc_c(instr))) {
  481.             kp_error(ks, "divide 0 arith operation\n");
  482.             return;
  483.         }
  484.         arith_VN(ks, NUMDIV);
  485.         DISPATCH();
  486.     DO_BC_MODVN: /* A = B % C */
  487.         /* divide 0 checking */
  488.         if (!nvalue((ktap_val_t *)kbase + bc_c(instr))) {
  489.             kp_error(ks, "mod 0 arith operation\n");
  490.             return;
  491.         }
  492.         arith_VN(ks, NUMMOD);
  493.         DISPATCH();
  494.     DO_BC_ADDNV: /* A = C + B */
  495.         arith_NV(ks, NUMADD);
  496.         DISPATCH();
  497.     DO_BC_SUBNV: /* A = C - B */
  498.         arith_NV(ks, NUMSUB);
  499.         DISPATCH();
  500.     DO_BC_MULNV: /* A = C * B */
  501.         arith_NV(ks, NUMMUL);
  502.         DISPATCH();
  503.     DO_BC_DIVNV: /* A = C / B */
  504.         /* divide 0 checking */
  505.         if (!nvalue(RB)){
  506.             kp_error(ks, "divide 0 arith operation\n");
  507.             return;
  508.         }
  509.         arith_NV(ks, NUMDIV);
  510.         DISPATCH();
  511.     DO_BC_MODNV: /* A = C % B */
  512.         /* divide 0 checking */
  513.         if (!nvalue(RB)){
  514.             kp_error(ks, "mod 0 arith operation\n");
  515.             return;
  516.         }
  517.         arith_NV(ks, NUMMOD);
  518.         DISPATCH();
  519.     DO_BC_ADDVV: /* A = B + C */
  520.         arith_VV(ks, NUMADD);
  521.         DISPATCH();
  522.     DO_BC_SUBVV: /* A = B - C */
  523.         arith_VV(ks, NUMSUB);
  524.         DISPATCH();
  525.     DO_BC_MULVV: /* A = B * C */
  526.         arith_VV(ks, NUMMUL);
  527.         DISPATCH();
  528.     DO_BC_DIVVV: /* A = B / C */
  529.         arith_VV(ks, NUMDIV);
  530.         DISPATCH();
  531.     DO_BC_MODVV: /* A = B % C */
  532.         arith_VV(ks, NUMMOD);
  533.         DISPATCH();
  534.     DO_BC_POW: /* A = B ^ C, rejected */
  535.         return;
  536.     DO_BC_CAT: { /* A = B .. ~ .. C */
  537.         /* The CAT instruction concatenates all values in
  538.          * variable slots B to C inclusive. */
  539.         ktap_str_t *ts = str_concat(ks, base, bc_b(instr),
  540.                         bc_c(instr));
  541.         if (!ts)
  542.             return;

  543.         set_string(RA, ts);
  544.         DISPATCH();
  545.         }
  546.     DO_BC_KSTR: { /* Set A to string constant D */
  547.         int idx = ~bc_d(instr);
  548.         set_string(RA, (ktap_str_t *)kbase[idx]);
  549.         DISPATCH();
  550.         }
  551.     DO_BC_KCDATA: /* not used now */
  552.         DISPATCH();
  553.     DO_BC_KSHORT: /* Set A to 16 bit signed integer D */
  554.         set_number(RA, bc_d(instr));
  555.         DISPATCH();
  556.     DO_BC_KNUM: /* Set A to number constant D */
  557.         set_number(RA, nvalue(RKD));
  558.         DISPATCH();
  559.     DO_BC_KPRI: /* Set A to primitive D */
  560.         setitype(RA, ~bc_d(instr));
  561.         DISPATCH();
  562.     DO_BC_KNIL: { /* Set slots A to D to nil */
  563.         int i;
  564.         for (i = 0; i <= bc_d(instr) - bc_a(instr); i++) {
  565.             set_nil(RA + i);
  566.         }
  567.         DISPATCH();
  568.         }
  569.     DO_BC_UGET: /* Set A to upvalue D */
  570.         set_obj(RA, fn->upvals[bc_d(instr)]->v);
  571.         DISPATCH();
  572.     DO_BC_USETV: /* Set upvalue A to D */
  573.         set_obj(fn->upvals[bc_a(instr)]->v, RD);
  574.         DISPATCH();
  575.     DO_BC_UINCV: { /* upvalus[A] += D */
  576.         ktap_val_t *v = fn->upvals[bc_a(instr)]->v;
  577.         if (unlikely(!is_number(RD) || !is_number(v))) {
  578.             kp_error(ks, "use '+=' on non-number\n");
  579.             return;
  580.         }
  581.         set_number(v, nvalue(v) + nvalue(RD));
  582.         DISPATCH();
  583.         }
  584.     DO_BC_USETS: { /* Set upvalue A to string constant D */
  585.         int idx = ~bc_d(instr);
  586.         set_string(fn->upvals[bc_a(instr)]->v,
  587.                 (ktap_str_t *)kbase[idx]);
  588.         DISPATCH();
  589.         }
  590.     DO_BC_USETN: /* Set upvalue A to number constant D */
  591.         set_number(fn->upvals[bc_a(instr)]->v, nvalue(RKD));
  592.         DISPATCH();
  593.     DO_BC_UINCN: { /* upvalus[A] += D */
  594.         ktap_val_t *v = fn->upvals[bc_a(instr)]->v;
  595.         if (unlikely(!is_number(v))) {
  596.             kp_error(ks, "use '+=' on non-number\n");
  597.             return;
  598.         }
  599.         set_number(v, nvalue(v) + nvalue(RKD));
  600.         DISPATCH();
  601.         }
  602.     DO_BC_USETP: /* Set upvalue A to primitive D */
  603.         setitype(fn->upvals[bc_a(instr)]->v, ~bc_d(instr));
  604.         DISPATCH();
  605.     DO_BC_UCLO: /* Close upvalues for slots . rbase and jump to target D */
  606.         if (ks->openupval != NULL)
  607.             func_closeuv(ks, RA);
  608.         dojump(instr, 0);
  609.         DISPATCH();
  610.     DO_BC_FNEW: {
  611.         /* Create new closure from prototype D and store it in A */
  612.         int idx = ~bc_d(instr);
  613.         ktap_func_t *subfn = func_new(ks, (ktap_proto_t *)kbase[idx],
  614.                           fn, base);
  615.         if (unlikely(!subfn))
  616.             return;
  617.         set_func(RA, subfn);
  618.         DISPATCH();
  619.         }
  620.     DO_BC_TNEW: { /* Set A to new table with size D */
  621.         /*
  622.          * preallocate default narr and nrec,
  623.          * op_b and op_c is not used
  624.          * This would allocate more memory for some static table.
  625.          */
  626.         ktap_tab_t *t = kp_tab_new_ah(ks, 0, 0);
  627.         if (unlikely(!t))
  628.             return;
  629.         set_table(RA, t);
  630.         DISPATCH();
  631.         }
  632.     DO_BC_TDUP: { /* Set A to duplicated template table D */
  633.         int idx = ~bc_d(instr);
  634.         ktap_tab_t *t = kp_tab_dup(ks, (ktap_tab_t *)kbase[idx]);
  635.         if (!t)
  636.             return;
  637.         set_table(RA, t);
  638.         DISPATCH();
  639.         }
  640.     DO_BC_GGET: { /* A = _G[D] */
  641.         int idx = ~bc_d(instr);
  642.         kp_tab_getstr(gtab, (ktap_str_t *)kbase[idx], RA);
  643.         DISPATCH();
  644.         }
  645.     DO_BC_GSET: /* _G[D] = A, rejected. */
  646.     DO_BC_GINC: /* _G[D] += A, rejected. */
  647.         return;
  648.     DO_BC_TGETV: /* A = B[C] */
  649.         if (unlikely(!is_table(RB))) {
  650.             kp_error(ks, "get key from non-table\n");
  651.             return;
  652.         }

  653.         kp_tab_get(ks, hvalue(RB), RC, RA);
  654.         DISPATCH();
  655.     DO_BC_TGETS: { /* A = B[C] */
  656.         int idx = ~bc_c(instr);

  657.         if (unlikely(!is_table(RB))) {
  658.             kp_error(ks, "get key from non-table\n");
  659.             return;
  660.         }
  661.         kp_tab_getstr(hvalue(RB), (ktap_str_t *)kbase[idx], RA);
  662.         DISPATCH();
  663.         }
  664.     DO_BC_TGETB: { /* A = B[C] */
  665.         /* 8 bit literal C operand as an unsigned integer
  666.          * index (0..255)) */
  667.         uint8_t idx = bc_c(instr);

  668.         if (unlikely(!is_table(RB))) {
  669.             kp_error(ks, "set key to non-table\n");
  670.             return;
  671.         }
  672.         kp_tab_getint(hvalue(RB), idx, RA);
  673.         DISPATCH();
  674.         }
  675.     DO_BC_TGETR: /* generated by genlibbc, not compiler, not used */
  676.         return;
  677.     DO_BC_TSETV: /* B[C] = A */
  678.         if (unlikely(!is_table(RB))) {
  679.             kp_error(ks, "set key to non-table\n");
  680.             return;
  681.         }
  682.         kp_tab_set(ks, hvalue(RB), RC, RA);
  683.         DISPATCH();
  684.     DO_BC_TINCV: /* B[C] += A */
  685.         if (unlikely(!is_table(RB))) {
  686.             kp_error(ks, "set key to non-table\n");
  687.             return;
  688.         }
  689.         if (unlikely(!is_number(RA))) {
  690.             kp_error(ks, "use '+=' on non-number\n");
  691.             return;
  692.         }
  693.         kp_tab_incr(ks, hvalue(RB), RC, nvalue(RA));
  694.         DISPATCH();
  695.     DO_BC_TSETS: { /* B[C] = A */
  696.         int idx = ~bc_c(instr);

  697.         if (unlikely(!is_table(RB))) {
  698.             kp_error(ks, "set key to non-table\n");
  699.             return;
  700.         }
  701.         kp_tab_setstr(ks, hvalue(RB), (ktap_str_t *)kbase[idx], RA);
  702.         DISPATCH();
  703.         }
  704.     DO_BC_TINCS: { /* B[C] += A */
  705.         int idx = ~bc_c(instr);

  706.         if (unlikely(!is_table(RB))) {
  707.             kp_error(ks, "set key to non-table\n");
  708.             return;
  709.         }
  710.         if (unlikely(!is_number(RA))) {
  711.             kp_error(ks, "use '+=' on non-number\n");
  712.             return;
  713.         }
  714.         kp_tab_incrstr(ks, hvalue(RB), (ktap_str_t *)kbase[idx],
  715.                 nvalue(RA));
  716.         DISPATCH();
  717.         }
  718.     DO_BC_TSETB: { /* B[C] = A */
  719.         /* 8 bit literal C operand as an unsigned integer
  720.          * index (0..255)) */
  721.         uint8_t idx = bc_c(instr);

  722.         if (unlikely(!is_table(RB))) {
  723.             kp_error(ks, "set key to non-table\n");
  724.             return;
  725.         }
  726.         kp_tab_setint(ks, hvalue(RB), idx, RA);
  727.         DISPATCH();
  728.         }
  729.     DO_BC_TINCB: { /* B[C] = A */
  730.         uint8_t idx = bc_c(instr);

  731.         if (unlikely(!is_table(RB))) {
  732.             kp_error(ks, "set key to non-table\n");
  733.             return;
  734.         }
  735.         if (unlikely(!is_number(RA))) {
  736.             kp_error(ks, "use '+=' on non-number\n");
  737.             return;
  738.         }
  739.         kp_tab_incrint(ks, hvalue(RB), idx, nvalue(RA));
  740.         DISPATCH();
  741.         }
  742.     DO_BC_TSETM: /* don't support */
  743.         return;
  744.     DO_BC_TSETR: /* generated by genlibbc, not compiler, not used */
  745.         return;
  746.     DO_BC_CALLM:
  747.     DO_BC_CALL: { /* b: return_number + 1; c: argument + 1 */
  748.         int c = bc_c(instr);
  749.         int nresults = bc_b(instr) - 1;
  750.         StkId oldtop = ks->top;
  751.         StkId newfunc = RA;

  752.         if (op == BC_CALL && c != 0)
  753.             ks->top = RA + c;
  754.         else if (op == BC_CALLM)
  755.             ks->top = RA + c + multres;

  756.         if (itype(newfunc) == KTAP_TCFUNC) { /* light C function */
  757.             ktap_cfunction f = fvalue(newfunc);
  758.             int n;

  759.             if (unlikely(checkstack(ks,
  760.                     KTAP_MIN_RESERVED_STACK_SIZE)))
  761.                 return;

  762.             ks->func = newfunc;
  763.             n = (*f)(ks);
  764.             if (unlikely(n < 0)) /* error occured */
  765.                 return;
  766.             poscall(ks, newfunc, ks->top - n, nresults);

  767.             ks->top = oldtop;
  768.             multres = n + 1; /* set to multres */
  769.             DISPATCH();
  770.         } else if (itype(newfunc) == KTAP_TFUNC) { /* ktap function */
  771.             int n;

  772.             func = newfunc;
  773.             pt = clvalue(func)->p;

  774.             if (unlikely(checkstack(ks, pt->framesize)))
  775.                 return;

  776.             /* get number of real arguments */
  777.             n = (int)(ks->top - func) - 1;

  778.             /* complete missing arguments */
  779.             for (; n < pt->numparams; n++)
  780.                 set_nil(ks->top++);

  781.             base = (!(pt->flags & PROTO_VARARG)) ? func + 1 :
  782.                         adjust_varargs(ks, pt, n);

  783.             fn = clvalue(func);
  784.             pt = fn->p;
  785.             kbase = pt->k;
  786.             func->pcr = pc - 1; /* save pc */
  787.             ks->top = base + pt->framesize;
  788.             pc = proto_bc(pt) + 1; /* starting point */
  789.             DISPATCH();
  790.         } else {
  791.             kp_error(ks, "attempt to call nil function\n");
  792.             return;
  793.         }
  794.         }
  795.     DO_BC_CALLMT: /* don't support */
  796.         return;
  797.     DO_BC_CALLT: { /* Tailcall: return A(A+1, ..., A+D-1) */
  798.         StkId nfunc = RA;

  799.         if (itype(nfunc) == KTAP_TCFUNC) { /* light C function */
  800.             kp_error(ks, "don't support callt for C function");
  801.             return;
  802.         } else if (itype(nfunc) == KTAP_TFUNC) { /* ktap function */
  803.             int aux;

  804.             /*
  805.              * tail call: put called frame (n) in place of
  806.              * caller one (o)
  807.              */
  808.             StkId ofunc = func; /* caller function */
  809.             /* last stack slot filled by 'precall' */
  810.             StkId lim = nfunc + 1 + clvalue(nfunc)->p->numparams;

  811.             fn = clvalue(nfunc);
  812.             ofunc->val = nfunc->val;

  813.             /* move new frame into old one */
  814.             for (aux = 1; nfunc + aux < lim; aux++)
  815.                 set_obj(ofunc + aux, nfunc + aux);

  816.             pt = fn->p;
  817.             kbase = pt->k;
  818.             ks->top = base + pt->framesize;
  819.             pc = proto_bc(pt) + 1; /* starting point */
  820.             DISPATCH();
  821.         } else {
  822.             kp_error(ks, "attempt to call nil function\n");
  823.             return;
  824.         }
  825.         }
  826.     DO_BC_ITERC: /* don't support it now */
  827.         return;
  828.     DO_BC_ITERN: /* Specialized ITERC, if iterator function A-3 is next()*/
  829.         /* detect hot loop */
  830.         if (unlikely(check_hot_loop(ks, loop_count++) < 0))
  831.             return;

  832.         if (kp_tab_next(ks, hvalue(RA - 2), RA)) {
  833.             donextjump; /* Get jump target from ITERL */
  834.         } else {
  835.             pc++; /* jump to ITERL + 1 */
  836.         }
  837.         DISPATCH();
  838.     DO_BC_VARG: /* don't support */
  839.         return;
  840.     DO_BC_ISNEXT: /* Verify ITERN specialization and jump */
  841.         if (!is_cfunc(RA - 3) || !is_table(RA - 2) || !is_nil(RA - 1)
  842.             || fvalue(RA - 3) != (ktap_cfunction)kp_tab_next) {
  843.             /* Despecialize bytecode if any of the checks fail. */
  844.             setbc_op(pc - 1, BC_JMP);
  845.             dojump(instr, 0);
  846.             setbc_op(pc, BC_ITERC);
  847.         } else {
  848.             dojump(instr, 0);
  849.             set_nil(RA); /* init control variable */
  850.         }
  851.         DISPATCH();
  852.     DO_BC_RETM: /* don't support return multiple values */
  853.     DO_BC_RET:
  854.         return;
  855.     DO_BC_RET0:
  856.         /* if it's called from external invocation, just return */
  857.         if (!func->pcr)
  858.             return;

  859.         pc = func->pcr; /* restore PC */

  860.         multres = bc_d(instr);
  861.         set_nil(func);

  862.         base = func - bc_a(*pc);
  863.         func = base - 1;
  864.         fn = clvalue(func);
  865.         kbase = fn->p->k;
  866.         ks->top = base + pt->framesize;
  867.         pc++;

  868.         DISPATCH();
  869.     DO_BC_RET1:
  870.         /* if it's called from external invocation, just return */
  871.         if (!func->pcr)
  872.             return;

  873.         pc = func->pcr; /* restore PC */

  874.         multres = bc_d(instr);
  875.         set_obj(base - 1, RA); /* move result */

  876.         base = func - bc_a(*pc);
  877.         func = base - 1;
  878.         fn = clvalue(func);
  879.         kbase = fn->p->k;
  880.         ks->top = base + pt->framesize;
  881.         pc++;

  882.         DISPATCH();
  883.     DO_BC_FORI: { /* Numeric 'for' loop init */
  884.         ktap_number idx;
  885.         ktap_number limit;
  886.         ktap_number step;

  887.         if (unlikely(!is_number(RA) || !is_number(RA + 1) ||
  888.                 !is_number(RA + 2))) {
  889.             kp_error(ks, KTAP_QL("for")
  890.                  " init/limit/step value must be a number\n");
  891.             return;
  892.         }

  893.         idx = nvalue(RA);
  894.         limit = nvalue(RA + 1);
  895.         step = nvalue(RA + 2);

  896.         if (NUMLT(0, step) ? NUMLE(idx, limit) : NUMLE(limit, idx)) {
  897.             set_number(RA + 3, nvalue(RA));
  898.         } else {
  899.             dojump(instr, 0);
  900.         }
  901.         DISPATCH();
  902.         }
  903.     DO_BC_JFORI: /* not used */
  904.         return;
  905.     DO_BC_FORL: { /* Numeric 'for' loop */
  906.         ktap_number step = nvalue(RA + 2);
  907.         /* increment index */
  908.         ktap_number idx = NUMADD(nvalue(RA), step);
  909.         ktap_number limit = nvalue(RA + 1);
  910.         if (NUMLT(0, step) ? NUMLE(idx, limit) : NUMLE(limit, idx)) {
  911.             dojump(instr, 0); /* jump back */
  912.             set_number(RA, idx);  /* update internal index... */
  913.             set_number(RA + 3, idx);  /* ...and external index */
  914.         }

  915.         if (unlikely(check_hot_loop(ks, loop_count++) < 0))
  916.             return;

  917.         DISPATCH();
  918.         }
  919.     DO_BC_IFORL: /* not used */
  920.     DO_BC_JFORL:
  921.     DO_BC_ITERL:
  922.     DO_BC_IITERL:
  923.     DO_BC_JITERL:
  924.         return;
  925.     DO_BC_LOOP: /* Generic loop */
  926.         /* ktap use this bc to detect hot loop */
  927.         if (unlikely(check_hot_loop(ks, loop_count++) < 0))
  928.             return;
  929.         DISPATCH();
  930.     DO_BC_ILOOP: /* not used */
  931.     DO_BC_JLOOP:
  932.         return;
  933.     DO_BC_JMP: /* Jump */
  934.         dojump(instr, 0);
  935.         DISPATCH();
  936.     DO_BC_FUNCF: /* function header, not used */
  937.     DO_BC_IFUNCF:
  938.     DO_BC_JFUNCF:
  939.     DO_BC_FUNCV:
  940.     DO_BC_IFUNCV:
  941.     DO_BC_JFUNCV:
  942.     DO_BC_FUNCC:
  943.     DO_BC_FUNCCW:
  944.         return;
  945.     DO_BC_VARGN: /* arg0 .. arg9*/
  946.         if (unlikely(!ks->current_event)) {
  947.             kp_error(ks, "invalid event context\n");
  948.             return;
  949.         }

  950.         kp_event_getarg(ks, RA, bc_d(instr));
  951.         DISPATCH();
  952.     DO_BC_VARGSTR: { /* argstr */
  953.         /*
  954.          * If you pass argstr to print/printf function directly,
  955.          * then no extra string generated, so don't worry string
  956.          * poll size for below case:
  957.          *     print(argstr)
  958.          *
  959.          * If you use argstr as table key like below, then it may
  960.          * overflow your string pool size, so be care of on it.
  961.          *     table[argstr] = V
  962.          *
  963.          * If you assign argstr to upval or table value like below,
  964.          * it don't really write string, just write type KTAP_TEVENTSTR,
  965.          * the value will be interpreted when value print out in valid
  966.          * event context, if context mismatch, error will report.
  967.          *     table[V] = argstr
  968.          *     upval = argstr
  969.          *
  970.          * If you want to save real string of argstr, then use it like
  971.          * below, again, be care of string pool size in this case.
  972.          *     table[V] = stringof(argstr)
  973.          *     upval = stringof(argstr)
  974.          */
  975.         struct ktap_event_data *e = ks->current_event;

  976.         if (unlikely(!e)) {
  977.             kp_error(ks, "invalid event context\n");
  978.             return;
  979.         }

  980.         if (e->argstr) /* argstr been stringified */
  981.             set_string(RA, e->argstr);
  982.         else
  983.             set_eventstr(RA);
  984.         DISPATCH();
  985.         }
  986.     DO_BC_VPROBENAME: { /* probename */
  987.         struct ktap_event_data *e = ks->current_event;

  988.         if (unlikely(!e)) {
  989.             kp_error(ks, "invalid event context\n");
  990.             return;
  991.         }
  992.         set_string(RA, e->event->name);
  993.         DISPATCH();
  994.         }
  995.     DO_BC_VPID: /* pid */
  996.         set_number(RA, (int)current->pid);
  997.         DISPATCH();
  998.     DO_BC_VTID: /* tid */
  999.         set_number(RA, (int)task_pid_vnr(current));
  1000.         DISPATCH();
  1001.     DO_BC_VUID: { /* uid */
  1002. #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0)
  1003.         uid_t uid = from_kuid_munged(current_user_ns(), current_uid());
  1004. #else
  1005.         uid_t uid = current_uid();
  1006. #endif
  1007.         set_number(RA, (int)uid);
  1008.         DISPATCH();
  1009.         }
  1010.     DO_BC_VCPU: /* cpu */
  1011.         set_number(RA, smp_processor_id());
  1012.         DISPATCH();
  1013.     DO_BC_VEXECNAME: { /* execname */
  1014.         ktap_str_t *ts = kp_str_newz(ks, current->comm);
  1015.         if (unlikely(!ts))
  1016.             return;
  1017.         set_string(RA, ts);
  1018.         DISPATCH();
  1019.         }
  1020.     DO_BC_GFUNC: { /* Call built-in C function, patched by BC_GGET */
  1021.         ktap_cfunction cfunc = gfunc_get(ks, bc_d(instr));
  1022.         set_cfunc(RA, cfunc);
  1023.         DISPATCH();
  1024.         }
  1025.     }
  1026. }

  1027. /*
  1028. * Validate byte code and static analysis.
  1029. *
  1030. * TODO: more type checking before real running.
  1031. */
  1032. int kp_vm_validate_code(ktap_state_t *ks, ktap_proto_t *pt, ktap_val_t *base)
  1033. {
  1034.     const unsigned int *pc = proto_bc(pt) + 1;
  1035.     unsigned int instr, op;
  1036.     ktap_obj_t **kbase = pt->k;
  1037.     ktap_tab_t *gtab = G(ks)->gtab;
  1038.     int i;

  1039. #define RA    (base + bc_a(instr))
  1040. #define RB    (base + bc_b(instr))
  1041. #define RC    (base + bc_c(instr))
  1042. #define RD    (base + bc_d(instr))

  1043.     if (pt->framesize > KP_MAX_SLOTS) {
  1044.         kp_error(ks, "exceed max frame size %d\n", pt->framesize);
  1045.         return -1;
  1046.     }

  1047.     if (base + pt->framesize > ks->stack_last) {
  1048.         kp_error(ks, "stack overflow\n");
  1049.         return -1;
  1050.     }

  1051.     for (i = 0; i < pt->sizebc - 1; i++) {
  1052.         instr = *pc++;
  1053.         op = bc_op(instr);


  1054.         if (op >= BC__MAX) {
  1055.             kp_error(ks, "unknown byte code %d\n", op);
  1056.             return -1;
  1057.         }

  1058.         switch (op) {
  1059.         case BC_FNEW: {
  1060.             int idx = ~bc_d(instr);
  1061.             ktap_proto_t *newpt = (ktap_proto_t *)kbase[idx];
  1062.             if (kp_vm_validate_code(ks, newpt, RA + 1))
  1063.                 return -1;

  1064.             break;
  1065.             }
  1066.         case BC_RETM: case BC_RET:
  1067.             kp_error(ks, "don't support return multiple values\n");
  1068.             return -1;
  1069.         case BC_GSET: case BC_GINC: { /* _G[D] = A, _G[D] += A */
  1070.             int idx = ~bc_d(instr);
  1071.             ktap_str_t *ts = (ktap_str_t *)kbase[idx];
  1072.             kp_error(ks, "cannot set global variable '%s'\n",
  1073.                     getstr(ts));
  1074.             return -1;
  1075.             }
  1076.         case BC_GGET: {
  1077.             int idx = ~bc_d(instr);
  1078.             ktap_str_t *ts = (ktap_str_t *)kbase[idx];
  1079.             ktap_val_t val;
  1080.             kp_tab_getstr(gtab, ts, &val);
  1081.             if (is_nil(&val)) {
  1082.                 kp_error(ks, "undefined global variable"
  1083.                         " '%s'\n", getstr(ts));
  1084.                 return -1;
  1085.             } else if (is_cfunc(&val)) {
  1086.                 int idx = gfunc_getidx(G(ks), fvalue(&val));
  1087.                 if (idx >= 0) {
  1088.                     /* patch BC_GGET bytecode to BC_GFUNC */
  1089.                     setbc_op(pc - 1, BC_GFUNC);
  1090.                     setbc_d(pc - 1, idx);
  1091.                 }
  1092.             }
  1093.             break;
  1094.             }
  1095.         case BC_ITERC:
  1096.             kp_error(ks, "ktap only support pairs iteraor\n");
  1097.             return -1;
  1098.         case BC_POW:
  1099.             kp_error(ks, "ktap don't support pow arith\n");
  1100.             return -1;
  1101.         }
  1102.     }

  1103.     return 0;
  1104. }

  1105. /* return cfunction by idx */
  1106. static ktap_cfunction gfunc_get(ktap_state_t *ks, int idx)
  1107. {
  1108.     return G(ks)->gfunc_tbl[idx];
  1109. }

  1110. /* get cfunction index, the index is for fast get cfunction in runtime */
  1111. static int gfunc_getidx(ktap_global_state_t *g, ktap_cfunction cfunc)
  1112. {
  1113.     int nr = g->nr_builtin_cfunction;
  1114.     ktap_cfunction *gfunc_tbl = g->gfunc_tbl;
  1115.     int i;

  1116.     for (i = 0; i < nr; i++) {
  1117.         if (gfunc_tbl[i] == cfunc)
  1118.             return i;
  1119.     }

  1120.     return -1;
  1121. }

  1122. static void gfunc_add(ktap_state_t *ks, ktap_cfunction cfunc)
  1123. {
  1124.     int nr = G(ks)->nr_builtin_cfunction;

  1125.     if (nr == KP_MAX_CACHED_CFUNCTION) {
  1126.         kp_error(ks, "please enlarge KP_MAX_CACHED_CFUNCTION %d\n",
  1127.                 KP_MAX_CACHED_CFUNCTION);
  1128.         return;
  1129.     }
  1130.     G(ks)->gfunc_tbl[nr] = cfunc;
  1131.     G(ks)->nr_builtin_cfunction++;
  1132. }

  1133. /* function for register library */
  1134. int kp_vm_register_lib(ktap_state_t *ks, const char *libname,
  1135.                const ktap_libfunc_t *funcs)
  1136. {
  1137.     ktap_tab_t *gtab = G(ks)->gtab;
  1138.     ktap_tab_t *target_tbl;
  1139.     int i;

  1140.     /* lib is null when register baselib function */
  1141.     if (libname == NULL)
  1142.         target_tbl = gtab;
  1143.     else {
  1144.         ktap_val_t key, val;
  1145.         ktap_str_t *ts = kp_str_newz(ks, libname);
  1146.         if (!ts)
  1147.             return -ENOMEM;

  1148.         /* calculate the function number contained by this library */
  1149.         for (i = 0; funcs[i].name != NULL; i++) {
  1150.         }

  1151.         target_tbl = kp_tab_new_ah(ks, 0, i + 1);
  1152.         if (!target_tbl)
  1153.             return -ENOMEM;

  1154.         set_string(&key, ts);
  1155.         set_table(&val, target_tbl);
  1156.         kp_tab_set(ks, gtab, &key, &val);
  1157.     }

  1158.     /* TODO: be care of same function name issue, foo() and tbl.foo() */
  1159.     for (i = 0; funcs[i].name != NULL; i++) {
  1160.         ktap_str_t *func_name = kp_str_newz(ks, funcs[i].name);
  1161.         ktap_val_t fn;

  1162.         if (unlikely(!func_name))
  1163.             return -ENOMEM;

  1164.         set_cfunc(&fn, funcs[i].func);
  1165.         kp_tab_setstr(ks, target_tbl, func_name, &fn);

  1166.         gfunc_add(ks, funcs[i].func);
  1167.     }

  1168.     return 0;
  1169. }

  1170. static int init_registry(ktap_state_t *ks)
  1171. {
  1172.     ktap_tab_t *registry = kp_tab_new_ah(ks, 2, 0);
  1173.     ktap_val_t gtbl;
  1174.     ktap_tab_t *t;

  1175.     if (!registry)
  1176.         return -1;

  1177.     set_table(&G(ks)->registry, registry);

  1178.     /* assume there will have max 1024 global variables */
  1179.     t = kp_tab_new_ah(ks, 0, 1024);
  1180.     if (!t)
  1181.         return -1;

  1182.     set_table(&gtbl, t);
  1183.     kp_tab_setint(ks, registry, KTAP_RIDX_GLOBALS, &gtbl);
  1184.     G(ks)->gtab = t;

  1185.     return 0;
  1186. }

  1187. static int init_arguments(ktap_state_t *ks, int argc, char __user **user_argv)
  1188. {
  1189.     ktap_tab_t *gtbl = G(ks)->gtab;
  1190.     ktap_tab_t *arg_tbl = kp_tab_new_ah(ks, argc, 1);
  1191.     ktap_val_t arg_tblval;
  1192.     ktap_val_t arg_tsval;
  1193.     ktap_str_t *argts = kp_str_newz(ks, "arg");
  1194.     char **argv;
  1195.     int i, ret;

  1196.     if (!arg_tbl)
  1197.         return -1;

  1198.     if (unlikely(!argts))
  1199.         return -ENOMEM;

  1200.     set_string(&arg_tsval, argts);
  1201.     set_table(&arg_tblval, arg_tbl);
  1202.     kp_tab_set(ks, gtbl, &arg_tsval, &arg_tblval);

  1203.     if (!argc)
  1204.         return 0;

  1205.     if (argc > 1024)
  1206.         return -EINVAL;

  1207.     argv = kzalloc(argc * sizeof(char *), GFP_KERNEL);
  1208.     if (!argv)
  1209.         return -ENOMEM;

  1210.     ret = copy_from_user(argv, user_argv, argc * sizeof(char *));
  1211.     if (ret < 0) {
  1212.         kfree(argv);
  1213.         return -EFAULT;
  1214.     }

  1215.     ret = 0;
  1216.     for (i = 0; i < argc; i++) {
  1217.         ktap_val_t val;
  1218.         char __user *ustr = argv[i];
  1219.         char *kstr;
  1220.         int len;
  1221.         int res;

  1222.         len = strlen_user(ustr);
  1223.         if (len > 0x1000) {
  1224.             ret = -EINVAL;
  1225.             break;
  1226.         }

  1227.         kstr = kmalloc(len + 1, GFP_KERNEL);
  1228.         if (!kstr) {
  1229.             ret = -ENOMEM;
  1230.             break;
  1231.         }

  1232.         if (strncpy_from_user(kstr, ustr, len) < 0) {
  1233.             kfree(kstr);
  1234.             ret = -EFAULT;
  1235.             break;
  1236.         }

  1237.         kstr[len] = '\0';

  1238.         if (!kstrtoint(kstr, 10, &res)) {
  1239.             set_number(&val, res);
  1240.         } else {
  1241.             ktap_str_t *ts = kp_str_newz(ks, kstr);
  1242.             if (unlikely(!ts)) {
  1243.                 kfree(kstr);
  1244.                 ret = -ENOMEM;
  1245.                 break;
  1246.             }

  1247.             set_string(&val, ts);
  1248.         }

  1249.         kp_tab_setint(ks, arg_tbl, i, &val);

  1250.         kfree(kstr);
  1251.     }

  1252.     kfree(argv);
  1253.     return ret;
  1254. }

  1255. static void free_preserved_data(ktap_state_t *ks)
  1256. {
  1257.     int cpu, i, j;

  1258.     /* free stack for each allocated ktap_state */
  1259.     for_each_possible_cpu(cpu) {
  1260.         for (j = 0; j < PERF_NR_CONTEXTS; j++) {
  1261.             void *percpu_state = G(ks)->percpu_state[j];
  1262.             ktap_state_t *pks;

  1263.             if (!percpu_state)
  1264.                 break;
  1265.             pks = per_cpu_ptr(percpu_state, cpu);
  1266.             if (!ks)
  1267.                 break;
  1268.             kfree(pks->stack);
  1269.         }
  1270.     }

  1271.     /* free percpu ktap_state */
  1272.     for (i = 0; i < PERF_NR_CONTEXTS; i++) {
  1273.         if (G(ks)->percpu_state[i])
  1274.             free_percpu(G(ks)->percpu_state[i]);
  1275.     }

  1276.     /* free percpu ktap print buffer */
  1277.     for (i = 0; i < PERF_NR_CONTEXTS; i++) {
  1278.         if (G(ks)->percpu_print_buffer[i])
  1279.             free_percpu(G(ks)->percpu_print_buffer[i]);
  1280.     }

  1281.     /* free percpu ktap temp buffer */
  1282.     for (i = 0; i < PERF_NR_CONTEXTS; i++) {
  1283.         if (G(ks)->percpu_temp_buffer[i])
  1284.             free_percpu(G(ks)->percpu_temp_buffer[i]);
  1285.     }

  1286.     /* free percpu ktap recursion context flag */
  1287.     for (i = 0; i < PERF_NR_CONTEXTS; i++)
  1288.         if (G(ks)->recursion_context[i])
  1289.             free_percpu(G(ks)->recursion_context[i]);
  1290. }

  1291. #define ALLOC_PERCPU(size)  __alloc_percpu(size, __alignof__(char))
  1292. static int init_preserved_data(ktap_state_t *ks)
  1293. {
  1294.     void __percpu *data;
  1295.     int cpu, i, j;

  1296.     /* init percpu ktap_state */
  1297.     for (i = 0; i < PERF_NR_CONTEXTS; i++) {
  1298.         data = ALLOC_PERCPU(sizeof(ktap_state_t));
  1299.         if (!data)
  1300.             goto fail;
  1301.         G(ks)->percpu_state[i] = data;
  1302.     }

  1303.     /* init stack for each allocated ktap_state */
  1304.     for_each_possible_cpu(cpu) {
  1305.         for (j = 0; j < PERF_NR_CONTEXTS; j++) {
  1306.             void *percpu_state = G(ks)->percpu_state[j];
  1307.             ktap_state_t *pks;

  1308.             if (!percpu_state)
  1309.                 break;
  1310.             pks = per_cpu_ptr(percpu_state, cpu);
  1311.             if (!ks)
  1312.                 break;
  1313.             pks->stack = kzalloc(KTAP_STACK_SIZE_BYTES, GFP_KERNEL);
  1314.             if (!pks->stack)
  1315.                 goto fail;

  1316.             pks->stack_last = pks->stack + KTAP_STACK_SIZE;
  1317.             G(pks) = G(ks);
  1318.         }
  1319.     }

  1320.     /* init percpu ktap print buffer */
  1321.     for (i = 0; i < PERF_NR_CONTEXTS; i++) {
  1322.         data = ALLOC_PERCPU(KTAP_PERCPU_BUFFER_SIZE);
  1323.         if (!data)
  1324.             goto fail;
  1325.         G(ks)->percpu_print_buffer[i] = data;
  1326.     }

  1327.     /* init percpu ktap temp buffer */
  1328.     for (i = 0; i < PERF_NR_CONTEXTS; i++) {
  1329.         data = ALLOC_PERCPU(KTAP_PERCPU_BUFFER_SIZE);
  1330.         if (!data)
  1331.             goto fail;
  1332.         G(ks)->percpu_temp_buffer[i] = data;
  1333.     }

  1334.     /* init percpu ktap recursion context flag */
  1335.     for (i = 0; i < PERF_NR_CONTEXTS; i++) {
  1336.         data = alloc_percpu(int);
  1337.         if (!data)
  1338.             goto fail;
  1339.         G(ks)->recursion_context[i] = data;
  1340.     }

  1341.     return 0;

  1342. fail:
  1343.     free_preserved_data(ks);
  1344.     return -ENOMEM;
  1345. }

  1346. /*
  1347. * wait ktapio thread read all content in ring buffer.
  1348. *
  1349. * Here we use stupid approach to sync with ktapio thread,
  1350. * note that we cannot use semaphore/completion/other sync method,
  1351. * because ktapio thread could be killed by SIG_KILL in anytime, there
  1352. * have no safe way to up semaphore or wake waitqueue before thread exit.
  1353. *
  1354. * we also cannot use waitqueue of current->signal->wait_chldexit to sync
  1355. * exit, becasue mainthread and ktapio thread are in same thread group.
  1356. *
  1357. * Also ktap mainthread must wait ktapio thread exit, otherwise ktapio
  1358. * thread will oops when access ktap structure.
  1359. */
  1360. static void wait_user_completion(ktap_state_t *ks)
  1361. {
  1362.     struct task_struct *tsk = G(ks)->task;
  1363.     G(ks)->wait_user = 1;

  1364.     while (1) {
  1365.         set_current_state(TASK_INTERRUPTIBLE);
  1366.         /* sleep for 100 msecs, and try again. */
  1367.         schedule_timeout(HZ / 10);

  1368.         if (get_nr_threads(tsk) == 1)
  1369.             break;
  1370.     }
  1371. }

  1372. static void sleep_loop(ktap_state_t *ks,
  1373.             int (*actor)(ktap_state_t *ks, void *arg), void *arg)
  1374. {
  1375.     while (!ks->stop) {
  1376.         set_current_state(TASK_INTERRUPTIBLE);
  1377.         /* sleep for 100 msecs, and try again. */
  1378.         schedule_timeout(HZ / 10);

  1379.         if (actor(ks, arg))
  1380.             return;
  1381.     }
  1382. }

  1383. static int sl_wait_task_pause_actor(ktap_state_t *ks, void *arg)
  1384. {
  1385.     struct task_struct *task = (struct task_struct *)arg;

  1386.     if (task->state)
  1387.         return 1;
  1388.     else
  1389.         return 0;
  1390. }

  1391. static int sl_wait_task_exit_actor(ktap_state_t *ks, void *arg)
  1392. {
  1393.     struct task_struct *task = (struct task_struct *)arg;

  1394.     if (signal_pending(current)) {
  1395.         flush_signals(current);

  1396.         /* newline for handle CTRL+C display as ^C */
  1397.         kp_puts(ks, "\n");
  1398.         return 1;
  1399.     }

  1400.     /* stop waiting if target pid is exited */
  1401.     if (task && task->state == TASK_DEAD)
  1402.             return 1;

  1403.     return 0;
  1404. }

  1405. /* wait user interrupt, signal killed */
  1406. static void wait_user_interrupt(ktap_state_t *ks)
  1407. {
  1408.     struct task_struct *task = G(ks)->trace_task;

  1409.     if (G(ks)->state == KTAP_EXIT || G(ks)->state == KTAP_ERROR)
  1410.         return;

  1411.     /* let tracing goes now. */
  1412.     ks->stop = 0;

  1413.     if (G(ks)->parm->workload) {
  1414.         /* make sure workload is in pause state
  1415.          * so it won't miss the signal */
  1416.         sleep_loop(ks, sl_wait_task_pause_actor, task);
  1417.         /* tell workload process to start executing */
  1418.         send_sig(SIGINT, G(ks)->trace_task, 0);
  1419.     }

  1420.     if (!G(ks)->parm->quiet)
  1421.         kp_printf(ks, "Tracing... Hit Ctrl-C to end.\n");

  1422.     sleep_loop(ks, sl_wait_task_exit_actor, task);
  1423. }

  1424. /*
  1425. * ktap exit, free all resources.
  1426. */
  1427. void kp_vm_exit(ktap_state_t *ks)
  1428. {
  1429.     if (!list_empty(&G(ks)->events_head) ||
  1430.         !list_empty(&G(ks)->timers))
  1431.         wait_user_interrupt(ks);

  1432.     kp_exit_timers(ks);
  1433.     kp_events_exit(ks);

  1434.     /* free all resources got by ktap */
  1435. #ifdef CONFIG_KTAP_FFI
  1436.     ffi_free_symbols(ks);
  1437. #endif
  1438.     kp_str_freeall(ks);
  1439.     kp_mempool_destroy(ks);

  1440.     func_closeuv(ks, 0); /* close all open upvals, let below call free it */
  1441.     kp_obj_freeall(ks);

  1442.     kp_vm_exit_thread(ks);
  1443.     kp_free(ks, ks->stack);

  1444.     free_preserved_data(ks);
  1445.     free_cpumask_var(G(ks)->cpumask);

  1446.     wait_user_completion(ks);

  1447.     /* should invoke after wait_user_completion */
  1448.     if (G(ks)->trace_task)
  1449.         put_task_struct(G(ks)->trace_task);

  1450.     kp_transport_exit(ks);
  1451.     kp_free(ks, ks); /* free self */
  1452. }

  1453. /*
  1454. * ktap mainthread initization
  1455. */
  1456. ktap_state_t *kp_vm_new_state(ktap_option_t *parm, struct dentry *dir)
  1457. {
  1458.     ktap_state_t *ks;
  1459.     ktap_global_state_t *g;
  1460.     pid_t pid;
  1461.     int cpu;

  1462.     ks = kzalloc(sizeof(ktap_state_t) + sizeof(ktap_global_state_t),
  1463.              GFP_KERNEL);
  1464.     if (!ks)
  1465.         return NULL;

  1466.     G(ks) = (ktap_global_state_t *)(ks + 1);
  1467.     g = G(ks);
  1468.     g->mainthread = ks;
  1469.     g->task = current;
  1470.     g->parm = parm;
  1471.     g->str_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
  1472.     g->strmask = ~(int)0;
  1473.     g->uvhead.prev = &g->uvhead;
  1474.     g->uvhead.next = &g->uvhead;
  1475.     g->state = KTAP_RUNNING;
  1476.     INIT_LIST_HEAD(&(g->timers));
  1477.     INIT_LIST_HEAD(&(g->events_head));

  1478.     if (kp_transport_init(ks, dir))
  1479.         goto out;

  1480.     ks->stack = kp_malloc(ks, KTAP_STACK_SIZE_BYTES);
  1481.     if (!ks->stack)
  1482.         goto out;

  1483.     ks->stack_last = ks->stack + KTAP_STACK_SIZE;
  1484.     ks->top = ks->stack;

  1485.     pid = (pid_t)parm->trace_pid;
  1486.     if (pid != -1) {
  1487.         struct task_struct *task;

  1488.         rcu_read_lock();
  1489.         task = pid_task(find_vpid(pid), PIDTYPE_PID);
  1490.         if (!task) {
  1491.             kp_error(ks, "cannot find pid %d\n", pid);
  1492.             rcu_read_unlock();
  1493.             goto out;
  1494.         }
  1495.         g->trace_task = task;
  1496.         get_task_struct(task);
  1497.         rcu_read_unlock();
  1498.     }

  1499.     if( !alloc_cpumask_var(&g->cpumask, GFP_KERNEL))
  1500.         goto out;

  1501.     cpumask_copy(g->cpumask, cpu_online_mask);

  1502.     cpu = parm->trace_cpu;
  1503.     if (cpu != -1) {
  1504.         if (!cpu_online(cpu)) {
  1505.             kp_error(ks, "ktap: cpu %d is not online\n", cpu);
  1506.             goto out;
  1507.         }

  1508.         cpumask_clear(g->cpumask);
  1509.         cpumask_set_cpu(cpu, g->cpumask);
  1510.     }

  1511.     if (kp_mempool_init(ks, KP_MAX_MEMPOOL_SIZE))
  1512.         goto out;

  1513.     if (kp_str_resize(ks, 1024 - 1)) /* set string hashtable size */
  1514.         goto out;

  1515.     if (init_registry(ks))
  1516.         goto out;
  1517.     if (init_arguments(ks, parm->argc, parm->argv))
  1518.         goto out;

  1519.     /* init librarys */
  1520.     if (kp_lib_init_base(ks))
  1521.         goto out;
  1522.     if (kp_lib_init_kdebug(ks))
  1523.         goto out;
  1524.     if (kp_lib_init_timer(ks))
  1525.         goto out;
  1526.     if (kp_lib_init_ansi(ks))
  1527.         goto out;
  1528. #ifdef CONFIG_KTAP_FFI
  1529.     if (kp_lib_init_ffi(ks))
  1530.         goto out;
  1531. #endif
  1532.     if (kp_lib_init_table(ks))
  1533.         goto out;

  1534.     if (kp_lib_init_net(ks))
  1535.         goto out;

  1536.     if (init_preserved_data(ks))
  1537.         goto out;

  1538.     if (kp_events_init(ks))
  1539.         goto out;

  1540.     return ks;

  1541. out:
  1542.     g->state = KTAP_ERROR;
  1543.     kp_vm_exit(ks);
  1544.     return NULL;
  1545. }