Skip to content
Myr

main.c

This file

Path

src/main.c

734 lines · 26.6 KiB · C

Last changed by

Exit with the given status for negative `halt_error` codes (#3660)qodeliciousbefore adoption0404249

History of this file

Take it

1#include <assert.h>2#include <ctype.h>3#include <errno.h>4#include <libgen.h>5#ifdef HAVE_SETLOCALE6#include <locale.h>7#endif8#include <stdlib.h>9#include <stdio.h>10#include <string.h>11#include <unistd.h>1213#ifdef WIN3214#include <windows.h>15#include <io.h>16#include <fcntl.h>17#include <processenv.h>18#include <shellapi.h>19#include <wchar.h>20#include <wtypes.h>21extern void jv_tsd_dtoa_ctx_init();22#endif2324#ifdef HAVE_LIBONIG25#include <oniguruma.h>26#endif2728#if !defined(HAVE_ISATTY) && defined(HAVE__ISATTY)29#undef isatty30#define isatty _isatty31#endif3233#if defined(HAVE_ISATTY) || defined(HAVE__ISATTY)34#define USE_ISATTY35#endif3637#include "jv.h"38#include "jq.h"39#include "util.h"40#include "src/version.h"41#include "src/config_opts.inc"4243int jq_testsuite(jv lib_dirs, int verbose, int argc, char* argv[]);4445/*46 * For a longer help message we could use a better option parsing47 * strategy, one that lets stack options.48 */49static void usage(int code, int keep_it_short) {50  FILE *f = stderr;5152  if (code == 0)53    f = stdout;5455  int ret = fprintf(f,56    "jq - commandline JSON processor [version %s]\n"57    "\nUsage:\tjq [options] <jq filter> [file...]\n"58    "\tjq [options] --args <jq filter> [strings...]\n"59    "\tjq [options] --jsonargs <jq filter> [JSON_TEXTS...]\n\n"60    "jq is a tool for processing JSON inputs, applying the given filter to\n"61    "its JSON text inputs and producing the filter's results as JSON on\n"62    "standard output.\n\n"63    "The simplest filter is ., which copies jq's input to its output\n"64    "unmodified except for formatting. For more advanced filters see\n"65    "the jq(1) manpage (\"man jq\") and/or https://jqlang.org/.\n\n"66    "Example:\n\n\t$ echo '{\"foo\": 0}' | jq .\n"67    "\t{\n\t  \"foo\": 0\n\t}\n\n", JQ_VERSION);68  if (keep_it_short) {69    fprintf(f, "For listing the command options, use jq --help.\n");70  } else {71    (void) fprintf(f,72      "Command options:\n"73      "  -n, --null-input          use `null` as the single input value;\n"74      "  -R, --raw-input           read each line as string instead of JSON;\n"75      "  -s, --slurp               read all inputs into an array and use it as\n"76      "                            the single input value;\n"77      "  -c, --compact-output      compact instead of pretty-printed output;\n"78      "  -r, --raw-output          output strings without escapes and quotes;\n"79      "      --raw-output0         implies -r and output NUL after each output;\n"80      "  -j, --join-output         implies -r and output without newline after\n"81      "                            each output;\n"82      "  -a, --ascii-output        output strings by only ASCII characters\n"83      "                            using escape sequences;\n"84      "  -S, --sort-keys           sort keys of each object on output;\n"85      "  -C, --color-output        colorize JSON output;\n"86      "  -M, --monochrome-output   disable colored output;\n"87      "      --tab                 use tabs for indentation;\n"88      "      --indent n            use n spaces for indentation (max 7 spaces);\n"89      "      --unbuffered          flush output stream after each output;\n"90      "      --stream              parse the input value in streaming fashion;\n"91      "      --stream-errors       implies --stream and report parse error as\n"92      "                            an array;\n"93      "      --seq                 parse input/output as application/json-seq;\n"94      "  -f, --from-file           load the filter from a file;\n"95      "  -L, --library-path dir    search modules from the directory;\n"96      "      --arg name value      set $name to the string value;\n"97      "      --argjson name value  set $name to the JSON value;\n"98      "      --slurpfile name file set $name to an array of JSON values read\n"99      "                            from the file;\n"100      "      --rawfile name file   set $name to string contents of file;\n"101      "      --args                consume remaining arguments as positional\n"102      "                            string values;\n"103      "      --jsonargs            consume remaining arguments as positional\n"104      "                            JSON values;\n"105      "  -e, --exit-status         set exit status code based on the output;\n"106#ifdef WIN32107      "  -b, --binary              open input/output streams in binary mode;\n"108#endif109      "  -V, --version             show the version;\n"110      "  --build-configuration     show jq's build configuration;\n"111      "  -h, --help                show the help;\n"112      "  --                        terminates argument processing;\n\n"113      "Named arguments are also available as $ARGS.named[], while\n"114      "positional arguments are available as $ARGS.positional[].\n");115  }116  exit((ret < 0 && code == 0) ? 2 : code);117}118119static void die(void) {120  fprintf(stderr, "Use jq --help for help with command-line options,\n");121  fprintf(stderr, "or see the jq manpage, or online docs at https://jqlang.org\n");122  exit(2);123}124125static int isoptish(const char* text) {126  return text[0] == '-' && (text[1] == '-' || isalpha((unsigned char)text[1]));127}128129static int isoption(const char** text, char shortopt, const char* longopt, int is_short) {130  if (is_short) {131    if (shortopt && **text == shortopt) {132      (*text)++;133      if (!**text) *text = NULL;134      return 1;135    }136  } else {137    if (!strcmp(*text, longopt)) {138      *text = NULL;139      return 1;140    }141  }142  return 0;143}144145enum {146  SLURP                 = 1,147  RAW_INPUT             = 2,148  PROVIDE_NULL          = 4,149  RAW_OUTPUT            = 8,150  RAW_OUTPUT0           = 16,151  ASCII_OUTPUT          = 32,152  COLOR_OUTPUT          = 64,153  NO_COLOR_OUTPUT       = 128,154  SORTED_OUTPUT         = 256,155  FROM_FILE             = 512,156  RAW_NO_LF             = 1024,157  UNBUFFERED_OUTPUT     = 2048,158  EXIT_STATUS           = 4096,159  SEQ                   = 16384,160  /* debugging only */161  DUMP_DISASM           = 32768,162};163164enum {165    JQ_OK              =  0,166    JQ_OK_NULL_KIND    = -1, /* exit 0 if --exit-status is not set*/167    JQ_ERROR_SYSTEM    =  2,168    JQ_ERROR_COMPILE   =  3,169    JQ_OK_NO_OUTPUT    = -4, /* exit 0 if --exit-status is not set*/170    JQ_ERROR_UNKNOWN   =  5,171};172#define jq_exit_with_status(r)  exit(abs(r))173#define jq_exit(r)              exit( r > 0 ? r : 0 )174175static int process(jq_state *jq, jv value, int flags, int dumpopts, int options) {176  int ret = JQ_OK_NO_OUTPUT; // No valid results && -e -> exit(4)177  jq_start(jq, value, flags);178  jv result;179  while (jv_is_valid(result = jq_next(jq))) {180    if ((options & RAW_OUTPUT) && jv_get_kind(result) == JV_KIND_STRING) {181      if (options & ASCII_OUTPUT) {182        jv_dumpf(jv_copy(result), stdout, JV_PRINT_ASCII);183      } else if ((options & RAW_OUTPUT0) && strlen(jv_string_value(result)) != (unsigned long)jv_string_length_bytes(jv_copy(result))) {184        jv_free(result);185        result = jv_invalid_with_msg(jv_string(186              "Cannot dump a string containing NUL with --raw-output0 option"));187        break;188      } else {189        priv_fwrite(jv_string_value(result), jv_string_length_bytes(jv_copy(result)),190            stdout, dumpopts & JV_PRINT_ISATTY);191      }192      ret = JQ_OK;193      jv_free(result);194    } else {195      if (jv_get_kind(result) == JV_KIND_FALSE || jv_get_kind(result) == JV_KIND_NULL)196        ret = JQ_OK_NULL_KIND;197      else198        ret = JQ_OK;199      if (options & SEQ)200        priv_fwrite("\036", 1, stdout, dumpopts & JV_PRINT_ISATTY);201      jv_dump(result, dumpopts);202    }203    if (!(options & RAW_NO_LF))204      priv_fwrite("\n", 1, stdout, dumpopts & JV_PRINT_ISATTY);205    if (options & RAW_OUTPUT0)206      priv_fwrite("\0", 1, stdout, dumpopts & JV_PRINT_ISATTY);207    if (options & UNBUFFERED_OUTPUT)208      fflush(stdout);209  }210  if (jq_halted(jq)) {211    // jq program invoked `halt` or `halt_error`212    jv exit_code = jq_get_exit_code(jq);213    if (!jv_is_valid(exit_code))214      ret = JQ_OK;215    else if (jv_get_kind(exit_code) == JV_KIND_NUMBER) {216      ret = jv_number_value(exit_code);217      // Negative values would be mistaken for JQ_OK_NULL_KIND and friends,218      // so keep the low 8 bits, like exit(3) does on POSIX systems.219      if (ret < 0)220        ret &= 0xff;221    } else222      ret = JQ_ERROR_UNKNOWN;223    jv_free(exit_code);224    jv error_message = jq_get_error_message(jq);225    if (jv_get_kind(error_message) == JV_KIND_STRING) {226      // No prefix should be added to the output of `halt_error`.227      priv_fwrite(jv_string_value(error_message), jv_string_length_bytes(jv_copy(error_message)),228          stderr, dumpopts & JV_PRINT_ISATTY);229    } else if (jv_get_kind(error_message) == JV_KIND_NULL) {230      // Halt with no output231    } else if (jv_is_valid(error_message)) {232      error_message = jv_dump_string(error_message, 0);233      fprintf(stderr, "%s\n", jv_string_value(error_message));234    } // else no message on stderr; use --debug-trace to see a message235    fflush(stderr);236    jv_free(error_message);237  } else if (jv_invalid_has_msg(jv_copy(result))) {238    // Uncaught jq exception239    jv msg = jv_invalid_get_msg(jv_copy(result));240    jv input_pos = jq_util_input_get_position(jq);241    if (jv_get_kind(msg) == JV_KIND_STRING) {242      fprintf(stderr, "jq: error (at %s): %s\n",243              jv_string_value(input_pos), jv_string_value(msg));244    } else {245      msg = jv_dump_string(msg, 0);246      fprintf(stderr, "jq: error (at %s) (not a string): %s\n",247              jv_string_value(input_pos), jv_string_value(msg));248    }249    ret = JQ_ERROR_UNKNOWN;250    jv_free(input_pos);251    jv_free(msg);252  }253  jv_free(result);254  return ret;255}256257static void debug_cb(void *data, jv input) {258  int dumpopts = *(int *)data;259  jv_dumpf(JV_ARRAY(jv_string("DEBUG:"), input), stderr, dumpopts & ~(JV_PRINT_PRETTY));260  fprintf(stderr, "\n");261}262263static void stderr_cb(void *data, jv input) {264  if (jv_get_kind(input) == JV_KIND_STRING) {265    int dumpopts = *(int *)data;266    priv_fwrite(jv_string_value(input), jv_string_length_bytes(jv_copy(input)),267        stderr, dumpopts & JV_PRINT_ISATTY);268  } else {269    input = jv_dump_string(input, 0);270    fprintf(stderr, "%s", jv_string_value(input));271  }272  jv_free(input);273}274275#ifdef WIN32276int umain(int argc, char* argv[]);277278int wmain(int argc, wchar_t* wargv[]) {279  size_t arg_sz;280  char **argv = alloca(argc * sizeof(wchar_t*));281  for (int i = 0; i < argc; i++) {282    argv[i] = alloca((arg_sz = WideCharToMultiByte(CP_UTF8,283                                                   0,284                                                   wargv[i],285                                                   -1, 0, 0, 0, 0)));286    WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], arg_sz, 0, 0);287  }288  return umain(argc, argv);289}290291int umain(int argc, char* argv[]) {292#else /*}*/293int main(int argc, char* argv[]) {294#endif295  jq_state *jq = NULL;296  jq_util_input_state *input_state = NULL;297  int ret = JQ_OK_NO_OUTPUT;298  int compiled = 0;299  int parser_flags = 0;300  int nfiles = 0;301  int last_result = -1; /* -1 = no result, 0=null or false, 1=true */302  int badwrite;303  int options = 0;304305#ifdef HAVE_SETLOCALE306  (void) setlocale(LC_ALL, "");307#endif308309#ifdef HAVE_LIBONIG310  // use a lower regex parse depth limit than the default (4096) to protect311  // from stack-overflows312  // https://github.com/jqlang/jq/security/advisories/GHSA-f946-j5j2-4w5m313  onig_set_parse_depth_limit(1024);314#endif315316#ifdef __OpenBSD__317  if (pledge("stdio rpath", NULL) == -1) {318    perror("pledge");319    exit(JQ_ERROR_SYSTEM);320  }321#endif322323#ifdef WIN32324  jv_tsd_dtoa_ctx_init();325  fflush(stdout);326  fflush(stderr);327  _setmode(fileno(stdout), _O_TEXT | _O_U8TEXT);328  _setmode(fileno(stderr), _O_TEXT | _O_U8TEXT);329#endif330331  jv ARGS = jv_array(); /* positional arguments */332  jv program_arguments = jv_object(); /* named arguments */333334  jq = jq_init();335  if (jq == NULL) {336    perror("jq_init");337    ret = JQ_ERROR_SYSTEM;338    goto out;339  }340341  int dumpopts = JV_PRINT_INDENT_FLAGS(2);342  const char* program = 0;343344  input_state = jq_util_input_init(NULL, NULL); // XXX add err_cb345346  int further_args_are_strings = 0;347  int further_args_are_json = 0;348  int args_done = 0;349  int jq_flags = 0;350  jv lib_search_paths = jv_null();351  for (int i=1; i<argc; i++) {352    if (args_done || !isoptish(argv[i])) {353      if (!program) {354        program = argv[i];355      } else if (further_args_are_strings) {356        ARGS = jv_array_append(ARGS, jv_string(argv[i]));357      } else if (further_args_are_json) {358        jv v =  jv_parse(argv[i]);359        if (!jv_is_valid(v)) {360          fprintf(stderr, "jq: invalid JSON text passed to --jsonargs\n");361          die();362        }363        ARGS = jv_array_append(ARGS, v);364      } else {365        jq_util_input_add_input(input_state, argv[i]);366        nfiles++;367      }368    } else if (!strcmp(argv[i], "--")) {369      args_done = 1;370    } else {371      const char* text = argv[i];372      int is_short;373      // First '-' already checked by isoptish374      if (text[1] == '-') {375        text += 2;376        is_short = 0;377      } else {378        text++;379        is_short = 1;380      }381      int raw; // Temporary for --rawfile382383      // Parse a long option in one iteration or iterate over short options384      while (text != NULL) {385        if (isoption(&text, 's', "slurp", is_short)) {386          options |= SLURP;387        } else if (isoption(&text, 'r', "raw-output", is_short)) {388          options |= RAW_OUTPUT;389        } else if (isoption(&text, 0, "raw-output0", is_short)) {390          options |= RAW_OUTPUT | RAW_NO_LF | RAW_OUTPUT0;391        } else if (isoption(&text, 'j', "join-output", is_short)) {392          options |= RAW_OUTPUT | RAW_NO_LF;393        } else if (isoption(&text, 'c', "compact-output", is_short)) {394          dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7));395        } else if (isoption(&text, 'C', "color-output", is_short)) {396          options |= COLOR_OUTPUT;397        } else if (isoption(&text, 'M', "monochrome-output", is_short)) {398          options |= NO_COLOR_OUTPUT;399        } else if (isoption(&text, 'a', "ascii-output", is_short)) {400          options |= ASCII_OUTPUT;401        } else if (isoption(&text, 0, "unbuffered", is_short)) {402          options |= UNBUFFERED_OUTPUT;403        } else if (isoption(&text, 'S', "sort-keys", is_short)) {404          options |= SORTED_OUTPUT;405        } else if (isoption(&text, 'R', "raw-input", is_short)) {406          options |= RAW_INPUT;407        } else if (isoption(&text, 'n', "null-input", is_short)) {408          options |= PROVIDE_NULL;409        } else if (isoption(&text, 'f', "from-file", is_short)) {410          options |= FROM_FILE;411        } else if (isoption(&text, 'L', "library-path", is_short)) {412          if (jv_get_kind(lib_search_paths) == JV_KIND_NULL)413            lib_search_paths = jv_array();414          if (text != NULL) { // -Lname415            lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(text)));416            text = NULL;417          } else if (i >= argc - 1) {418            fprintf(stderr, "-L takes a parameter: (e.g. -L /search/path or -L/search/path)\n");419            die();420          } else {421            lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(argv[i+1])));422            i++;423          }424        } else if (isoption(&text, 'b', "binary", is_short)) {425#ifdef WIN32426          fflush(stdout);427          fflush(stderr);428          _setmode(fileno(stdin),  _O_BINARY);429          _setmode(fileno(stdout), _O_BINARY);430          _setmode(fileno(stderr), _O_BINARY);431#endif432        } else if (isoption(&text, 0, "tab", is_short)) {433          dumpopts &= ~JV_PRINT_INDENT_FLAGS(7);434          dumpopts |= JV_PRINT_TAB | JV_PRINT_PRETTY;435        } else if (isoption(&text, 0, "indent", is_short)) {436          if (i >= argc - 1) {437            fprintf(stderr, "jq: --indent takes one parameter\n");438            die();439          }440          char* end = NULL;441          errno = 0;442          long indent = strtol(argv[i+1], &end, 10);443          if (errno || indent < -1 || indent > 7 ||444              isspace((unsigned char)*argv[i+1]) || end == argv[i+1] || *end) {445            fprintf(stderr, "jq: --indent takes a number between -1 and 7\n");446            die();447          }448          dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7));449          dumpopts |= JV_PRINT_INDENT_FLAGS(indent);450          i++;451        } else if (isoption(&text, 0, "seq", is_short)) {452          options |= SEQ;453        } else if (isoption(&text, 0, "stream", is_short)) {454          parser_flags |= JV_PARSE_STREAMING;455        } else if (isoption(&text, 0, "stream-errors", is_short)) {456          parser_flags |= JV_PARSE_STREAMING | JV_PARSE_STREAM_ERRORS;457        } else if (isoption(&text, 'e', "exit-status", is_short)) {458          options |= EXIT_STATUS;459        } else if (isoption(&text, 0, "args", is_short)) {460          further_args_are_strings = 1;461          further_args_are_json = 0;462        } else if (isoption(&text, 0, "jsonargs", is_short)) {463          further_args_are_strings = 0;464          further_args_are_json = 1;465        } else if (isoption(&text, 0, "arg", is_short)) {466          if (i >= argc - 2) {467            fprintf(stderr, "jq: --arg takes two parameters (e.g. --arg varname value)\n");468            die();469          }470          if (!jv_object_has(jv_copy(program_arguments), jv_string(argv[i+1])))471            program_arguments = jv_object_set(program_arguments, jv_string(argv[i+1]), jv_string(argv[i+2]));472          i += 2; // skip the next two arguments473        } else if (isoption(&text, 0, "argjson", is_short)) {474          if (i >= argc - 2) {475            fprintf(stderr, "jq: --argjson takes two parameters (e.g. --argjson varname text)\n");476            die();477          }478          if (!jv_object_has(jv_copy(program_arguments), jv_string(argv[i+1]))) {479            jv v = jv_parse(argv[i+2]);480            if (!jv_is_valid(v)) {481              fprintf(stderr, "jq: invalid JSON text passed to --argjson\n");482              die();483            }484            program_arguments = jv_object_set(program_arguments, jv_string(argv[i+1]), v);485          }486          i += 2; // skip the next two arguments487        } else if ((raw = isoption(&text, 0, "rawfile", is_short)) ||488            isoption(&text, 0, "slurpfile", is_short)) {489          const char *which = raw ? "rawfile" : "slurpfile";490          if (i >= argc - 2) {491            fprintf(stderr, "jq: --%s takes two parameters (e.g. --%s varname filename)\n", which, which);492            die();493          }494          if (!jv_object_has(jv_copy(program_arguments), jv_string(argv[i+1]))) {495            jv data = jv_load_file(argv[i+2], raw);496            if (!jv_is_valid(data)) {497              data = jv_invalid_get_msg(data);498              fprintf(stderr, "jq: Bad JSON in --%s %s %s: %s\n", which,499                      argv[i+1], argv[i+2], jv_string_value(data));500              jv_free(data);501              ret = JQ_ERROR_SYSTEM;502              goto out;503            }504            program_arguments = jv_object_set(program_arguments, jv_string(argv[i+1]), data);505          }506          i += 2; // skip the next two arguments507        } else if (isoption(&text,  0,  "debug-dump-disasm", is_short)) {508          options |= DUMP_DISASM;509        } else if (isoption(&text,  0,  "debug-trace=all", is_short)) {510          jq_flags |= JQ_DEBUG_TRACE_ALL;511        } else if (isoption(&text,  0,  "debug-trace", is_short)) {512          jq_flags |= JQ_DEBUG_TRACE;513        } else if (isoption(&text, 'h', "help", is_short)) {514          usage(0, 0);515        } else if (isoption(&text, 'V', "version", is_short)) {516          printf("jq-%s\n", JQ_VERSION);517          ret = JQ_OK;518          goto out;519        } else if (isoption(&text, 0, "build-configuration", is_short)) {520          printf("%s\n", JQ_CONFIG);521          ret = JQ_OK;522          goto out;523        } else if (isoption(&text, 0, "run-tests", is_short)) {524          i++;525          // XXX Pass program_arguments, even a whole jq_state *, through;526          // could be useful for testing527          ret = jq_testsuite(lib_search_paths,528                             (options & DUMP_DISASM) || (jq_flags & JQ_DEBUG_TRACE),529                             argc - i, argv + i);530          goto out;531        } else {532          if (is_short) {533            fprintf(stderr, "jq: Unknown option -%c\n", text[0]);534          } else {535            fprintf(stderr, "jq: Unknown option --%s\n", text);536          }537          die();538        }539      }540    }541  }542543#ifdef USE_ISATTY544  if (isatty(STDOUT_FILENO)) {545#ifndef WIN32546    dumpopts |= JV_PRINT_ISATTY | JV_PRINT_COLOR;547#else548  /* Verify we actually have the console, as the NUL device is also regarded as549     tty.  Windows can handle color if ANSICON (or ConEmu) is installed, or550     Windows 10 supports the virtual terminal */551    DWORD mode;552    HANDLE con = GetStdHandle(STD_OUTPUT_HANDLE);553    if (GetConsoleMode(con, &mode)) {554      dumpopts |= JV_PRINT_ISATTY;555      if (getenv("ANSICON") != NULL ||556          SetConsoleMode(con, mode | 4/*ENABLE_VIRTUAL_TERMINAL_PROCESSING*/))557        dumpopts |= JV_PRINT_COLOR;558    }559#endif560    if (dumpopts & JV_PRINT_COLOR) {561      char *no_color = getenv("NO_COLOR");562      if (no_color != NULL && no_color[0] != '\0')563        dumpopts &= ~JV_PRINT_COLOR;564    }565  }566#endif567  if (options & SORTED_OUTPUT) dumpopts |= JV_PRINT_SORTED;568  if (options & ASCII_OUTPUT) dumpopts |= JV_PRINT_ASCII;569  if (options & COLOR_OUTPUT) dumpopts |= JV_PRINT_COLOR;570  if (options & NO_COLOR_OUTPUT) dumpopts &= ~JV_PRINT_COLOR;571572  if (!jq_set_colors(getenv("JQ_COLORS")))573      fprintf(stderr, "Failed to set $JQ_COLORS\n");574575  if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) {576    // Default search path list577    lib_search_paths = JV_ARRAY(jv_string("~/.jq"),578                                jv_string("$ORIGIN/../lib/jq"),579                                jv_string("$ORIGIN/../lib"));580  }581  jq_set_attr(jq, jv_string("JQ_LIBRARY_PATH"), lib_search_paths);582583  char *origin = strdup(argv[0]);584  if (origin == NULL) {585    fprintf(stderr, "jq: error: out of memory\n");586    exit(1);587  }588  jq_set_attr(jq, jv_string("JQ_ORIGIN"), jv_string(dirname(origin)));589  free(origin);590591  if (strchr(JQ_VERSION, '-') == NULL)592    jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string(JQ_VERSION));593  else594    jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string_fmt("%.*s-master", (int)(strchr(JQ_VERSION, '-') - JQ_VERSION), JQ_VERSION));595596#ifdef USE_ISATTY597  if (!program && !(options & FROM_FILE) && (!isatty(STDOUT_FILENO) || !isatty(STDIN_FILENO)))598    program = ".";599#endif600601  if (!program) usage(2, 1);602603  if (options & FROM_FILE) {604    char *program_origin = strdup(program);605    if (program_origin == NULL) {606      perror("malloc");607      exit(2);608    }609610    jv data = jv_load_file(program, 1);611    if (!jv_is_valid(data)) {612      data = jv_invalid_get_msg(data);613      fprintf(stderr, "jq: %s\n", jv_string_value(data));614      free(program_origin);615      jv_free(data);616      ret = JQ_ERROR_SYSTEM;617      goto out;618    }619    int len = jv_string_length_bytes(jv_copy(data));620    if ((size_t)len != strlen(jv_string_value(data))) {621      fprintf(stderr, "jq: program file contains NUL bytes\n");622      free(program_origin);623      jv_free(data);624      ret = JQ_ERROR_SYSTEM;625      goto out;626    }627    jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string(dirname(program_origin))));628    ARGS = JV_OBJECT(jv_string("positional"), ARGS,629                     jv_string("named"), jv_copy(program_arguments));630    program_arguments = jv_object_set(program_arguments, jv_string("ARGS"), jv_copy(ARGS));631    if (!jv_object_has(jv_copy(program_arguments), jv_string("JQ_BUILD_CONFIGURATION")))632      program_arguments = jv_object_set(program_arguments,633                                        jv_string("JQ_BUILD_CONFIGURATION"),634                                        jv_string(JQ_CONFIG)); /* named arguments */635    compiled = jq_compile_args(jq, jv_string_value(data), jv_copy(program_arguments));636    free(program_origin);637    jv_free(data);638  } else {639    jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string("."))); // XXX is this good?640    ARGS = JV_OBJECT(jv_string("positional"), ARGS,641                     jv_string("named"), jv_copy(program_arguments));642    program_arguments = jv_object_set(program_arguments, jv_string("ARGS"), jv_copy(ARGS));643    if (!jv_object_has(jv_copy(program_arguments), jv_string("JQ_BUILD_CONFIGURATION")))644      program_arguments = jv_object_set(program_arguments,645                                        jv_string("JQ_BUILD_CONFIGURATION"),646                                        jv_string(JQ_CONFIG)); /* named arguments */647    compiled = jq_compile_args(jq, program, jv_copy(program_arguments));648  }649  if (!compiled){650    ret = JQ_ERROR_COMPILE;651    goto out;652  }653654  if (options & DUMP_DISASM) {655    jq_dump_disassembly(jq, 0);656    printf("\n");657  }658659  if ((options & SEQ))660    parser_flags |= JV_PARSE_SEQ;661662  if ((options & RAW_INPUT))663    jq_util_input_set_parser(input_state, NULL, (options & SLURP) ? 1 : 0);664  else665    jq_util_input_set_parser(input_state, jv_parser_new(parser_flags), (options & SLURP) ? 1 : 0);666667  // Let jq program read from inputs668  jq_set_input_cb(jq, jq_util_input_next_input_cb, input_state);669670  // Let jq program call `debug` builtin and have that go somewhere671  jq_set_debug_cb(jq, debug_cb, &dumpopts);672673  // Let jq program call `stderr` builtin and have that go somewhere674  jq_set_stderr_cb(jq, stderr_cb, &dumpopts);675676  if (nfiles == 0)677    jq_util_input_add_input(input_state, "-");678679  if (options & PROVIDE_NULL) {680    ret = process(jq, jv_null(), jq_flags, dumpopts, options);681  } else {682    jv value;683    while (jq_util_input_errors(input_state) == 0 &&684           (jv_is_valid((value = jq_util_input_next_input(input_state))) || jv_invalid_has_msg(jv_copy(value)))) {685      if (jv_is_valid(value)) {686        ret = process(jq, value, jq_flags, dumpopts, options);687        if (ret <= 0 && ret != JQ_OK_NO_OUTPUT)688          last_result = (ret != JQ_OK_NULL_KIND);689        if (jq_halted(jq))690          break;691        continue;692      }693694      // Parse error695      jv msg = jv_invalid_get_msg(value);696      if (!(options & SEQ)) {697        ret = JQ_ERROR_UNKNOWN;698        fprintf(stderr, "jq: parse error: %s\n", jv_string_value(msg));699        jv_free(msg);700        break;701      }702      // --seq -> errors are not fatal703      fprintf(stderr, "jq: ignoring parse error: %s\n", jv_string_value(msg));704      jv_free(msg);705    }706  }707708  if (jq_util_input_errors(input_state) != 0)709    ret = JQ_ERROR_SYSTEM;710711out:712  badwrite = ferror(stdout);713  if (fclose(stdout)!=0 || badwrite) {714    fprintf(stderr,"jq: error: writing output failed: %s\n", strerror(errno));715    ret = JQ_ERROR_SYSTEM;716  }717718  jv_free(ARGS);719  jv_free(program_arguments);720  jq_util_input_free(&input_state);721  jq_teardown(&jq);722723  if (options & EXIT_STATUS) {724    if (ret != JQ_OK_NO_OUTPUT)725      jq_exit_with_status(ret);726    else727      switch (last_result) {728        case -1: jq_exit_with_status(JQ_OK_NO_OUTPUT);729        case  0: jq_exit_with_status(JQ_OK_NULL_KIND);730        default: jq_exit_with_status(JQ_OK);731      }732  } else733    jq_exit(ret);734}