aboutsummaryrefslogtreecommitdiff
path: root/tools/ccj.c
blob: 49c040a0613b3df12e43a80e880e594c70ce2a40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void *mallocx(size_t sz) {
  void *buf = malloc(sz);
  if (!buf) {
    perror("malloc");
    exit(EXIT_FAILURE);
  }
  return buf;
}

static int scanopt(int argc, char *argv[argc + 1], char const *optstr) {
  opterr = 0;
  int ch = getopt(argc, argv, optstr);
  if (ch == -1 && optind < argc) {
    ch = '?';
    optind++;
  }
  return ch;
}

static char *strchext(char const *s, char const *ext, char const *newext) {
  size_t ls = strlen(s);
  size_t lx = strlen(ext);
  size_t ln = strlen(newext);

  size_t lb = ls - lx;
  if (lb > ls || strcmp(s + lb, ext)) {
    return NULL;
  }

  char *buf = mallocx(lb + ln + 1);
  memcpy(buf, s, lb);
  memcpy(buf + lb, newext, ln + 1);
  return buf;
}

int main(int argc, char *argv[argc + 1]) {
  // We want to wrap `clang` calls to add an additional `-MJ ${@:.o=.json}`
  // option to output a `compile_commands.json` fragment for `clangd`.
  bool compile;
  char *json = NULL;
  int ch;
  while ((ch = scanopt(argc, argv, "co:")) != -1) {
    switch (ch) {
    case 'c':
      compile = true;
      break;
    case 'o':
      json = strchext(optarg, ".o", ".json");
      break;
    }
  }

  char **args;
  char arg0[] = "cc";
  if (argc && compile && json) {
    args = mallocx((argc + 3) * sizeof(char *));
    args[0] = arg0;
    args[1] = "-MJ";
    args[2] = json;
    memcpy(args + 3, argv + 1, argc * sizeof(char *));
  } else {
    args = argv;
    args[0] = arg0;
  }

  (void)execvp("clang", args);

  // If we get here, then `exec` failed. Clean up and error.
  perror("exec(clang)");
  if (args != argv) {
    free(args);
  }
  free(json);
  return EXIT_FAILURE;
}