Skip to content
Myr

execute.c

This file

Path

src/execute.c

1,348 lines · 35.8 KiB · C

Last changed by

Fix memory leaks and double frees (#3487)itchynybefore adoption750dbe7

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 "locfile.h"14#include "jv.h"15#include "jq.h"16#include "builtin.h"17#include "linker.h"1819struct jq_state {20  void (*nomem_handler)(void *);21  void *nomem_handler_data;22  struct bytecode* bc;2324  jq_msg_cb err_cb;25  void *err_cb_data;26  jv error;2728  struct stack stk;29  stack_ptr curr_frame;30  stack_ptr stk_top;31  stack_ptr fork_top;3233  jv path;34  jv value_at_path;35  int subexp_nest;36  int debug_trace_enabled;37  int initial_execution;38  unsigned next_label;3940  int halted;41  jv exit_code;42  jv error_message;4344  jv attrs;45  jq_input_cb input_cb;46  void *input_cb_data;47  jq_msg_cb debug_cb;48  void *debug_cb_data;49  jq_msg_cb stderr_cb;50  void *stderr_cb_data;51};5253struct closure {54  struct bytecode* bc;  // jq bytecode55  stack_ptr env;        // jq stack address of closed frame56};5758// locals for any function called: either a closure or a local variable59union frame_entry {60  struct closure closure;61  jv localvar;62};6364// jq function call frame65struct frame {66  struct bytecode* bc;      // jq bytecode for callee67  stack_ptr env;            // jq stack address of frame to return to68  stack_ptr retdata;        // jq stack address to unwind to on RET69  uint16_t* retaddr;        // jq bytecode return address70  union frame_entry entries[]; // nclosures + nlocals71};7273static int frame_size(struct bytecode* bc) {74  return sizeof(struct frame) + sizeof(union frame_entry) * (bc->nclosures + bc->nlocals);75}7677static struct frame* frame_current(struct jq_state* jq) {78  struct frame* fp = stack_block(&jq->stk, jq->curr_frame);7980  stack_ptr next = *stack_block_next(&jq->stk, jq->curr_frame);81  if (next) {82    struct frame* fpnext = stack_block(&jq->stk, next);83    struct bytecode* bc = fpnext->bc;84    assert(fp->retaddr >= bc->code && fp->retaddr < bc->code + bc->codelen);85  } else {86    assert(fp->retaddr == 0);87  }88  return fp;89}9091static stack_ptr frame_get_level(struct jq_state* jq, int level) {92  stack_ptr fr = jq->curr_frame;93  for (int i=0; i<level; i++) {94    struct frame* fp = stack_block(&jq->stk, fr);95    fr = fp->env;96  }97  return fr;98}99100static jv* frame_local_var(struct jq_state* jq, int var, int level) {101  struct frame* fr = stack_block(&jq->stk, frame_get_level(jq, level));102  assert(var >= 0);103  assert(var < fr->bc->nlocals);104  return &fr->entries[fr->bc->nclosures + var].localvar;105}106107static struct closure make_closure(struct jq_state* jq, uint16_t* pc) {108  uint16_t level = *pc++;109  uint16_t idx = *pc++;110  stack_ptr fridx = frame_get_level(jq, level);111  struct frame* fr = stack_block(&jq->stk, fridx);112  if (idx & ARG_NEWCLOSURE) {113    // A new closure closing the frame identified by level, and with114    // the bytecode body of the idx'th subfunction of that frame115    int subfn_idx = idx & ~ARG_NEWCLOSURE;116    assert(subfn_idx < fr->bc->nsubfunctions);117    struct closure cl = {fr->bc->subfunctions[subfn_idx],118                         fridx};119    return cl;120  } else {121    // A reference to a closure from the frame identified by level; copy122    // it as-is123    int closure = idx;124    assert(closure >= 0);125    assert(closure < fr->bc->nclosures);126    return fr->entries[closure].closure;127  }128}129130static struct frame* frame_push(struct jq_state* jq, struct closure callee,131                                uint16_t* argdef, int nargs) {132  stack_ptr new_frame_idx = stack_push_block(&jq->stk, jq->curr_frame, frame_size(callee.bc));133  struct frame* new_frame = stack_block(&jq->stk, new_frame_idx);134  new_frame->bc = callee.bc;135  new_frame->env = callee.env;136  assert(nargs == new_frame->bc->nclosures);137  union frame_entry* entries = new_frame->entries;138  for (int i=0; i<nargs; i++) {139    entries->closure = make_closure(jq, argdef + i * 2);140    entries++;141  }142  for (int i=0; i<callee.bc->nlocals; i++) {143    entries->localvar = jv_invalid();144    entries++;145  }146  jq->curr_frame = new_frame_idx;147  return new_frame;148}149150static void frame_pop(struct jq_state* jq) {151  assert(jq->curr_frame);152  struct frame* fp = frame_current(jq);153  if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {154    int nlocals = fp->bc->nlocals;155    for (int i=0; i<nlocals; i++) {156      jv_free(*frame_local_var(jq, i, 0));157    }158  }159  jq->curr_frame = stack_pop_block(&jq->stk, jq->curr_frame, frame_size(fp->bc));160}161162void stack_push(jq_state *jq, jv val) {163  assert(jv_is_valid(val));164  jq->stk_top = stack_push_block(&jq->stk, jq->stk_top, sizeof(jv));165  jv* sval = stack_block(&jq->stk, jq->stk_top);166  *sval = val;167}168169jv stack_pop(jq_state *jq) {170  jv* sval = stack_block(&jq->stk, jq->stk_top);171  jv val = *sval;172  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {173    val = jv_copy(val);174  }175  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));176  assert(jv_is_valid(val));177  return val;178}179180// Like stack_pop(), but assert !stack_pop_will_free() and replace with181// jv_null() on the stack.182jv stack_popn(jq_state *jq) {183  jv* sval = stack_block(&jq->stk, jq->stk_top);184  jv val = *sval;185  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {186    *sval = jv_null();187  }188  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));189  assert(jv_is_valid(val));190  return val;191}192193194struct forkpoint {195  stack_ptr saved_data_stack;196  stack_ptr saved_curr_frame;197  int path_len, subexp_nest;198  jv value_at_path;199  uint16_t* return_address;200};201202struct stack_pos {203  stack_ptr saved_data_stack, saved_curr_frame;204};205206struct stack_pos stack_get_pos(jq_state* jq) {207  struct stack_pos sp = {jq->stk_top, jq->curr_frame};208  return sp;209}210211void stack_save(jq_state *jq, uint16_t* retaddr, struct stack_pos sp){212  jq->fork_top = stack_push_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));213  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);214  fork->saved_data_stack = jq->stk_top;215  fork->saved_curr_frame = jq->curr_frame;216  fork->path_len =217    jv_get_kind(jq->path) == JV_KIND_ARRAY ? jv_array_length(jv_copy(jq->path)) : 0;218  fork->value_at_path = jv_copy(jq->value_at_path);219  fork->subexp_nest = jq->subexp_nest;220  fork->return_address = retaddr;221  jq->stk_top = sp.saved_data_stack;222  jq->curr_frame = sp.saved_curr_frame;223}224225static int path_intact(jq_state *jq, jv curr) {226  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {227    return jv_identical(curr, jv_copy(jq->value_at_path));228  } else {229    jv_free(curr);230    return 1;231  }232}233234static void path_append(jq_state* jq, jv component, jv value_at_path) {235  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {236    int n1 = jv_array_length(jv_copy(jq->path));237    jq->path = jv_array_append(jq->path, component);238    int n2 = jv_array_length(jv_copy(jq->path));239    assert(n2 == n1 + 1);240    jv_free(jq->value_at_path);241    jq->value_at_path = value_at_path;242  } else {243    jv_free(component);244    jv_free(value_at_path);245  }246}247248/* For f_getpath() */249jv250_jq_path_append(jq_state *jq, jv v, jv p, jv value_at_path) {251  if (jq->subexp_nest != 0 ||252      jv_get_kind(jq->path) != JV_KIND_ARRAY ||253      !jv_is_valid(value_at_path)) {254    jv_free(v);255    jv_free(p);256    return value_at_path;257  }258  if (!jv_identical(v, jv_copy(jq->value_at_path))) {259    jv_free(p);260    return value_at_path;261  }262  if (jv_get_kind(p) == JV_KIND_ARRAY)263    jq->path = jv_array_concat(jq->path, p);264  else265    jq->path = jv_array_append(jq->path, p);266  jv_free(jq->value_at_path);267  return jv_copy(jq->value_at_path = value_at_path);268}269270uint16_t* stack_restore(jq_state *jq){271  while (!stack_pop_will_free(&jq->stk, jq->fork_top)) {272    if (stack_pop_will_free(&jq->stk, jq->stk_top)) {273      jv_free(stack_pop(jq));274    } else if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {275      frame_pop(jq);276    } else {277      assert(0);278    }279  }280281  if (jq->fork_top == 0) {282    return 0;283  }284285  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);286  uint16_t* retaddr = fork->return_address;287  jq->stk_top = fork->saved_data_stack;288  jq->curr_frame = fork->saved_curr_frame;289  int path_len = fork->path_len;290  if (jv_get_kind(jq->path) == JV_KIND_ARRAY) {291    assert(path_len >= 0);292    jq->path = jv_array_slice(jq->path, 0, path_len);293  } else {294    fork->path_len = 0;295  }296  jv_free(jq->value_at_path);297  jq->value_at_path = fork->value_at_path;298  jq->subexp_nest = fork->subexp_nest;299  jq->fork_top = stack_pop_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));300  return retaddr;301}302303static void jq_reset(jq_state *jq) {304  while (stack_restore(jq)) {}305306  assert(jq->stk_top == 0);307  assert(jq->fork_top == 0);308  assert(jq->curr_frame == 0);309  stack_reset(&jq->stk);310  jv_free(jq->error);311  jq->error = jv_null();312313  jq->halted = 0;314  jv_free(jq->exit_code);315  jq->exit_code = jv_invalid();316  jv_free(jq->error_message);317  jq->error_message = jv_invalid();318  if (jv_get_kind(jq->path) != JV_KIND_INVALID)319    jv_free(jq->path);320  jq->path = jv_null();321  jv_free(jq->value_at_path);322  jq->value_at_path = jv_null();323  jq->subexp_nest = 0;324}325326void jq_report_error(jq_state *jq, jv value) {327  assert(jq->err_cb);328  // callback must jv_free() its jv argument329  jq->err_cb(jq->err_cb_data, value);330}331332static void set_error(jq_state *jq, jv value) {333  // Record so try/catch can find it.334  jv_free(jq->error);335  jq->error = value;336}337338#define ON_BACKTRACK(op) ((op)+NUM_OPCODES)339340jv jq_next(jq_state *jq) {341  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);342343  uint16_t* pc = stack_restore(jq);344  assert(pc);345346  int raising;347  int backtracking = !jq->initial_execution;348349  jq->initial_execution = 0;350  assert(jv_get_kind(jq->error) == JV_KIND_NULL);351  while (1) {352    if (jq->halted) {353      if (jq->debug_trace_enabled)354        printf("\t<halted>\n");355      return jv_invalid();356    }357    uint16_t opcode = *pc;358    raising = 0;359360    if (jq->debug_trace_enabled) {361      dump_operation(frame_current(jq)->bc, pc);362      printf("\t");363      const struct opcode_description* opdesc = opcode_describe(opcode);364      stack_ptr param = 0;365      if (!backtracking) {366        int stack_in = opdesc->stack_in;367        if (stack_in == -1) stack_in = pc[1];368        param = jq->stk_top;369        for (int i=0; i<stack_in; i++) {370          if (i != 0) {371            printf(" | ");372            param = *stack_block_next(&jq->stk, param);373          }374          if (!param) break;375          jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);376          //printf("<%d>", jv_get_refcnt(param->val));377          //printf(" -- ");378          //jv_dump(jv_copy(jq->path), 0);379        }380        if (jq->debug_trace_enabled & JQ_DEBUG_TRACE_DETAIL) {381          while ((param = *stack_block_next(&jq->stk, param))) {382            printf(" || ");383            jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);384          }385        }386      } else {387        printf("\t<backtracking>");388      }389390      printf("\n");391    }392393    if (backtracking) {394      opcode = ON_BACKTRACK(opcode);395      backtracking = 0;396      raising = !jv_is_valid(jq->error);397    }398    pc++;399400    switch (opcode) {401    default: assert(0 && "invalid instruction");402403    case TOP: break;404405    case ERRORK: {406      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);407      set_error(jq, jv_invalid_with_msg(v));408      goto do_backtrack;409    }410411    case LOADK: {412      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);413      assert(jv_is_valid(v));414      jv_free(stack_pop(jq));415      stack_push(jq, v);416      break;417    }418419    case GENLABEL: {420      stack_push(jq, JV_OBJECT(jv_string("__jq"), jv_number(jq->next_label++)));421      break;422    }423424    case DUP: {425      jv v = stack_pop(jq);426      stack_push(jq, jv_copy(v));427      stack_push(jq, v);428      break;429    }430431    case DUPN: {432      jv v = stack_popn(jq);433      stack_push(jq, jv_copy(v));434      stack_push(jq, v);435      break;436    }437438    case DUP2: {439      jv keep = stack_pop(jq);440      jv v = stack_pop(jq);441      stack_push(jq, jv_copy(v));442      stack_push(jq, keep);443      stack_push(jq, v);444      break;445    }446447    case SUBEXP_BEGIN: {448      jv v = stack_pop(jq);449      stack_push(jq, jv_copy(v));450      stack_push(jq, v);451      jq->subexp_nest++;452      break;453    }454455    case SUBEXP_END: {456      assert(jq->subexp_nest > 0);457      jq->subexp_nest--;458      jv a = stack_pop(jq);459      jv b = stack_pop(jq);460      stack_push(jq, a);461      stack_push(jq, b);462      break;463    }464465    case PUSHK_UNDER: {466      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);467      assert(jv_is_valid(v));468      jv v2 = stack_pop(jq);469      stack_push(jq, v);470      stack_push(jq, v2);471      break;472    }473474    case POP: {475      jv_free(stack_pop(jq));476      break;477    }478479    case APPEND: {480      jv v = stack_pop(jq);481      uint16_t level = *pc++;482      uint16_t vidx = *pc++;483      jv* var = frame_local_var(jq, vidx, level);484      assert(jv_get_kind(*var) == JV_KIND_ARRAY);485      *var = jv_array_append(*var, v);486      break;487    }488489    case INSERT: {490      jv stktop = stack_pop(jq);491      jv v = stack_pop(jq);492      jv k = stack_pop(jq);493      jv objv = stack_pop(jq);494      assert(jv_get_kind(objv) == JV_KIND_OBJECT);495      if (jv_get_kind(k) == JV_KIND_STRING) {496        stack_push(jq, jv_object_set(objv, k, v));497        stack_push(jq, stktop);498      } else {499        char errbuf[30];500        set_error(jq, jv_invalid_with_msg(jv_string_fmt(501                "Cannot use %s (%s) as object key",502                jv_kind_name(jv_get_kind(k)),503                jv_dump_string_trunc(jv_copy(k), errbuf, sizeof(errbuf)))));504        jv_free(stktop);505        jv_free(v);506        jv_free(k);507        jv_free(objv);508        goto do_backtrack;509      }510      break;511    }512513    case ON_BACKTRACK(RANGE):514    case RANGE: {515      uint16_t level = *pc++;516      uint16_t v = *pc++;517      jv* var = frame_local_var(jq, v, level);518      jv max = stack_pop(jq);519      if (raising) {520        jv_free(max);521        goto do_backtrack;522      } 523      if (jv_get_kind(*var) != JV_KIND_NUMBER ||524          jv_get_kind(max) != JV_KIND_NUMBER) {525        set_error(jq, jv_invalid_with_msg(jv_string_fmt("Range bounds must be numeric")));526        jv_free(max);527        goto do_backtrack;528      } else if (jv_number_value(*var) >= jv_number_value(max)) {529        /* finished iterating */530        jv_free(max);531        goto do_backtrack;532      } else {533        jv curr = *var;534        *var = jv_number(jv_number_value(*var) + 1);535536        struct stack_pos spos = stack_get_pos(jq);537        stack_push(jq, max);538        stack_save(jq, pc - 3, spos);539540        stack_push(jq, curr);541      }542      break;543    }544545      // FIXME: loadv/storev may do too much copying/freeing546    case LOADV: {547      uint16_t level = *pc++;548      uint16_t v = *pc++;549      jv* var = frame_local_var(jq, v, level);550      if (jq->debug_trace_enabled) {551        printf("V%d = ", v);552        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);553        printf("\n");554      }555      jv_free(stack_pop(jq));556      stack_push(jq, jv_copy(*var));557      break;558    }559560      // Does a load but replaces the variable with null561    case LOADVN: {562      uint16_t level = *pc++;563      uint16_t v = *pc++;564      jv* var = frame_local_var(jq, v, level);565      if (jq->debug_trace_enabled) {566        printf("V%d = ", v);567        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);568        printf("\n");569      }570      jv_free(stack_popn(jq));571572      // This `stack_push()` invalidates the `var` reference, so573      stack_push(jq, *var);574      // we have to re-resolve `var` before we can set it to null575      var = frame_local_var(jq, v, level);576      *var = jv_null();577      break;578    }579580    case STOREVN:581        stack_save(jq, pc - 1, stack_get_pos(jq));582        JQ_FALLTHROUGH;583    case STOREV: {584      uint16_t level = *pc++;585      uint16_t v = *pc++;586      jv* var = frame_local_var(jq, v, level);587      jv val = stack_pop(jq);588      if (jq->debug_trace_enabled) {589        printf("V%d = ", v);590        jv_dump(jv_copy(val), 0);591        printf(" (%d)\n", jv_get_refcnt(val));592      }593      jv_free(*var);594      *var = val;595      break;596    }597598    case ON_BACKTRACK(STOREVN): {599      uint16_t level = *pc++;600      uint16_t v = *pc++;601      jv* var = frame_local_var(jq, v, level);602      jv_free(*var);603      *var = jv_null();604      goto do_backtrack;605      break;606    }607608    case STORE_GLOBAL: {609      // Get the constant610      jv val = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);611      assert(jv_is_valid(val));612613      // Store the var614      uint16_t level = *pc++;615      uint16_t v = *pc++;616      jv* var = frame_local_var(jq, v, level);617      if (jq->debug_trace_enabled) {618        printf("V%d = ", v);619        jv_dump(jv_copy(val), 0);620        printf(" (%d)\n", jv_get_refcnt(val));621      }622      jv_free(*var);623      *var = val;624      break;625    }626627    case PATH_BEGIN: {628      jv v = stack_pop(jq);629      stack_push(jq, jq->path);630631      stack_save(jq, pc - 1, stack_get_pos(jq));632633      stack_push(jq, jv_number(jq->subexp_nest));634      stack_push(jq, jq->value_at_path);635      stack_push(jq, jv_copy(v));636637      jq->path = jv_array();638      jq->value_at_path = v; // next INDEX operation must index into v639      jq->subexp_nest = 0;640      break;641    }642643    case PATH_END: {644      jv v = stack_pop(jq);645      // detect invalid path expression like path(.a | reverse)646      if (!path_intact(jq, jv_copy(v))) {647        char errbuf[30];648        jv msg = jv_string_fmt(649            "Invalid path expression with result %s",650            jv_dump_string_trunc(v, errbuf, sizeof(errbuf)));651        set_error(jq, jv_invalid_with_msg(msg));652        goto do_backtrack;653      }654      jv_free(v); // discard value, only keep path655656      jv old_value_at_path = stack_pop(jq);657      int old_subexp_nest = (int)jv_number_value(stack_pop(jq));658659      jv path = jq->path;660      jq->path = stack_pop(jq);661662      struct stack_pos spos = stack_get_pos(jq);663      stack_push(jq, jv_copy(path));664      stack_save(jq, pc - 1, spos);665666      stack_push(jq, path);667      jq->subexp_nest = old_subexp_nest;668      jv_free(jq->value_at_path);669      jq->value_at_path = old_value_at_path;670      break;671    }672673    case ON_BACKTRACK(PATH_BEGIN):674    case ON_BACKTRACK(PATH_END): {675      jv_free(jq->path);676      jq->path = stack_pop(jq);677      goto do_backtrack;678    }679680    case INDEX:681    case INDEX_OPT: {682      jv t = stack_pop(jq);683      jv k = stack_pop(jq);684      // detect invalid path expression like path(reverse | .a)685      if (!path_intact(jq, jv_copy(t))) {686        char keybuf[30];687        char objbuf[30];688        jv msg = jv_string_fmt(689            "Invalid path expression near attempt to access element %s of %s",690            jv_dump_string_trunc(k, keybuf, sizeof(keybuf)),691            jv_dump_string_trunc(t, objbuf, sizeof(objbuf)));692        set_error(jq, jv_invalid_with_msg(msg));693        goto do_backtrack;694      }695      jv v = jv_get(t, jv_copy(k));696      if (jv_is_valid(v)) {697        path_append(jq, k, jv_copy(v));698        stack_push(jq, v);699      } else {700        jv_free(k);701        if (opcode == INDEX)702          set_error(jq, v);703        else704          jv_free(v);705        goto do_backtrack;706      }707      break;708    }709710711    case JUMP: {712      uint16_t offset = *pc++;713      pc += offset;714      break;715    }716717    case JUMP_F: {718      uint16_t offset = *pc++;719      jv t = stack_pop(jq);720      jv_kind kind = jv_get_kind(t);721      if (kind == JV_KIND_FALSE || kind == JV_KIND_NULL) {722        pc += offset;723      }724      stack_push(jq, t); // FIXME do this better725      break;726    }727728    case EACH:729    case EACH_OPT: {730      jv container = stack_pop(jq);731      // detect invalid path expression like path(reverse | .[])732      if (!path_intact(jq, jv_copy(container))) {733        char errbuf[30];734        jv msg = jv_string_fmt(735            "Invalid path expression near attempt to iterate through %s",736            jv_dump_string_trunc(container, errbuf, sizeof(errbuf)));737        set_error(jq, jv_invalid_with_msg(msg));738        goto do_backtrack;739      }740      stack_push(jq, container);741      stack_push(jq, jv_number(-1));742      JQ_FALLTHROUGH;743    }744    case ON_BACKTRACK(EACH):745    case ON_BACKTRACK(EACH_OPT): {746      int idx = jv_number_value(stack_pop(jq));747      jv container = stack_pop(jq);748749      int keep_going, is_last = 0;750      jv key, value;751      if (jv_get_kind(container) == JV_KIND_ARRAY) {752        if (opcode == EACH || opcode == EACH_OPT) idx = 0;753        else idx = idx + 1;754        int len = jv_array_length(jv_copy(container));755        keep_going = idx < len;756        is_last = idx == len - 1;757        if (keep_going) {758          key = jv_number(idx);759          value = jv_array_get(jv_copy(container), idx);760        }761      } else if (jv_get_kind(container) == JV_KIND_OBJECT) {762        if (opcode == EACH || opcode == EACH_OPT) idx = jv_object_iter(container);763        else idx = jv_object_iter_next(container, idx);764        keep_going = jv_object_iter_valid(container, idx);765        if (keep_going) {766          key = jv_object_iter_key(container, idx);767          value = jv_object_iter_value(container, idx);768        }769      } else {770        assert(opcode == EACH || opcode == EACH_OPT);771        if (opcode == EACH) {772          char errbuf[30];773          set_error(jq, jv_invalid_with_msg(jv_string_fmt(774                  "Cannot iterate over %s (%s)",775                  jv_kind_name(jv_get_kind(container)),776                  jv_dump_string_trunc(jv_copy(container), errbuf, sizeof(errbuf)))));777        }778        keep_going = 0;779      }780781      if (!keep_going || raising) {782        if (keep_going) {783          jv_free(key);784          jv_free(value);785        }786        jv_free(container);787        goto do_backtrack;788      } else if (is_last) {789        // we don't need to make a backtrack point790        jv_free(container);791        path_append(jq, key, jv_copy(value));792        stack_push(jq, value);793      } else {794        struct stack_pos spos = stack_get_pos(jq);795        stack_push(jq, container);796        stack_push(jq, jv_number(idx));797        stack_save(jq, pc - 1, spos);798        path_append(jq, key, jv_copy(value));799        stack_push(jq, value);800      }801      break;802    }803804    do_backtrack:805    case BACKTRACK: {806      pc = stack_restore(jq);807      if (!pc) {808        if (!jv_is_valid(jq->error)) {809          jv error = jq->error;810          jq->error = jv_null();811          return error;812        }813        return jv_invalid();814      }815      backtracking = 1;816      break;817    }818819    case TRY_BEGIN:820      stack_save(jq, pc - 1, stack_get_pos(jq));821      pc++; // skip handler offset this time822      break;823824    case TRY_END:825      stack_save(jq, pc - 1, stack_get_pos(jq));826      break;827828    case ON_BACKTRACK(TRY_BEGIN): {829      if (!raising) {830        /*831         * `try EXP ...` -- EXP backtracked (e.g., EXP was `empty`), so we832         * backtrack more:833         */834        jv_free(stack_pop(jq));835        goto do_backtrack;836      }837838      /*839       * Else `(try EXP ... ) | EXP2` raised an error.840       *841       * If the error was wrapped in another error, then that means EXP2 raised842       * the error.  We unwrap it and re-raise it as it wasn't raised by EXP.843       *844       * See commentary in gen_try().845       */846      jv e = jv_invalid_get_msg(jv_copy(jq->error));847      if (!jv_is_valid(e) && jv_invalid_has_msg(jv_copy(e))) {848        set_error(jq, e);849        goto do_backtrack;850      }851      jv_free(e);852853      /*854       * Else we caught an error containing a non-error value, so we jump to855       * the handler.856       *857       * See commentary in gen_try().858       */859      uint16_t offset = *pc++;860      jv_free(stack_pop(jq)); // free the input861      stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message862      jq->error = jv_null();863      pc += offset;864      break;865    }866    case ON_BACKTRACK(TRY_END):867      // Wrap the error so the matching TRY_BEGIN doesn't catch it868      if (raising)869        set_error(jq, jv_invalid_with_msg(jv_copy(jq->error)));870      goto do_backtrack;871872    case DESTRUCTURE_ALT:873    case FORK: {874      stack_save(jq, pc - 1, stack_get_pos(jq));875      pc++; // skip offset this time876      break;877    }878879    case ON_BACKTRACK(DESTRUCTURE_ALT): {880      if (jv_is_valid(jq->error)) {881        // `try EXP ...` backtracked here (no value, `empty`), so we backtrack more882        jv_free(stack_pop(jq));883        goto do_backtrack;884      }885      // `try EXP ...` exception caught in EXP886      // DESTRUCTURE_ALT doesn't want the error message on the stack,887      // as we would just want to throw it away anyway.888      if (opcode != ON_BACKTRACK(DESTRUCTURE_ALT)) {889        jv_free(stack_pop(jq)); // free the input890        stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message891      } else {892        jv_free(jq->error);893      }894      jq->error = jv_null();895      uint16_t offset = *pc++;896      pc += offset;897      break;898    }899    case ON_BACKTRACK(FORK): {900      if (raising) goto do_backtrack;901      uint16_t offset = *pc++;902      pc += offset;903      break;904    }905906    case CALL_BUILTIN: {907      int nargs = *pc++;908      struct cfunction* function = &frame_current(jq)->bc->globals->cfunctions[*pc++];909      jv in[MAX_CFUNCTION_ARGS];910      for (int i = 0; i < nargs; ++i)911        in[i] = stack_pop(jq);912913      jv top;914      switch (function->nargs) {915      case 1: top = function->fptr.a1(jq, in[0]); break;916      case 2: top = function->fptr.a2(jq, in[0], in[1]); break;917      case 3: top = function->fptr.a3(jq, in[0], in[1], in[2]); break;918      case 4: top = function->fptr.a4(jq, in[0], in[1], in[2], in[3]); break;919      default: assert(0 && "Invalid number of arguments");920      }921922      if (!jv_is_valid(top)) {923        if (jv_invalid_has_msg(jv_copy(top)))924          set_error(jq, top);925        else926          jv_free(top);927        goto do_backtrack;928      }929930      stack_push(jq, top);931      break;932    }933934    case TAIL_CALL_JQ:935    case CALL_JQ: {936      /*937       * Bytecode layout here:938       *939       *  CALL_JQ940       *  <nclosures>                       (i.e., number of call arguments)941       *  <callee closure>                  (what we're calling)942       *  <nclosures' worth of closures>    (frame reference + code pointer)943       *944       *  <next instruction (to return to)>945       *946       * Each closure consists of two uint16_t values: a "level"947       * identifying the frame to be closed over, and an index.948       *949       * The level is a relative number of call frames reachable from950       * the currently one; 0 -> current frame, 1 -> previous frame, and951       * so on.952       *953       * The index is either an index of the closed frame's subfunctions954       * or of the closed frame's parameter closures.  If the latter,955       * that closure will be passed, else the closed frame's pointer956       * and the subfunction's code will form the closure to be passed.957       *958       * See make_closure() for more information.959       */960      jv input = stack_pop(jq);961      uint16_t nclosures = *pc++;962      uint16_t* retaddr = pc + 2 + nclosures*2;963      stack_ptr retdata = jq->stk_top;964      struct frame* new_frame;965      struct closure cl = make_closure(jq, pc);966      if (opcode == TAIL_CALL_JQ) {967        retaddr = frame_current(jq)->retaddr;968        retdata = frame_current(jq)->retdata;969        frame_pop(jq);970      }971      new_frame = frame_push(jq, cl, pc + 2, nclosures);972      new_frame->retdata = retdata;973      new_frame->retaddr = retaddr;974      pc = new_frame->bc->code;975      stack_push(jq, input);976      break;977    }978979    case RET: {980      jv value = stack_pop(jq);981      assert(jq->stk_top == frame_current(jq)->retdata);982      uint16_t* retaddr = frame_current(jq)->retaddr;983      if (retaddr) {984        // function return985        pc = retaddr;986        frame_pop(jq);987      } else {988        // top-level return, yielding value989        struct stack_pos spos = stack_get_pos(jq);990        stack_push(jq, jv_null());991        stack_save(jq, pc - 1, spos);992        return value;993      }994      stack_push(jq, value);995      break;996    }997    case ON_BACKTRACK(RET): {998      // resumed after top-level return999      goto do_backtrack;1000    }1001    }1002  }1003}10041005jv jq_format_error(jv msg) {1006  if (jv_get_kind(msg) == JV_KIND_NULL ||1007      (jv_get_kind(msg) == JV_KIND_INVALID && !jv_invalid_has_msg(jv_copy(msg)))) {1008    jv_free(msg);1009    fprintf(stderr, "jq: error: out of memory\n");1010    return jv_null();1011  }10121013  if (jv_get_kind(msg) == JV_KIND_STRING)1014    return msg;                         // expected to already be formatted10151016  if (jv_get_kind(msg) == JV_KIND_INVALID)1017    msg = jv_invalid_get_msg(msg);10181019  if (jv_get_kind(msg) == JV_KIND_NULL)1020    return jq_format_error(msg);        // ENOMEM10211022  // Invalid with msg; prefix with "jq: error: "10231024  if (jv_get_kind(msg) != JV_KIND_INVALID) {1025    if (jv_get_kind(msg) == JV_KIND_STRING) {1026      jv r = jv_string_fmt("jq: error: %s", jv_string_value(msg));1027      jv_free(msg);1028      return r;1029    }10301031    msg = jv_dump_string(msg, JV_PRINT_INVALID);1032    if (jv_get_kind(msg) == JV_KIND_STRING) {1033      jv r = jv_string_fmt("jq: error: %s", jv_string_value(msg));1034      jv_free(msg);1035      return r;1036    }1037    jv_free(msg);1038    return jq_format_error(jv_null());  // ENOMEM1039  }10401041  // An invalid inside an invalid!1042  return jq_format_error(jv_invalid_get_msg(msg));1043}10441045// XXX Refactor into a utility function that returns a jv and one that1046// uses it and then prints that jv's string as the complete error1047// message.1048static void default_err_cb(void *data, jv msg) {1049  msg = jq_format_error(msg);1050  fprintf((FILE *)data, "%s\n", jv_string_value(msg));1051  jv_free(msg);1052}10531054jq_state *jq_init(void) {1055  jq_state *jq;1056  jq = jv_mem_alloc_unguarded(sizeof(*jq));1057  if (jq == NULL)1058    return NULL;10591060  jq->bc = 0;1061  jq->next_label = 0;10621063  stack_init(&jq->stk);1064  jq->stk_top = 0;1065  jq->fork_top = 0;1066  jq->curr_frame = 0;1067  jq->error = jv_null();10681069  jq->halted = 0;1070  jq->exit_code = jv_invalid();1071  jq->error_message = jv_invalid();10721073  jq->input_cb = NULL;1074  jq->input_cb_data = NULL;10751076  jq->debug_cb = NULL;1077  jq->debug_cb_data = NULL;10781079  jq->stderr_cb = NULL;1080  jq->stderr_cb_data = NULL;10811082  jq->err_cb = default_err_cb;1083  jq->err_cb_data = stderr;10841085  jq->attrs = jv_object();1086  jq->path = jv_null();1087  jq->value_at_path = jv_null();10881089  jq->nomem_handler = NULL;1090  jq->nomem_handler_data = NULL;1091  return jq;1092}10931094void jq_set_error_cb(jq_state *jq, jq_msg_cb cb, void *data) {1095  if (cb == NULL) {1096    jq->err_cb = default_err_cb;1097    jq->err_cb_data = stderr;1098  } else {1099    jq->err_cb = cb;1100    jq->err_cb_data = data;1101  }1102}11031104void jq_get_error_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1105  *cb = jq->err_cb;1106  *data = jq->err_cb_data;1107}11081109void jq_set_nomem_handler(jq_state *jq, void (*nomem_handler)(void *), void *data) {1110  jv_nomem_handler(nomem_handler, data);1111  jq->nomem_handler = nomem_handler;1112  jq->nomem_handler_data = data;1113}111411151116void jq_start(jq_state *jq, jv input, int flags) {1117  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1118  jq_reset(jq);11191120  struct closure top = {jq->bc, -1};1121  struct frame* top_frame = frame_push(jq, top, 0, 0);1122  top_frame->retdata = 0;1123  top_frame->retaddr = 0;11241125  stack_push(jq, input);1126  stack_save(jq, jq->bc->code, stack_get_pos(jq));1127  jq->debug_trace_enabled = flags & JQ_DEBUG_TRACE_ALL;1128  jq->initial_execution = 1;1129}11301131void jq_teardown(jq_state **jq) {1132  jq_state *old_jq = *jq;1133  if (old_jq == NULL)1134    return;1135  *jq = NULL;11361137  jq_reset(old_jq);1138  bytecode_free(old_jq->bc);1139  old_jq->bc = 0;1140  jv_free(old_jq->attrs);11411142  jv_mem_free(old_jq);1143}11441145static int ret_follows(uint16_t *pc) {1146  if (*pc == RET)1147    return 1;1148  if (*pc++ != JUMP)1149    return 0;1150  return ret_follows(pc + *pc + 1); // FIXME, might be ironic1151}11521153/*1154 * Look for tail calls that can be optimized: tail calls with no1155 * references left to the current frame.1156 *1157 * We're staring at this bytecode layout:1158 *1159 *   CALL_JQ1160 *   <nclosures>1161 *   <callee closure>       (2 units)1162 *   <nclosures closures>   (2 units each)1163 *   <next instruction>1164 *1165 * A closure is:1166 *1167 *   <level>    (a relative frame count chased via the current frame's env)1168 *   <index>    (an index of a subfunction or closure in that frame)1169 *1170 * We're looking for:1171 *1172 * a) the next instruction is a RET or a chain of unconditional JUMPs1173 * that ends in a RET, and1174 *1175 * b) none of the closures -callee included- have level == 0.1176 */1177static uint16_t tail_call_analyze(uint16_t *pc) {1178  assert(*pc == CALL_JQ);1179  pc++;1180  // + 1 for the callee closure1181  for (uint16_t nclosures = *pc++ + 1; nclosures > 0; pc++, nclosures--) {1182    if (*pc++ == 0)1183      return CALL_JQ;1184  }1185  if (ret_follows(pc))1186    return TAIL_CALL_JQ;1187  return CALL_JQ;1188}11891190static struct bytecode *optimize_code(struct bytecode *bc) {1191  uint16_t *pc = bc->code;1192  // FIXME: Don't mutate bc->code...1193  while (pc < bc->code + bc->codelen) {1194    switch (*pc) {1195    case CALL_JQ:1196      *pc = tail_call_analyze(pc);1197      break;11981199    // Other bytecode optimizations here.  A peephole optimizer would1200    // fit right in.1201    default: break;1202    }1203    pc += bytecode_operation_length(pc);1204  }1205  return bc;1206}12071208static struct bytecode *optimize(struct bytecode *bc) {1209  for (int i=0; i<bc->nsubfunctions; i++) {1210    bc->subfunctions[i] = optimize(bc->subfunctions[i]);1211  }1212  return optimize_code(bc);1213}12141215static jv1216args2obj(jv args)1217{1218  if (jv_get_kind(args) == JV_KIND_OBJECT)1219    return args;1220  assert(jv_get_kind(args) == JV_KIND_ARRAY);1221  jv r = jv_object();1222  jv kk = jv_string("name");1223  jv vk = jv_string("value");1224  jv_array_foreach(args, i, v)1225    r = jv_object_set(r, jv_object_get(jv_copy(v), kk), jv_object_get(v, vk));1226  jv_free(args);1227  jv_free(kk);1228  jv_free(vk);1229  return r;1230}12311232int jq_compile_args(jq_state *jq, const char* str, jv args) {1233  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1234  assert(jv_get_kind(args) == JV_KIND_ARRAY || jv_get_kind(args) == JV_KIND_OBJECT);1235  struct locfile* locations;1236  locations = locfile_init(jq, "<top-level>", str, strlen(str));1237  block program;1238  jq_reset(jq);1239  if (jq->bc) {1240    bytecode_free(jq->bc);1241    jq->bc = 0;1242  }1243  int nerrors = load_program(jq, locations, &program);1244  if (nerrors == 0) {1245    nerrors = builtins_bind(jq, &program);1246    if (nerrors == 0)1247      nerrors = block_compile(program, &jq->bc, locations, args2obj(args));1248    else1249      jv_free(args);1250  } else1251    jv_free(args);1252  if (nerrors)1253    jq_report_error(jq, jv_string_fmt("jq: %d compile %s", nerrors, nerrors > 1 ? "errors" : "error"));1254  if (jq->bc)1255    jq->bc = optimize(jq->bc);1256  locfile_free(locations);1257  return jq->bc != NULL;1258}12591260int jq_compile(jq_state *jq, const char* str) {1261  return jq_compile_args(jq, str, jv_object());1262}12631264jv jq_get_jq_origin(jq_state *jq) {1265  return jq_get_attr(jq, jv_string("JQ_ORIGIN"));1266}12671268jv jq_get_prog_origin(jq_state *jq) {1269  return jq_get_attr(jq, jv_string("PROGRAM_ORIGIN"));1270}12711272jv jq_get_lib_dirs(jq_state *jq) {1273  jv lib_dirs = jq_get_attr(jq, jv_string("JQ_LIBRARY_PATH"));1274  return jv_is_valid(lib_dirs) ? lib_dirs : jv_array();1275}12761277void jq_set_attrs(jq_state *jq, jv attrs) {1278  assert(jv_get_kind(attrs) == JV_KIND_OBJECT);1279  jv_free(jq->attrs);1280  jq->attrs = attrs;1281}12821283void jq_set_attr(jq_state *jq, jv attr, jv val) {1284  jq->attrs = jv_object_set(jq->attrs, attr, val);1285}12861287jv jq_get_attr(jq_state *jq, jv attr) {1288  return jv_object_get(jv_copy(jq->attrs), attr);1289}12901291void jq_dump_disassembly(jq_state *jq, int indent) {1292  dump_disassembly(indent, jq->bc);1293}12941295void jq_set_input_cb(jq_state *jq, jq_input_cb cb, void *data) {1296  jq->input_cb = cb;1297  jq->input_cb_data = data;1298}12991300void jq_get_input_cb(jq_state *jq, jq_input_cb *cb, void **data) {1301  *cb = jq->input_cb;1302  *data = jq->input_cb_data;1303}13041305void jq_set_debug_cb(jq_state *jq, jq_msg_cb cb, void *data) {1306  jq->debug_cb = cb;1307  jq->debug_cb_data = data;1308}13091310void jq_get_debug_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1311  *cb = jq->debug_cb;1312  *data = jq->debug_cb_data;1313}13141315void jq_set_stderr_cb(jq_state *jq, jq_msg_cb cb, void *data) {1316  jq->stderr_cb = cb;1317  jq->stderr_cb_data = data;1318}13191320void jq_get_stderr_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1321  *cb = jq->stderr_cb;1322  *data = jq->stderr_cb_data;1323}13241325void1326jq_halt(jq_state *jq, jv exit_code, jv error_message)1327{1328  assert(!jq->halted);1329  jq->halted = 1;1330  jq->exit_code = exit_code;1331  jq->error_message = error_message;1332}13331334int1335jq_halted(jq_state *jq)1336{1337  return jq->halted;1338}13391340jv jq_get_exit_code(jq_state *jq)1341{1342  return jv_copy(jq->exit_code);1343}13441345jv jq_get_error_message(jq_state *jq)1346{1347  return jv_copy(jq->error_message);1348}