Skip to content
Myr

linker.c

This file

Path

src/linker.c

484 lines · 16.7 KiB · C

Last changed by

Register imported libraries in dependency order (#3620)itchynybefore adoption12cdd95

History of this file

Take it

1#include <assert.h>2#include <errno.h>3#include <limits.h>4#include <string.h>5#include <stdio.h>6#include <stdlib.h>7#include <stdint.h>8#include <sys/stat.h>9#include <libgen.h>1011#ifdef WIN3212#include <shlwapi.h>13#endif1415#include "jq_parser.h"16#include "locfile.h"17#include "jv.h"18#include "jq.h"19#include "util.h"20#include "compile.h"21#include "jv_alloc.h"2223struct lib_entry {24  char *name;25  block def;26};27struct loading_lib {28  const char *name;29  struct loading_lib *next;30};31struct lib_loading_state {32  struct lib_entry *entries;33  uint64_t ct;34  struct loading_lib *loading;35};36static int load_library(jq_state *jq, jv lib_path,37                        int is_data, int raw, int optional,38                        const char *as, block *out_block,39                        struct lib_loading_state *lib_state);4041static int path_is_relative(jv p) {42  const char *s = jv_string_value(p);4344#ifdef WIN3245  int res = PathIsRelativeA(s);46#else47  int res = *s != '/';48#endif49  jv_free(p);50  return res;51}525354// Given a lib_path to search first, creates a chain of search paths55// in the following order:56// 1. lib_path57// 2. -L paths passed in on the command line (from jq_state*) or builtin list58static jv build_lib_search_chain(jq_state *jq, jv search_path, jv jq_origin, jv lib_origin) {59  assert(jv_get_kind(search_path) == JV_KIND_ARRAY);60  jv expanded = jv_array();61  jv expanded_elt;62  jv err = jv_null();63  jv_array_foreach(search_path, i, path) {64    if (jv_get_kind(path) != JV_KIND_STRING) {65      jv_free(path);66      continue;67    }68    path = expand_path(path);69    if (!jv_is_valid(path)) {70      jv_free(err);71      err = path;72      path = jv_null();73      continue;74    }75    if (strcmp(".",jv_string_value(path)) == 0) {76      expanded_elt = jv_copy(path);77    } else if (strncmp("$ORIGIN/",jv_string_value(path),sizeof("$ORIGIN/") - 1) == 0) {78      expanded_elt = jv_string_fmt("%s/%s",79                               jv_string_value(jq_origin),80                               jv_string_value(path) + sizeof ("$ORIGIN/") - 1);81    } else if (jv_get_kind(lib_origin) == JV_KIND_STRING &&82               path_is_relative(jv_copy(path))) {83      expanded_elt = jv_string_fmt("%s/%s",84                               jv_string_value(lib_origin),85                               jv_string_value(path));86    } else {87      expanded_elt = path;88      path = jv_invalid();89    }90    expanded = jv_array_append(expanded, expanded_elt);91    jv_free(path);92  }93  jv_free(jq_origin);94  jv_free(lib_origin);95  jv_free(search_path);96  return JV_ARRAY(expanded, err);97}9899// Doesn't actually check that name not be an absolute path, and we100// don't have to: we always append relative paths to others (with a '/'101// in between).102static jv validate_relpath(jv name) {103  const char *s = jv_string_value(name);104  if (strlen(s) != (size_t)jv_string_length_bytes(jv_copy(name))) {105    jv_free(name);106    return jv_invalid_with_msg(jv_string("Module path contains a NUL byte"));107  }108  if (strchr(s, '\\')) {109    jv res = jv_invalid_with_msg(jv_string_fmt("Modules must be named by relative paths using '/', not '\\' (%s)", s));110    jv_free(name);111    return res;112  }113  jv components = jv_string_split(jv_copy(name), jv_string("/"));114  jv_array_foreach(components, i, x) {115    if (!strcmp(jv_string_value(x), "..")) {116      jv_free(x);117      jv_free(components);118      jv res = jv_invalid_with_msg(jv_string_fmt("Relative paths to modules may not traverse to parent directories (%s)", s));119      jv_free(name);120      return res;121    }122    if (i > 0 && jv_equal(jv_copy(x), jv_array_get(jv_copy(components), i - 1))) {123      jv_free(x);124      jv_free(components);125      jv res = jv_invalid_with_msg(jv_string_fmt("module names must not have equal consecutive components: %s",126                                                 jv_string_value(name)));127      jv_free(name);128      return res;129    }130    jv_free(x);131  }132  jv_free(components);133  return name;134}135136// Assumes name has been validated137static jv jv_basename(jv name) {138  const char *s = jv_string_value(name);139  const char *p = strrchr(s, '/');140  if (!p)141    return name;142  jv res = jv_string_fmt("%s", p);143  jv_free(name);144  return res;145}146147// Asummes validated relative path to module148static jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {149  if (!jv_is_valid(rel_path)) {150    jv_free(search);151    jv_free(jq_origin);152    jv_free(lib_origin);153    return rel_path;154  }155  if (jv_get_kind(rel_path) != JV_KIND_STRING) {156    jv_free(rel_path);157    jv_free(search);158    jv_free(jq_origin);159    jv_free(lib_origin);160    return jv_invalid_with_msg(jv_string_fmt("Module path must be a string"));161  }162  if (jv_get_kind(search) != JV_KIND_ARRAY) {163    jv_free(rel_path);164    jv_free(search);165    jv_free(jq_origin);166    jv_free(lib_origin);167    return jv_invalid_with_msg(jv_string_fmt("Module search path must be an array"));168  }169170  struct stat st;171  int ret;172173  // Ideally we should cache this somewhere174  search = build_lib_search_chain(jq, search, jq_origin, lib_origin);175  jv err = jv_array_get(jv_copy(search), 1);176  search = jv_array_get(search, 0);177178  jv bname = jv_basename(jv_copy(rel_path));179180  jv_array_foreach(search, i, spath) {181    if (jv_get_kind(spath) == JV_KIND_NULL) {182      jv_free(spath);183      break;184    }185    if (jv_get_kind(spath) != JV_KIND_STRING ||186        strcmp(jv_string_value(spath), "") == 0) {187      jv_free(spath);188      continue; /* XXX report non-strings in search path?? */189    }190    // Try ${search_dir}/${rel_path}.jq191    jv testpath = jq_realpath(jv_string_fmt("%s/%s%s",192                                            jv_string_value(spath),193                                            jv_string_value(rel_path),194                                            suffix));195    ret = stat(jv_string_value(testpath),&st);196    if (ret == -1 && errno == ENOENT) {197      jv_free(testpath);198      // Try ${search_dir}/$(dirname ${rel_path})/jq/main.jq199      testpath = jq_realpath(jv_string_fmt("%s/%s/%s%s",200                                           jv_string_value(spath),201                                           jv_string_value(rel_path),202                                           "jq/main",203                                           suffix));204      ret = stat(jv_string_value(testpath),&st);205    }206    if (ret == -1 && errno == ENOENT) {207      jv_free(testpath);208      // Try ${search_dir}/${rel_path}/$(basename ${rel_path}).jq209      testpath = jq_realpath(jv_string_fmt("%s/%s/%s%s",210                                           jv_string_value(spath),211                                           jv_string_value(rel_path),212                                           jv_string_value(bname),213                                           suffix));214      ret = stat(jv_string_value(testpath),&st);215    }216    if (ret == 0) {217      jv_free(err);218      jv_free(rel_path);219      jv_free(search);220      jv_free(bname);221      jv_free(spath);222      return testpath;223    }224    jv_free(testpath);225    jv_free(spath);226  }227  jv output;228  if (!jv_is_valid(err)) {229    err = jv_invalid_get_msg(err);230    output = jv_invalid_with_msg(jv_string_fmt("module not found: %s (%s)",231                                               jv_string_value(rel_path),232                                               jv_string_value(err)));233  } else {234    output = jv_invalid_with_msg(jv_string_fmt("module not found: %s",235                                               jv_string_value(rel_path)));236  }237  jv_free(err);238  jv_free(rel_path);239  jv_free(search);240  jv_free(bname);241  return output;242}243244static jv default_search(jq_state *jq, jv value) {245  if (!jv_is_valid(value)) {246    // dependent didn't say; prepend . to system search path listj247    jv_free(value);248    return jv_array_concat(JV_ARRAY(jv_string(".")), jq_get_lib_dirs(jq));249  }250  if (jv_get_kind(value) != JV_KIND_ARRAY)251    return JV_ARRAY(value);252  return value;253}254255// XXX Split this into a util that takes a callback, and then...256static int process_dependencies(jq_state *jq, jv jq_origin, jv lib_origin, block *src_block, struct lib_loading_state *lib_state) {257  jv deps = block_take_imports(src_block);258  block bk = *src_block;259  int nerrors = 0;260261  // XXX This is a backward jv_array_foreach because bindings go in reverse262  for (int i = jv_array_length(jv_copy(deps)); i > 0; ) {263    i--;264    jv dep = jv_array_get(jv_copy(deps), i);265266    const char *as_str = NULL;267    int is_data = jv_get_kind(jv_object_get(jv_copy(dep), jv_string("is_data"))) == JV_KIND_TRUE;268    int raw = 0;269    jv v = jv_object_get(jv_copy(dep), jv_string("raw"));270    if (jv_get_kind(v) == JV_KIND_TRUE)271      raw = 1;272    int optional = 0;273    if (jv_get_kind(jv_object_get(jv_copy(dep), jv_string("optional"))) == JV_KIND_TRUE)274      optional = 1;275    jv_free(v);276    jv relpath = validate_relpath(jv_object_get(jv_copy(dep), jv_string("relpath")));277    jv as = jv_object_get(jv_copy(dep), jv_string("as"));278    assert(!jv_is_valid(as) || jv_get_kind(as) == JV_KIND_STRING);279    if (jv_get_kind(as) == JV_KIND_STRING)280      as_str = jv_string_value(as);281    jv search = default_search(jq, jv_object_get(dep, jv_string("search")));282    // dep is now freed; do not reuse283284    // find_lib does a lot of work that could be cached...285    jv resolved = find_lib(jq, relpath, search, is_data ? ".json" : ".jq", jv_copy(jq_origin), jv_copy(lib_origin));286    // XXX ...move the rest of this into a callback.287    if (!jv_is_valid(resolved)) {288      jv_free(as);289      if (optional) {290        jv_free(resolved);291        continue;292      }293      jv emsg = jv_invalid_get_msg(resolved);294      jq_report_error(jq, jv_string_fmt("jq: error: %s\n",jv_string_value(emsg)));295      jv_free(emsg);296      jv_free(deps);297      jv_free(jq_origin);298      jv_free(lib_origin);299      return 1;300    }301302    if (is_data) {303      // Can't reuse data libs because the wrong name is bound304      block dep_def_block;305      nerrors += load_library(jq, resolved, is_data, raw, optional, as_str, &dep_def_block, lib_state);306      if (nerrors == 0) {307        // Bind as both $data::data and $data for backward compatibility vs common sense308        bk = block_bind_library(dep_def_block, bk, OP_IS_CALL_PSEUDO, as_str);309        bk = block_bind_library(dep_def_block, bk, OP_IS_CALL_PSEUDO, NULL);310      }311    } else {312      uint64_t state_idx = 0;313      for (; state_idx < lib_state->ct; ++state_idx) {314        if (strcmp(lib_state->entries[state_idx].name, jv_string_value(resolved)) == 0)315          break;316      }317318      if (state_idx < lib_state->ct) { // Found319        jv_free(resolved);320        // Bind the library to the program321        bk = block_bind_library(lib_state->entries[state_idx].def, bk, OP_IS_CALL_PSEUDO, as_str);322      } else { // Not found.   Add it to the table before binding.323        block dep_def_block = gen_noop();324        nerrors += load_library(jq, resolved, is_data, raw, optional, as_str, &dep_def_block, lib_state);325        // resolved has been freed326        if (nerrors == 0) {327          // Bind the library to the program328          bk = block_bind_library(dep_def_block, bk, OP_IS_CALL_PSEUDO, as_str);329        }330      }331    }332333    jv_free(as);334  }335  jv_free(lib_origin);336  jv_free(jq_origin);337  jv_free(deps);338  return nerrors;339}340341// Loads the library at lib_path into lib_state, putting the library's defs342// into *out_block343static int load_library(jq_state *jq, jv lib_path, int is_data, int raw, int optional, const char *as, block *out_block, struct lib_loading_state *lib_state) {344  int nerrors = 0;345  struct locfile* src = NULL;346  block program;347  jv data;348  for (struct loading_lib *l = lib_state->loading; l; l = l->next) {349    if (strcmp(l->name, jv_string_value(lib_path)) == 0) {350      jq_report_error(jq, jv_string_fmt("jq: error: circular import of %s\n",351                                        jv_string_value(lib_path)));352      *out_block = gen_noop();353      jv_free(lib_path);354      return 1;355    }356  }357  if (is_data && !raw)358    data = jv_load_file(jv_string_value(lib_path), 0);359  else360    data = jv_load_file(jv_string_value(lib_path), 1);361  uint64_t state_idx;362  if (!jv_is_valid(data)) {363    program = gen_noop();364    if (!optional) {365      if (jv_invalid_has_msg(jv_copy(data)))366        data = jv_invalid_get_msg(data);367      else368        data = jv_string("unknown error");369      jq_report_error(jq, jv_string_fmt("jq: error loading data file %s: %s\n", jv_string_value(lib_path), jv_string_value(data)));370      nerrors++;371    }372  } else if (is_data) {373    // import "foo" as $bar;374    program = gen_const_global(jv_copy(data), as);375    state_idx = lib_state->ct++;376    lib_state->entries = jv_mem_realloc(lib_state->entries, lib_state->ct * sizeof(struct lib_entry));377    lib_state->entries[state_idx].name = strdup(jv_string_value(lib_path));378    lib_state->entries[state_idx].def = program;379  } else {380    // import "foo" as bar;381    src = locfile_init(jq, jv_string_value(lib_path), jv_string_value(data), jv_string_length_bytes(jv_copy(data)));382    nerrors += jq_parse_library(src, &program);383    locfile_free(src);384    if (nerrors == 0) {385      // Mark the library as being loaded while its dependencies are processed,386      // so that a recursive reference to it is reported as a circular import.387      // The node lives on this frame and is popped before lib_path is freed,388      // so it can borrow the path string.389      struct loading_lib loading = { jv_string_value(lib_path), lib_state->loading };390      lib_state->loading = &loading;391      char *lib_origin = strdup(jv_string_value(lib_path));392      nerrors += process_dependencies(jq, jq_get_jq_origin(jq),393                                      jv_string(dirname(lib_origin)),394                                      &program, lib_state);395      free(lib_origin);396      lib_state->loading = loading.next;397      program = block_bind_self(program, OP_IS_CALL_PSEUDO);398      // Register the library only once its dependencies have been processed,399      // to keep lib_state->entries in dependency order.  Register it even when400      // its dependencies failed, so that other importers reuse this entry401      // rather than loading and diagnosing the same library again.402      state_idx = lib_state->ct++;403      lib_state->entries = jv_mem_realloc(lib_state->entries, lib_state->ct * sizeof(struct lib_entry));404      lib_state->entries[state_idx].name = strdup(jv_string_value(lib_path));405      lib_state->entries[state_idx].def = program;406    }407  }408  *out_block = program;409  jv_free(lib_path);410  jv_free(data);411  return nerrors;412}413414// FIXME It'd be nice to have an option to search the same search path415// as we do in process_dependencies.416jv load_module_meta(jq_state *jq, jv mod_relpath) {417  // We can't know the caller's origin; we could though, if it was passed in418  jv lib_path = find_lib(jq, validate_relpath(mod_relpath), jq_get_lib_dirs(jq), ".jq", jq_get_jq_origin(jq), jv_null());419  if (!jv_is_valid(lib_path))420    return lib_path;421  jv meta = jv_null();422  jv data = jv_load_file(jv_string_value(lib_path), 1);423  if (jv_is_valid(data)) {424    block program;425    struct locfile* src = locfile_init(jq, jv_string_value(lib_path), jv_string_value(data), jv_string_length_bytes(jv_copy(data)));426    int nerrors = jq_parse_library(src, &program);427    if (nerrors == 0) {428      meta = block_module_meta(program);429      if (jv_get_kind(meta) == JV_KIND_NULL)430        meta = jv_object();431      meta = jv_object_set(meta, jv_string("deps"), block_take_imports(&program));432      meta = jv_object_set(meta, jv_string("defs"), block_list_funcs(program, 0));433    }434    locfile_free(src);435    block_free(program);436  }437  jv_free(lib_path);438  jv_free(data);439  return meta;440}441442int load_program(jq_state *jq, struct locfile* src, block *out_block) {443  int nerrors = 0;444  block program;445  struct lib_loading_state lib_state = {0,0,0};446  nerrors = jq_parse(src, &program);447  if (nerrors)448    return nerrors;449450  if (!block_has_main(program)) {451    jq_report_error(jq, jv_string("jq: error: Top-level program not given (try \".\")"));452    block_free(program);453    return 1;454  }455456  jv home = get_home();457  if (jv_is_valid(home)) {458    /* Import ~/.jq as a library named "" found in $HOME or %USERPROFILE% */459    block import = gen_import_meta(gen_import(jv_string(""), jv_invalid(), 0),460        gen_const(JV_OBJECT(461            jv_string("optional"), jv_true(),462            jv_string("search"), home)));463    program = BLOCK(import, program);464  } else {    // silently ignore if home dir not determined465    jv_free(home);466  }467468  nerrors = process_dependencies(jq, jq_get_jq_origin(jq), jq_get_prog_origin(jq), &program, &lib_state);469  block libs = gen_noop();470  for (uint64_t i = 0; i < lib_state.ct; ++i) {471    free(lib_state.entries[i].name);472    if (nerrors == 0 && !block_is_const(lib_state.entries[i].def))473      libs = block_join(libs, lib_state.entries[i].def);474    else475      block_free(lib_state.entries[i].def);476  }477  free(lib_state.entries);478  if (nerrors)479    block_free(program);480  else481    *out_block = block_drop_unreferenced(block_join(libs, program));482483  return nerrors;484}