Skip to content
Myr

execute.c

This file

Path

src/execute.c

1,349 lines · 36.5 KiB · C

Last changed by

Remove multiple calls to free when successively calling jq_reset. (#3134)Samar Sunkariabefore adoption7be6870

History of this file

Take it

1#include <assert.h>2#include <errno.h>3#include <stdarg.h>4#include <stdio.h>5#include <stdlib.h>6#include <stdint.h>7#include <sys/stat.h>89#include "exec_stack.h"10#include "bytecode.h"1112#include "jv_alloc.h"13#include "jq_parser.h"14#include "locfile.h"15#include "jv.h"16#include "jq.h"17#include "parser.h"18#include "builtin.h"19#include "util.h"20#include "linker.h"2122struct jq_state {23  void (*nomem_handler)(void *);24  void *nomem_handler_data;25  struct bytecode* bc;2627  jq_msg_cb err_cb;28  void *err_cb_data;29  jv error;3031  struct stack stk;32  stack_ptr curr_frame;33  stack_ptr stk_top;34  stack_ptr fork_top;3536  jv path;37  jv value_at_path;38  int subexp_nest;39  int debug_trace_enabled;40  int initial_execution;41  unsigned next_label;4243  int halted;44  jv exit_code;45  jv error_message;4647  jv attrs;48  jq_input_cb input_cb;49  void *input_cb_data;50  jq_msg_cb debug_cb;51  void *debug_cb_data;52  jq_msg_cb stderr_cb;53  void *stderr_cb_data;54};5556struct closure {57  struct bytecode* bc;  // jq bytecode58  stack_ptr env;        // jq stack address of closed frame59};6061// locals for any function called: either a closure or a local variable62union frame_entry {63  struct closure closure;64  jv localvar;65};6667// jq function call frame68struct frame {69  struct bytecode* bc;      // jq bytecode for callee70  stack_ptr env;            // jq stack address of frame to return to71  stack_ptr retdata;        // jq stack address to unwind to on RET72  uint16_t* retaddr;        // jq bytecode return address73  union frame_entry entries[]; // nclosures + nlocals74};7576static int frame_size(struct bytecode* bc) {77  return sizeof(struct frame) + sizeof(union frame_entry) * (bc->nclosures + bc->nlocals);78}7980static struct frame* frame_current(struct jq_state* jq) {81  struct frame* fp = stack_block(&jq->stk, jq->curr_frame);8283  stack_ptr next = *stack_block_next(&jq->stk, jq->curr_frame);84  if (next) {85    struct frame* fpnext = stack_block(&jq->stk, next);86    struct bytecode* bc = fpnext->bc;87    assert(fp->retaddr >= bc->code && fp->retaddr < bc->code + bc->codelen);88  } else {89    assert(fp->retaddr == 0);90  }91  return fp;92}9394static stack_ptr frame_get_level(struct jq_state* jq, int level) {95  stack_ptr fr = jq->curr_frame;96  for (int i=0; i<level; i++) {97    struct frame* fp = stack_block(&jq->stk, fr);98    fr = fp->env;99  }100  return fr;101}102103static jv* frame_local_var(struct jq_state* jq, int var, int level) {104  struct frame* fr = stack_block(&jq->stk, frame_get_level(jq, level));105  assert(var >= 0);106  assert(var < fr->bc->nlocals);107  return &fr->entries[fr->bc->nclosures + var].localvar;108}109110static struct closure make_closure(struct jq_state* jq, uint16_t* pc) {111  uint16_t level = *pc++;112  uint16_t idx = *pc++;113  stack_ptr fridx = frame_get_level(jq, level);114  struct frame* fr = stack_block(&jq->stk, fridx);115  if (idx & ARG_NEWCLOSURE) {116    // A new closure closing the frame identified by level, and with117    // the bytecode body of the idx'th subfunction of that frame118    int subfn_idx = idx & ~ARG_NEWCLOSURE;119    assert(subfn_idx < fr->bc->nsubfunctions);120    struct closure cl = {fr->bc->subfunctions[subfn_idx],121                         fridx};122    return cl;123  } else {124    // A reference to a closure from the frame identified by level; copy125    // it as-is126    int closure = idx;127    assert(closure >= 0);128    assert(closure < fr->bc->nclosures);129    return fr->entries[closure].closure;130  }131}132133static struct frame* frame_push(struct jq_state* jq, struct closure callee,134                                uint16_t* argdef, int nargs) {135  stack_ptr new_frame_idx = stack_push_block(&jq->stk, jq->curr_frame, frame_size(callee.bc));136  struct frame* new_frame = stack_block(&jq->stk, new_frame_idx);137  new_frame->bc = callee.bc;138  new_frame->env = callee.env;139  assert(nargs == new_frame->bc->nclosures);140  union frame_entry* entries = new_frame->entries;141  for (int i=0; i<nargs; i++) {142    entries->closure = make_closure(jq, argdef + i * 2);143    entries++;144  }145  for (int i=0; i<callee.bc->nlocals; i++) {146    entries->localvar = jv_invalid();147    entries++;148  }149  jq->curr_frame = new_frame_idx;150  return new_frame;151}152153static void frame_pop(struct jq_state* jq) {154  assert(jq->curr_frame);155  struct frame* fp = frame_current(jq);156  if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {157    int nlocals = fp->bc->nlocals;158    for (int i=0; i<nlocals; i++) {159      jv_free(*frame_local_var(jq, i, 0));160    }161  }162  jq->curr_frame = stack_pop_block(&jq->stk, jq->curr_frame, frame_size(fp->bc));163}164165void stack_push(jq_state *jq, jv val) {166  assert(jv_is_valid(val));167  jq->stk_top = stack_push_block(&jq->stk, jq->stk_top, sizeof(jv));168  jv* sval = stack_block(&jq->stk, jq->stk_top);169  *sval = val;170}171172jv stack_pop(jq_state *jq) {173  jv* sval = stack_block(&jq->stk, jq->stk_top);174  jv val = *sval;175  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {176    val = jv_copy(val);177  }178  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));179  assert(jv_is_valid(val));180  return val;181}182183// Like stack_pop(), but assert !stack_pop_will_free() and replace with184// jv_null() on the stack.185jv stack_popn(jq_state *jq) {186  jv* sval = stack_block(&jq->stk, jq->stk_top);187  jv val = *sval;188  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {189    *sval = jv_null();190  }191  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));192  assert(jv_is_valid(val));193  return val;194}195196197struct forkpoint {198  stack_ptr saved_data_stack;199  stack_ptr saved_curr_frame;200  int path_len, subexp_nest;201  jv value_at_path;202  uint16_t* return_address;203};204205struct stack_pos {206  stack_ptr saved_data_stack, saved_curr_frame;207};208209struct stack_pos stack_get_pos(jq_state* jq) {210  struct stack_pos sp = {jq->stk_top, jq->curr_frame};211  return sp;212}213214void stack_save(jq_state *jq, uint16_t* retaddr, struct stack_pos sp){215  jq->fork_top = stack_push_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));216  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);217  fork->saved_data_stack = jq->stk_top;218  fork->saved_curr_frame = jq->curr_frame;219  fork->path_len =220    jv_get_kind(jq->path) == JV_KIND_ARRAY ? jv_array_length(jv_copy(jq->path)) : 0;221  fork->value_at_path = jv_copy(jq->value_at_path);222  fork->subexp_nest = jq->subexp_nest;223  fork->return_address = retaddr;224  jq->stk_top = sp.saved_data_stack;225  jq->curr_frame = sp.saved_curr_frame;226}227228static int path_intact(jq_state *jq, jv curr) {229  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {230    return jv_identical(curr, jv_copy(jq->value_at_path));231  } else {232    jv_free(curr);233    return 1;234  }235}236237static void path_append(jq_state* jq, jv component, jv value_at_path) {238  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {239    int n1 = jv_array_length(jv_copy(jq->path));240    jq->path = jv_array_append(jq->path, component);241    int n2 = jv_array_length(jv_copy(jq->path));242    assert(n2 == n1 + 1);243    jv_free(jq->value_at_path);244    jq->value_at_path = value_at_path;245  } else {246    jv_free(component);247    jv_free(value_at_path);248  }249}250251/* For f_getpath() */252jv253_jq_path_append(jq_state *jq, jv v, jv p, jv value_at_path) {254  if (jq->subexp_nest != 0 ||255      jv_get_kind(jq->path) != JV_KIND_ARRAY ||256      !jv_is_valid(value_at_path)) {257    jv_free(v);258    jv_free(p);259    return value_at_path;260  }261  if (!jv_identical(v, jv_copy(jq->value_at_path))) {262    jv_free(p);263    return value_at_path;264  }265  if (jv_get_kind(p) == JV_KIND_ARRAY)266    jq->path = jv_array_concat(jq->path, p);267  else268    jq->path = jv_array_append(jq->path, p);269  jv_free(jq->value_at_path);270  return jv_copy(jq->value_at_path = value_at_path);271}272273uint16_t* stack_restore(jq_state *jq){274  while (!stack_pop_will_free(&jq->stk, jq->fork_top)) {275    if (stack_pop_will_free(&jq->stk, jq->stk_top)) {276      jv_free(stack_pop(jq));277    } else if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {278      frame_pop(jq);279    } else {280      assert(0);281    }282  }283284  if (jq->fork_top == 0) {285    return 0;286  }287288  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);289  uint16_t* retaddr = fork->return_address;290  jq->stk_top = fork->saved_data_stack;291  jq->curr_frame = fork->saved_curr_frame;292  int path_len = fork->path_len;293  if (jv_get_kind(jq->path) == JV_KIND_ARRAY) {294    assert(path_len >= 0);295    jq->path = jv_array_slice(jq->path, 0, path_len);296  } else {297    fork->path_len = 0;298  }299  jv_free(jq->value_at_path);300  jq->value_at_path = fork->value_at_path;301  jq->subexp_nest = fork->subexp_nest;302  jq->fork_top = stack_pop_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));303  return retaddr;304}305306static void jq_reset(jq_state *jq) {307  while (stack_restore(jq)) {}308309  assert(jq->stk_top == 0);310  assert(jq->fork_top == 0);311  assert(jq->curr_frame == 0);312  stack_reset(&jq->stk);313  jv_free(jq->error);314  jq->error = jv_null();315316  jq->halted = 0;317  jv_free(jq->exit_code);318  jq->exit_code = jv_invalid();319  jv_free(jq->error_message);320  jq->error_message = jv_invalid();321  if (jv_get_kind(jq->path) != JV_KIND_INVALID)322    jv_free(jq->path);323  jq->path = jv_null();324  jv_free(jq->value_at_path);325  jq->value_at_path = jv_null();326  jq->subexp_nest = 0;327}328329void jq_report_error(jq_state *jq, jv value) {330  assert(jq->err_cb);331  // callback must jv_free() its jv argument332  jq->err_cb(jq->err_cb_data, value);333}334335static void set_error(jq_state *jq, jv value) {336  // Record so try/catch can find it.337  jv_free(jq->error);338  jq->error = value;339}340341#define ON_BACKTRACK(op) ((op)+NUM_OPCODES)342343jv jq_next(jq_state *jq) {344  jv cfunc_input[MAX_CFUNCTION_ARGS];345346  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);347348  uint16_t* pc = stack_restore(jq);349  assert(pc);350351  int raising;352  int backtracking = !jq->initial_execution;353354  jq->initial_execution = 0;355  assert(jv_get_kind(jq->error) == JV_KIND_NULL);356  while (1) {357    if (jq->halted) {358      if (jq->debug_trace_enabled)359        printf("\t<halted>\n");360      return jv_invalid();361    }362    uint16_t opcode = *pc;363    raising = 0;364365    if (jq->debug_trace_enabled) {366      dump_operation(frame_current(jq)->bc, pc);367      printf("\t");368      const struct opcode_description* opdesc = opcode_describe(opcode);369      stack_ptr param = 0;370      if (!backtracking) {371        int stack_in = opdesc->stack_in;372        if (stack_in == -1) stack_in = pc[1];373        param = jq->stk_top;374        for (int i=0; i<stack_in; i++) {375          if (i != 0) {376            printf(" | ");377            param = *stack_block_next(&jq->stk, param);378          }379          if (!param) break;380          jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);381          //printf("<%d>", jv_get_refcnt(param->val));382          //printf(" -- ");383          //jv_dump(jv_copy(jq->path), 0);384        }385        if (jq->debug_trace_enabled & JQ_DEBUG_TRACE_DETAIL) {386          while ((param = *stack_block_next(&jq->stk, param))) {387            printf(" || ");388            jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);389          }390        }391      } else {392        printf("\t<backtracking>");393      }394395      printf("\n");396    }397398    if (backtracking) {399      opcode = ON_BACKTRACK(opcode);400      backtracking = 0;401      raising = !jv_is_valid(jq->error);402    }403    pc++;404405    switch (opcode) {406    default: assert(0 && "invalid instruction");407408    case TOP: break;409410    case ERRORK: {411      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);412      set_error(jq, jv_invalid_with_msg(v));413      goto do_backtrack;414    }415416    case LOADK: {417      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);418      assert(jv_is_valid(v));419      jv_free(stack_pop(jq));420      stack_push(jq, v);421      break;422    }423424    case GENLABEL: {425      stack_push(jq, JV_OBJECT(jv_string("__jq"), jv_number(jq->next_label++)));426      break;427    }428429    case DUP: {430      jv v = stack_pop(jq);431      stack_push(jq, jv_copy(v));432      stack_push(jq, v);433      break;434    }435436    case DUPN: {437      jv v = stack_popn(jq);438      stack_push(jq, jv_copy(v));439      stack_push(jq, v);440      break;441    }442443    case DUP2: {444      jv keep = stack_pop(jq);445      jv v = stack_pop(jq);446      stack_push(jq, jv_copy(v));447      stack_push(jq, keep);448      stack_push(jq, v);449      break;450    }451452    case SUBEXP_BEGIN: {453      jv v = stack_pop(jq);454      stack_push(jq, jv_copy(v));455      stack_push(jq, v);456      jq->subexp_nest++;457      break;458    }459460    case SUBEXP_END: {461      assert(jq->subexp_nest > 0);462      jq->subexp_nest--;463      jv a = stack_pop(jq);464      jv b = stack_pop(jq);465      stack_push(jq, a);466      stack_push(jq, b);467      break;468    }469470    case PUSHK_UNDER: {471      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);472      assert(jv_is_valid(v));473      jv v2 = stack_pop(jq);474      stack_push(jq, v);475      stack_push(jq, v2);476      break;477    }478479    case POP: {480      jv_free(stack_pop(jq));481      break;482    }483484    case APPEND: {485      jv v = stack_pop(jq);486      uint16_t level = *pc++;487      uint16_t vidx = *pc++;488      jv* var = frame_local_var(jq, vidx, level);489      assert(jv_get_kind(*var) == JV_KIND_ARRAY);490      *var = jv_array_append(*var, v);491      break;492    }493494    case INSERT: {495      jv stktop = stack_pop(jq);496      jv v = stack_pop(jq);497      jv k = stack_pop(jq);498      jv objv = stack_pop(jq);499      assert(jv_get_kind(objv) == JV_KIND_OBJECT);500      if (jv_get_kind(k) == JV_KIND_STRING) {501        stack_push(jq, jv_object_set(objv, k, v));502        stack_push(jq, stktop);503      } else {504        char errbuf[15];505        set_error(jq, jv_invalid_with_msg(jv_string_fmt("Cannot use %s (%s) as object key",506                                                        jv_kind_name(jv_get_kind(k)),507                                                        jv_dump_string_trunc(jv_copy(k), errbuf, sizeof(errbuf)))));508        jv_free(stktop);509        jv_free(v);510        jv_free(k);511        jv_free(objv);512        goto do_backtrack;513      }514      break;515    }516517    case ON_BACKTRACK(RANGE):518    case RANGE: {519      uint16_t level = *pc++;520      uint16_t v = *pc++;521      jv* var = frame_local_var(jq, v, level);522      jv max = stack_pop(jq);523      if (raising) {524        jv_free(max);525        goto do_backtrack;526      } 527      if (jv_get_kind(*var) != JV_KIND_NUMBER ||528          jv_get_kind(max) != JV_KIND_NUMBER) {529        set_error(jq, jv_invalid_with_msg(jv_string_fmt("Range bounds must be numeric")));530        jv_free(max);531        goto do_backtrack;532      } else if (jv_number_value(*var) >= jv_number_value(max)) {533        /* finished iterating */534        jv_free(max);535        goto do_backtrack;536      } else {537        jv curr = *var;538        *var = jv_number(jv_number_value(*var) + 1);539540        struct stack_pos spos = stack_get_pos(jq);541        stack_push(jq, max);542        stack_save(jq, pc - 3, spos);543544        stack_push(jq, curr);545      }546      break;547    }548549      // FIXME: loadv/storev may do too much copying/freeing550    case LOADV: {551      uint16_t level = *pc++;552      uint16_t v = *pc++;553      jv* var = frame_local_var(jq, v, level);554      if (jq->debug_trace_enabled) {555        printf("V%d = ", v);556        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);557        printf("\n");558      }559      jv_free(stack_pop(jq));560      stack_push(jq, jv_copy(*var));561      break;562    }563564      // Does a load but replaces the variable with null565    case LOADVN: {566      uint16_t level = *pc++;567      uint16_t v = *pc++;568      jv* var = frame_local_var(jq, v, level);569      if (jq->debug_trace_enabled) {570        printf("V%d = ", v);571        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);572        printf("\n");573      }574      jv_free(stack_popn(jq));575576      // This `stack_push()` invalidates the `var` reference, so577      stack_push(jq, *var);578      // we have to re-resolve `var` before we can set it to null579      var = frame_local_var(jq, v, level);580      *var = jv_null();581      break;582    }583584    case STOREVN:585        stack_save(jq, pc - 1, stack_get_pos(jq));586        JQ_FALLTHROUGH;587    case STOREV: {588      uint16_t level = *pc++;589      uint16_t v = *pc++;590      jv* var = frame_local_var(jq, v, level);591      jv val = stack_pop(jq);592      if (jq->debug_trace_enabled) {593        printf("V%d = ", v);594        jv_dump(jv_copy(val), 0);595        printf(" (%d)\n", jv_get_refcnt(val));596      }597      jv_free(*var);598      *var = val;599      break;600    }601602    case ON_BACKTRACK(STOREVN): {603      uint16_t level = *pc++;604      uint16_t v = *pc++;605      jv* var = frame_local_var(jq, v, level);606      jv_free(*var);607      *var = jv_null();608      goto do_backtrack;609      break;610    }611612    case STORE_GLOBAL: {613      // Get the constant614      jv val = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);615      assert(jv_is_valid(val));616617      // Store the var618      uint16_t level = *pc++;619      uint16_t v = *pc++;620      jv* var = frame_local_var(jq, v, level);621      if (jq->debug_trace_enabled) {622        printf("V%d = ", v);623        jv_dump(jv_copy(val), 0);624        printf(" (%d)\n", jv_get_refcnt(val));625      }626      jv_free(*var);627      *var = val;628      break;629    }630631    case PATH_BEGIN: {632      jv v = stack_pop(jq);633      stack_push(jq, jq->path);634635      stack_save(jq, pc - 1, stack_get_pos(jq));636637      stack_push(jq, jv_number(jq->subexp_nest));638      stack_push(jq, jq->value_at_path);639      stack_push(jq, jv_copy(v));640641      jq->path = jv_array();642      jq->value_at_path = v; // next INDEX operation must index into v643      jq->subexp_nest = 0;644      break;645    }646647    case PATH_END: {648      jv v = stack_pop(jq);649      // detect invalid path expression like path(.a | reverse)650      if (!path_intact(jq, jv_copy(v))) {651        char errbuf[30];652        jv msg = jv_string_fmt(653            "Invalid path expression with result %s",654            jv_dump_string_trunc(v, errbuf, sizeof(errbuf)));655        set_error(jq, jv_invalid_with_msg(msg));656        goto do_backtrack;657      }658      jv_free(v); // discard value, only keep path659660      jv old_value_at_path = stack_pop(jq);661      int old_subexp_nest = (int)jv_number_value(stack_pop(jq));662663      jv path = jq->path;664      jq->path = stack_pop(jq);665666      struct stack_pos spos = stack_get_pos(jq);667      stack_push(jq, jv_copy(path));668      stack_save(jq, pc - 1, spos);669670      stack_push(jq, path);671      jq->subexp_nest = old_subexp_nest;672      jv_free(jq->value_at_path);673      jq->value_at_path = old_value_at_path;674      break;675    }676677    case ON_BACKTRACK(PATH_BEGIN):678    case ON_BACKTRACK(PATH_END): {679      jv_free(jq->path);680      jq->path = stack_pop(jq);681      goto do_backtrack;682    }683684    case INDEX:685    case INDEX_OPT: {686      jv t = stack_pop(jq);687      jv k = stack_pop(jq);688      // detect invalid path expression like path(reverse | .a)689      if (!path_intact(jq, jv_copy(t))) {690        char keybuf[15];691        char objbuf[30];692        jv msg = jv_string_fmt(693            "Invalid path expression near attempt to access element %s of %s",694            jv_dump_string_trunc(k, keybuf, sizeof(keybuf)),695            jv_dump_string_trunc(t, objbuf, sizeof(objbuf)));696        set_error(jq, jv_invalid_with_msg(msg));697        goto do_backtrack;698      }699      jv v = jv_get(t, jv_copy(k));700      if (jv_is_valid(v)) {701        path_append(jq, k, jv_copy(v));702        stack_push(jq, v);703      } else {704        jv_free(k);705        if (opcode == INDEX)706          set_error(jq, v);707        else708          jv_free(v);709        goto do_backtrack;710      }711      break;712    }713714715    case JUMP: {716      uint16_t offset = *pc++;717      pc += offset;718      break;719    }720721    case JUMP_F: {722      uint16_t offset = *pc++;723      jv t = stack_pop(jq);724      jv_kind kind = jv_get_kind(t);725      if (kind == JV_KIND_FALSE || kind == JV_KIND_NULL) {726        pc += offset;727      }728      stack_push(jq, t); // FIXME do this better729      break;730    }731732    case EACH:733    case EACH_OPT: {734      jv container = stack_pop(jq);735      // detect invalid path expression like path(reverse | .[])736      if (!path_intact(jq, jv_copy(container))) {737        char errbuf[30];738        jv msg = jv_string_fmt(739            "Invalid path expression near attempt to iterate through %s",740            jv_dump_string_trunc(container, errbuf, sizeof(errbuf)));741        set_error(jq, jv_invalid_with_msg(msg));742        goto do_backtrack;743      }744      stack_push(jq, container);745      stack_push(jq, jv_number(-1));746      JQ_FALLTHROUGH;747    }748    case ON_BACKTRACK(EACH):749    case ON_BACKTRACK(EACH_OPT): {750      int idx = jv_number_value(stack_pop(jq));751      jv container = stack_pop(jq);752753      int keep_going, is_last = 0;754      jv key, value;755      if (jv_get_kind(container) == JV_KIND_ARRAY) {756        if (opcode == EACH || opcode == EACH_OPT) idx = 0;757        else idx = idx + 1;758        int len = jv_array_length(jv_copy(container));759        keep_going = idx < len;760        is_last = idx == len - 1;761        if (keep_going) {762          key = jv_number(idx);763          value = jv_array_get(jv_copy(container), idx);764        }765      } else if (jv_get_kind(container) == JV_KIND_OBJECT) {766        if (opcode == EACH || opcode == EACH_OPT) idx = jv_object_iter(container);767        else idx = jv_object_iter_next(container, idx);768        keep_going = jv_object_iter_valid(container, idx);769        if (keep_going) {770          key = jv_object_iter_key(container, idx);771          value = jv_object_iter_value(container, idx);772        }773      } else {774        assert(opcode == EACH || opcode == EACH_OPT);775        if (opcode == EACH) {776          char errbuf[15];777          set_error(jq,778                    jv_invalid_with_msg(jv_string_fmt("Cannot iterate over %s (%s)",779                                                      jv_kind_name(jv_get_kind(container)),780                                                      jv_dump_string_trunc(jv_copy(container), errbuf, sizeof(errbuf)))));781        }782        keep_going = 0;783      }784785      if (!keep_going || raising) {786        if (keep_going) {787          jv_free(key);788          jv_free(value);789        }790        jv_free(container);791        goto do_backtrack;792      } else if (is_last) {793        // we don't need to make a backtrack point794        jv_free(container);795        path_append(jq, key, jv_copy(value));796        stack_push(jq, value);797      } else {798        struct stack_pos spos = stack_get_pos(jq);799        stack_push(jq, container);800        stack_push(jq, jv_number(idx));801        stack_save(jq, pc - 1, spos);802        path_append(jq, key, jv_copy(value));803        stack_push(jq, value);804      }805      break;806    }807808    do_backtrack:809    case BACKTRACK: {810      pc = stack_restore(jq);811      if (!pc) {812        if (!jv_is_valid(jq->error)) {813          jv error = jq->error;814          jq->error = jv_null();815          return error;816        }817        return jv_invalid();818      }819      backtracking = 1;820      break;821    }822823    case TRY_BEGIN:824      stack_save(jq, pc - 1, stack_get_pos(jq));825      pc++; // skip handler offset this time826      break;827828    case TRY_END:829      stack_save(jq, pc - 1, stack_get_pos(jq));830      break;831832    case ON_BACKTRACK(TRY_BEGIN): {833      if (!raising) {834        /*835         * `try EXP ...` -- EXP backtracked (e.g., EXP was `empty`), so we836         * backtrack more:837         */838        jv_free(stack_pop(jq));839        goto do_backtrack;840      }841842      /*843       * Else `(try EXP ... ) | EXP2` raised an error.844       *845       * If the error was wrapped in another error, then that means EXP2 raised846       * the error.  We unwrap it and re-raise it as it wasn't raised by EXP.847       *848       * See commentary in gen_try().849       */850      jv e = jv_invalid_get_msg(jv_copy(jq->error));851      if (!jv_is_valid(e) && jv_invalid_has_msg(jv_copy(e))) {852        set_error(jq, e);853        goto do_backtrack;854      }855      jv_free(e);856857      /*858       * Else we caught an error containing a non-error value, so we jump to859       * the handler.860       *861       * See commentary in gen_try().862       */863      uint16_t offset = *pc++;864      jv_free(stack_pop(jq)); // free the input865      stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message866      jq->error = jv_null();867      pc += offset;868      break;869    }870    case ON_BACKTRACK(TRY_END):871      // Wrap the error so the matching TRY_BEGIN doesn't catch it872      if (raising)873        set_error(jq, jv_invalid_with_msg(jv_copy(jq->error)));874      goto do_backtrack;875876    case DESTRUCTURE_ALT:877    case FORK: {878      stack_save(jq, pc - 1, stack_get_pos(jq));879      pc++; // skip offset this time880      break;881    }882883    case ON_BACKTRACK(DESTRUCTURE_ALT): {884      if (jv_is_valid(jq->error)) {885        // `try EXP ...` backtracked here (no value, `empty`), so we backtrack more886        jv_free(stack_pop(jq));887        goto do_backtrack;888      }889      // `try EXP ...` exception caught in EXP890      // DESTRUCTURE_ALT doesn't want the error message on the stack,891      // as we would just want to throw it away anyway.892      if (opcode != ON_BACKTRACK(DESTRUCTURE_ALT)) {893        jv_free(stack_pop(jq)); // free the input894        stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message895      } else {896        jv_free(jq->error);897      }898      jq->error = jv_null();899      uint16_t offset = *pc++;900      pc += offset;901      break;902    }903    case ON_BACKTRACK(FORK): {904      if (raising) goto do_backtrack;905      uint16_t offset = *pc++;906      pc += offset;907      break;908    }909910    case CALL_BUILTIN: {911      int nargs = *pc++;912      jv top = stack_pop(jq);913      jv* in = cfunc_input;914      in[0] = top;915      for (int i = 1; i < nargs; i++) {916        in[i] = stack_pop(jq);917      }918      struct cfunction* function = &frame_current(jq)->bc->globals->cfunctions[*pc++];919      switch (function->nargs) {920      case 1: top = ((jv (*)(jq_state *, jv))function->fptr)(jq, in[0]); break;921      case 2: top = ((jv (*)(jq_state *, jv, jv))function->fptr)(jq, in[0], in[1]); break;922      case 3: top = ((jv (*)(jq_state *, jv, jv, jv))function->fptr)(jq, in[0], in[1], in[2]); break;923      case 4: top = ((jv (*)(jq_state *, jv, jv, jv, jv))function->fptr)(jq, in[0], in[1], in[2], in[3]); break;924      case 5: top = ((jv (*)(jq_state *, jv, jv, jv, jv, jv))function->fptr)(jq, in[0], in[1], in[2], in[3], in[4]); break;925      // FIXME: a) up to 7 arguments (input + 6), b) should assert926      // because the compiler should not generate this error.927      default: return jv_invalid_with_msg(jv_string("Function takes too many arguments"));928      }929930      if (jv_is_valid(top)) {931        stack_push(jq, top);932      } else if (jv_invalid_has_msg(jv_copy(top))) {933        set_error(jq, top);934        goto do_backtrack;935      } else {936        // C-coded function returns invalid w/o msg? -> backtrack, as if937        // it had returned `empty`938        goto do_backtrack;939      }940      break;941    }942943    case TAIL_CALL_JQ:944    case CALL_JQ: {945      /*946       * Bytecode layout here:947       *948       *  CALL_JQ949       *  <nclosures>                       (i.e., number of call arguments)950       *  <callee closure>                  (what we're calling)951       *  <nclosures' worth of closures>    (frame reference + code pointer)952       *953       *  <next instruction (to return to)>954       *955       * Each closure consists of two uint16_t values: a "level"956       * identifying the frame to be closed over, and an index.957       *958       * The level is a relative number of call frames reachable from959       * the currently one; 0 -> current frame, 1 -> previous frame, and960       * so on.961       *962       * The index is either an index of the closed frame's subfunctions963       * or of the closed frame's parameter closures.  If the latter,964       * that closure will be passed, else the closed frame's pointer965       * and the subfunction's code will form the closure to be passed.966       *967       * See make_closure() for more information.968       */969      jv input = stack_pop(jq);970      uint16_t nclosures = *pc++;971      uint16_t* retaddr = pc + 2 + nclosures*2;972      stack_ptr retdata = jq->stk_top;973      struct frame* new_frame;974      struct closure cl = make_closure(jq, pc);975      if (opcode == TAIL_CALL_JQ) {976        retaddr = frame_current(jq)->retaddr;977        retdata = frame_current(jq)->retdata;978        frame_pop(jq);979      }980      new_frame = frame_push(jq, cl, pc + 2, nclosures);981      new_frame->retdata = retdata;982      new_frame->retaddr = retaddr;983      pc = new_frame->bc->code;984      stack_push(jq, input);985      break;986    }987988    case RET: {989      jv value = stack_pop(jq);990      assert(jq->stk_top == frame_current(jq)->retdata);991      uint16_t* retaddr = frame_current(jq)->retaddr;992      if (retaddr) {993        // function return994        pc = retaddr;995        frame_pop(jq);996      } else {997        // top-level return, yielding value998        struct stack_pos spos = stack_get_pos(jq);999        stack_push(jq, jv_null());1000        stack_save(jq, pc - 1, spos);1001        return value;1002      }1003      stack_push(jq, value);1004      break;1005    }1006    case ON_BACKTRACK(RET): {1007      // resumed after top-level return1008      goto do_backtrack;1009    }1010    }1011  }1012}10131014jv jq_format_error(jv msg) {1015  if (jv_get_kind(msg) == JV_KIND_NULL ||1016      (jv_get_kind(msg) == JV_KIND_INVALID && !jv_invalid_has_msg(jv_copy(msg)))) {1017    jv_free(msg);1018    fprintf(stderr, "jq: error: out of memory\n");1019    return jv_null();1020  }10211022  if (jv_get_kind(msg) == JV_KIND_STRING)1023    return msg;                         // expected to already be formatted10241025  if (jv_get_kind(msg) == JV_KIND_INVALID)1026    msg = jv_invalid_get_msg(msg);10271028  if (jv_get_kind(msg) == JV_KIND_NULL)1029    return jq_format_error(msg);        // ENOMEM10301031  // Invalid with msg; prefix with "jq: error: "10321033  if (jv_get_kind(msg) != JV_KIND_INVALID) {1034    if (jv_get_kind(msg) == JV_KIND_STRING)1035      return jv_string_fmt("jq: error: %s", jv_string_value(msg));10361037    msg = jv_dump_string(msg, JV_PRINT_INVALID);1038    if (jv_get_kind(msg) == JV_KIND_STRING)1039      return jv_string_fmt("jq: error: %s", jv_string_value(msg));1040    return jq_format_error(jv_null());  // ENOMEM1041  }10421043  // An invalid inside an invalid!1044  return jq_format_error(jv_invalid_get_msg(msg));1045}10461047// XXX Refactor into a utility function that returns a jv and one that1048// uses it and then prints that jv's string as the complete error1049// message.1050static void default_err_cb(void *data, jv msg) {1051  msg = jq_format_error(msg);1052  fprintf((FILE *)data, "%s\n", jv_string_value(msg));1053  jv_free(msg);1054}10551056jq_state *jq_init(void) {1057  jq_state *jq;1058  jq = jv_mem_alloc_unguarded(sizeof(*jq));1059  if (jq == NULL)1060    return NULL;10611062  jq->bc = 0;1063  jq->next_label = 0;10641065  stack_init(&jq->stk);1066  jq->stk_top = 0;1067  jq->fork_top = 0;1068  jq->curr_frame = 0;1069  jq->error = jv_null();10701071  jq->halted = 0;1072  jq->exit_code = jv_invalid();1073  jq->error_message = jv_invalid();10741075  jq->input_cb = NULL;1076  jq->input_cb_data = NULL;10771078  jq->debug_cb = NULL;1079  jq->debug_cb_data = NULL;10801081  jq->stderr_cb = NULL;1082  jq->stderr_cb_data = NULL;10831084  jq->err_cb = default_err_cb;1085  jq->err_cb_data = stderr;10861087  jq->attrs = jv_object();1088  jq->path = jv_null();1089  jq->value_at_path = jv_null();10901091  jq->nomem_handler = NULL;1092  jq->nomem_handler_data = NULL;1093  return jq;1094}10951096void jq_set_error_cb(jq_state *jq, jq_msg_cb cb, void *data) {1097  if (cb == NULL) {1098    jq->err_cb = default_err_cb;1099    jq->err_cb_data = stderr;1100  } else {1101    jq->err_cb = cb;1102    jq->err_cb_data = data;1103  }1104}11051106void jq_get_error_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1107  *cb = jq->err_cb;1108  *data = jq->err_cb_data;1109}11101111void jq_set_nomem_handler(jq_state *jq, void (*nomem_handler)(void *), void *data) {1112  jv_nomem_handler(nomem_handler, data);1113  jq->nomem_handler = nomem_handler;1114  jq->nomem_handler_data = data;1115}111611171118void jq_start(jq_state *jq, jv input, int flags) {1119  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1120  jq_reset(jq);11211122  struct closure top = {jq->bc, -1};1123  struct frame* top_frame = frame_push(jq, top, 0, 0);1124  top_frame->retdata = 0;1125  top_frame->retaddr = 0;11261127  stack_push(jq, input);1128  stack_save(jq, jq->bc->code, stack_get_pos(jq));1129  jq->debug_trace_enabled = flags & JQ_DEBUG_TRACE_ALL;1130  jq->initial_execution = 1;1131}11321133void jq_teardown(jq_state **jq) {1134  jq_state *old_jq = *jq;1135  if (old_jq == NULL)1136    return;1137  *jq = NULL;11381139  jq_reset(old_jq);1140  bytecode_free(old_jq->bc);1141  old_jq->bc = 0;1142  jv_free(old_jq->attrs);11431144  jv_mem_free(old_jq);1145}11461147static int ret_follows(uint16_t *pc) {1148  if (*pc == RET)1149    return 1;1150  if (*pc++ != JUMP)1151    return 0;1152  return ret_follows(pc + *pc + 1); // FIXME, might be ironic1153}11541155/*1156 * Look for tail calls that can be optimized: tail calls with no1157 * references left to the current frame.1158 *1159 * We're staring at this bytecode layout:1160 *1161 *   CALL_JQ1162 *   <nclosures>1163 *   <callee closure>       (2 units)1164 *   <nclosures closures>   (2 units each)1165 *   <next instruction>1166 *1167 * A closure is:1168 *1169 *   <level>    (a relative frame count chased via the current frame's env)1170 *   <index>    (an index of a subfunction or closure in that frame)1171 *1172 * We're looking for:1173 *1174 * a) the next instruction is a RET or a chain of unconditional JUMPs1175 * that ends in a RET, and1176 *1177 * b) none of the closures -callee included- have level == 0.1178 */1179static uint16_t tail_call_analyze(uint16_t *pc) {1180  assert(*pc == CALL_JQ);1181  pc++;1182  // + 1 for the callee closure1183  for (uint16_t nclosures = *pc++ + 1; nclosures > 0; pc++, nclosures--) {1184    if (*pc++ == 0)1185      return CALL_JQ;1186  }1187  if (ret_follows(pc))1188    return TAIL_CALL_JQ;1189  return CALL_JQ;1190}11911192static struct bytecode *optimize_code(struct bytecode *bc) {1193  uint16_t *pc = bc->code;1194  // FIXME: Don't mutate bc->code...1195  while (pc < bc->code + bc->codelen) {1196    switch (*pc) {1197    case CALL_JQ:1198      *pc = tail_call_analyze(pc);1199      break;12001201    // Other bytecode optimizations here.  A peephole optimizer would1202    // fit right in.1203    default: break;1204    }1205    pc += bytecode_operation_length(pc);1206  }1207  return bc;1208}12091210static struct bytecode *optimize(struct bytecode *bc) {1211  for (int i=0; i<bc->nsubfunctions; i++) {1212    bc->subfunctions[i] = optimize(bc->subfunctions[i]);1213  }1214  return optimize_code(bc);1215}12161217static jv1218args2obj(jv args)1219{1220  if (jv_get_kind(args) == JV_KIND_OBJECT)1221    return args;1222  assert(jv_get_kind(args) == JV_KIND_ARRAY);1223  jv r = jv_object();1224  jv kk = jv_string("name");1225  jv vk = jv_string("value");1226  jv_array_foreach(args, i, v)1227    r = jv_object_set(r, jv_object_get(jv_copy(v), kk), jv_object_get(v, vk));1228  jv_free(args);1229  jv_free(kk);1230  jv_free(vk);1231  return r;1232}12331234int jq_compile_args(jq_state *jq, const char* str, jv args) {1235  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1236  assert(jv_get_kind(args) == JV_KIND_ARRAY || jv_get_kind(args) == JV_KIND_OBJECT);1237  struct locfile* locations;1238  locations = locfile_init(jq, "<top-level>", str, strlen(str));1239  block program;1240  jq_reset(jq);1241  if (jq->bc) {1242    bytecode_free(jq->bc);1243    jq->bc = 0;1244  }1245  int nerrors = load_program(jq, locations, &program);1246  if (nerrors == 0) {1247    nerrors = builtins_bind(jq, &program);1248    if (nerrors == 0) {1249      nerrors = block_compile(program, &jq->bc, locations, args2obj(args));1250    }1251  } else1252    jv_free(args);1253  if (nerrors)1254    jq_report_error(jq, jv_string_fmt("jq: %d compile %s", nerrors, nerrors > 1 ? "errors" : "error"));1255  if (jq->bc)1256    jq->bc = optimize(jq->bc);1257  locfile_free(locations);1258  return jq->bc != NULL;1259}12601261int jq_compile(jq_state *jq, const char* str) {1262  return jq_compile_args(jq, str, jv_object());1263}12641265jv jq_get_jq_origin(jq_state *jq) {1266  return jq_get_attr(jq, jv_string("JQ_ORIGIN"));1267}12681269jv jq_get_prog_origin(jq_state *jq) {1270  return jq_get_attr(jq, jv_string("PROGRAM_ORIGIN"));1271}12721273jv jq_get_lib_dirs(jq_state *jq) {1274  jv lib_dirs = jq_get_attr(jq, jv_string("JQ_LIBRARY_PATH"));1275  return jv_is_valid(lib_dirs) ? lib_dirs : jv_array();1276}12771278void jq_set_attrs(jq_state *jq, jv attrs) {1279  assert(jv_get_kind(attrs) == JV_KIND_OBJECT);1280  jv_free(jq->attrs);1281  jq->attrs = attrs;1282}12831284void jq_set_attr(jq_state *jq, jv attr, jv val) {1285  jq->attrs = jv_object_set(jq->attrs, attr, val);1286}12871288jv jq_get_attr(jq_state *jq, jv attr) {1289  return jv_object_get(jv_copy(jq->attrs), attr);1290}12911292void jq_dump_disassembly(jq_state *jq, int indent) {1293  dump_disassembly(indent, jq->bc);1294}12951296void jq_set_input_cb(jq_state *jq, jq_input_cb cb, void *data) {1297  jq->input_cb = cb;1298  jq->input_cb_data = data;1299}13001301void jq_get_input_cb(jq_state *jq, jq_input_cb *cb, void **data) {1302  *cb = jq->input_cb;1303  *data = jq->input_cb_data;1304}13051306void jq_set_debug_cb(jq_state *jq, jq_msg_cb cb, void *data) {1307  jq->debug_cb = cb;1308  jq->debug_cb_data = data;1309}13101311void jq_get_debug_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1312  *cb = jq->debug_cb;1313  *data = jq->debug_cb_data;1314}13151316void jq_set_stderr_cb(jq_state *jq, jq_msg_cb cb, void *data) {1317  jq->stderr_cb = cb;1318  jq->stderr_cb_data = data;1319}13201321void jq_get_stderr_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1322  *cb = jq->stderr_cb;1323  *data = jq->stderr_cb_data;1324}13251326void1327jq_halt(jq_state *jq, jv exit_code, jv error_message)1328{1329  assert(!jq->halted);1330  jq->halted = 1;1331  jq->exit_code = exit_code;1332  jq->error_message = error_message;1333}13341335int1336jq_halted(jq_state *jq)1337{1338  return jq->halted;1339}13401341jv jq_get_exit_code(jq_state *jq)1342{1343  return jv_copy(jq->exit_code);1344}13451346jv jq_get_error_message(jq_state *jq)1347{1348  return jv_copy(jq->error_message);1349}