1 /*
   2  * This file and its contents are supplied under the terms of the
   3  * Common Development and Distribution License ("CDDL"), version 1.0.
   4  * You may only use this file in accordance with the terms of version
   5  * 1.0 of the CDDL.
   6  *
   7  * A full copy of the text of the CDDL should have accompanied this
   8  * source.  A copy of the CDDL is also available via the Internet at
   9  * http://www.illumos.org/license/CDDL.
  10  */
  11 
  12 /*
  13  * Copyright (c) 2015, Joyent, Inc.
  14  */
  15 
  16 /*
  17  * Create CTF from extant debugging information
  18  */
  19 
  20 #include <stdio.h>
  21 #include <unistd.h>
  22 #include <stdlib.h>
  23 #include <stdarg.h>
  24 #include <sys/types.h>
  25 #include <sys/stat.h>
  26 #include <fcntl.h>
  27 #include <errno.h>
  28 #include <libelf.h>
  29 #include <libctf.h>
  30 #include <string.h>
  31 #include <libgen.h>
  32 #include <limits.h>
  33 #include <strings.h>
  34 #include <sys/debug.h>
  35 
  36 #define CTFCONVERT_OK           0
  37 #define CTFCONVERT_FATAL        1
  38 #define CTFCONVERT_USAGE        2
  39 
  40 #define CTFCONVERT_DEFAULT_NTHREADS     4
  41 
  42 #define CTFCONVERT_ALTEXEC      "CTFCONVERT_ALTEXEC"
  43 
  44 static char *ctfconvert_progname;
  45 
  46 static void
  47 ctfconvert_fatal(const char *fmt, ...)
  48 {
  49         va_list ap;
  50 
  51         (void) fprintf(stderr, "%s: ", ctfconvert_progname);
  52         va_start(ap, fmt);
  53         (void) vfprintf(stderr, fmt, ap);
  54         va_end(ap);
  55 
  56         exit(CTFCONVERT_FATAL);
  57 }
  58 
  59 
  60 static void
  61 ctfconvert_usage(const char *fmt, ...)
  62 {
  63         if (fmt != NULL) {
  64                 va_list ap;
  65 
  66                 (void) fprintf(stderr, "%s: ", ctfconvert_progname);
  67                 va_start(ap, fmt);
  68                 (void) vfprintf(stderr, fmt, ap);
  69                 va_end(ap);
  70         }
  71 
  72         (void) fprintf(stderr, "Usage: %s [-is] [-j nthrs] [-l label | "
  73             "-L labelenv] [-o outfile] input\n"
  74             "\n"
  75             "\t-i  ignore files not built partially from C sources\n"
  76             "\t-j  use nthrs threads to perform the merge\n"
  77             "\t-k  keep around original input file on failure\n"
  78             "\t-o  copy input to outfile and add CTF\n"
  79             "\t-l  set output container's label to specified value\n"
  80             "\t-L  set output container's label to value from environment\n",
  81             ctfconvert_progname);
  82 }
  83 
  84 /*
  85  * This is a bit unfortunate. Traditionally we do type uniquification across all
  86  * modules in the kernel, including ip and unix against genunix. However, when
  87  * _MACHDEP is defined, then the cpu_t ends up having an additional member
  88  * (cpu_m), thus changing the ability for us to uniquify against it. This in
  89  * turn causes a lot of type sprawl, as there's a lot of things that end up
  90  * referring to the cpu_t and it chains out from there.
  91  *
  92  * So, if we find that a cpu_t has been defined and it has a couple of useful
  93  * sentinel members and it does *not* have the cpu_m member, then we will try
  94  * and lookup or create a forward declaration to the machcpu, append it to the
  95  * end, and update the file.
  96  *
  97  * This currently is only invoked if an undocumented option -X is passed. This
  98  * value is private to illumos and it can be changed at any time inside of it,
  99  * so if -X wants to be used for something, it should be. The ability to rely on
 100  * -X for others is strictly not an interface in any way, shape, or form.
 101  *
 102  * The following struct contains most of the information that we care about and
 103  * that we want to validate exists before we decide what to do.
 104  */
 105 
 106 typedef struct ctfconvert_fixup {
 107         boolean_t       cf_cyclic;      /* Do we have a cpu_cyclic member */
 108         boolean_t       cf_mcpu;        /* We have a cpu_m member */
 109         boolean_t       cf_lastpad;     /* Is the pad member the last entry */
 110         ulong_t         cf_padoff;      /* offset of the pad */
 111 } ctfconvert_fixup_t;
 112 
 113 /* ARGSUSED */
 114 static int
 115 ctfconvert_fixup_genunix_cb(const char *name, ctf_id_t tid, ulong_t off,
 116     void *arg)
 117 {
 118         ctfconvert_fixup_t *cfp = arg;
 119 
 120         cfp->cf_lastpad = B_FALSE;
 121         if (strcmp(name, "cpu_cyclic") == 0) {
 122                 cfp->cf_cyclic = B_TRUE;
 123                 return (0);
 124         }
 125 
 126         if (strcmp(name, "cpu_m") == 0) {
 127                 cfp->cf_mcpu = B_TRUE;
 128                 return (0);
 129         }
 130 
 131         if (strcmp(name, "cpu_m_pad") == 0) {
 132                 cfp->cf_lastpad = B_TRUE;
 133                 cfp->cf_padoff = off;
 134                 return (0);
 135         }
 136 
 137         return (0);
 138 }
 139 
 140 static void
 141 ctfconvert_fixup_genunix(ctf_file_t *fp)
 142 {
 143         ctf_id_t cpuid, mcpu;
 144         ssize_t sz;
 145         ctfconvert_fixup_t cf;
 146         int model, ptrsz;
 147 
 148         cpuid = ctf_lookup_by_name(fp, "struct cpu");
 149         if (cpuid == CTF_ERR)
 150                 return;
 151 
 152         if (ctf_type_kind(fp, cpuid) != CTF_K_STRUCT)
 153                 return;
 154 
 155         if ((sz = ctf_type_size(fp, cpuid)) == CTF_ERR)
 156                 return;
 157 
 158         model = ctf_getmodel(fp);
 159         VERIFY(model == CTF_MODEL_ILP32 || model == CTF_MODEL_LP64);
 160         ptrsz = model == CTF_MODEL_ILP32 ? 4 : 8;
 161 
 162         bzero(&cf, sizeof (ctfconvert_fixup_t));
 163         if (ctf_member_iter(fp, cpuid, ctfconvert_fixup_genunix_cb, &cf) ==
 164             CTF_ERR)
 165                 return;
 166 
 167         /*
 168          * Finally, we want to verify that the cpu_m is actually the last member
 169          * that we have here.
 170          */
 171         if (cf.cf_cyclic == B_FALSE || cf.cf_mcpu == B_TRUE ||
 172             cf.cf_lastpad == B_FALSE) {
 173                 return;
 174         }
 175 
 176         if (cf.cf_padoff + ptrsz * NBBY != sz * NBBY) {
 177                 return;
 178         }
 179 
 180         /*
 181          * Okay, we're going to do this, try to find a struct machcpu. We either
 182          * want a forward or a struct. If we find something else, error. If we
 183          * find nothing, add a forward and then add the member.
 184          */
 185         mcpu = ctf_lookup_by_name(fp, "struct machcpu");
 186         if (mcpu == CTF_ERR) {
 187                 mcpu = ctf_add_forward(fp, CTF_ADD_NONROOT, "machcpu",
 188                     CTF_K_STRUCT);
 189                 if (mcpu == CTF_ERR) {
 190                         ctfconvert_fatal("failed to add 'struct machcpu' "
 191                             "forward: %s", ctf_errmsg(ctf_errno(fp)));
 192                 }
 193         } else {
 194                 int kind;
 195                 if ((kind = ctf_type_kind(fp, mcpu)) == CTF_ERR) {
 196                         ctfconvert_fatal("failed to get the type kind for "
 197                             "the struct machcpu: %s",
 198                             ctf_errmsg(ctf_errno(fp)));
 199                 }
 200 
 201                 if (kind != CTF_K_STRUCT && kind != CTF_K_FORWARD)
 202                         ctfconvert_fatal("encountered a struct machcpu of the "
 203                             "wrong type, found type kind %d\n", kind);
 204         }
 205 
 206         if (ctf_update(fp) == CTF_ERR) {
 207                 ctfconvert_fatal("failed to update output file: %s\n",
 208                     ctf_errmsg(ctf_errno(fp)));
 209         }
 210 
 211         if (ctf_add_member(fp, cpuid, "cpu_m", mcpu, sz * NBBY) == CTF_ERR) {
 212                 ctfconvert_fatal("failed to add the m_cpu member: %s\n",
 213                     ctf_errmsg(ctf_errno(fp)));
 214         }
 215 
 216         if (ctf_update(fp) == CTF_ERR) {
 217                 ctfconvert_fatal("failed to update output file: %s\n",
 218                     ctf_errmsg(ctf_errno(fp)));
 219         }
 220 
 221         VERIFY(ctf_type_size(fp, cpuid) == sz);
 222 }
 223 
 224 static void
 225 ctfconvert_altexec(char **argv)
 226 {
 227         const char *alt;
 228         char *altexec;
 229 
 230         alt = getenv(CTFCONVERT_ALTEXEC);
 231         if (alt == NULL || *alt == '\0')
 232                 return;
 233 
 234         altexec = strdup(alt);
 235         if (altexec == NULL)
 236                 ctfconvert_fatal("failed to allocate memory for altexec\n");
 237         if (unsetenv(CTFCONVERT_ALTEXEC) != 0)
 238                 ctfconvert_fatal("failed to unset %s from environment: %s\n",
 239                     CTFCONVERT_ALTEXEC, strerror(errno));
 240 
 241         (void) execv(altexec, argv);
 242         ctfconvert_fatal("failed to execute alternate program %s: %s",
 243             altexec, strerror(errno));
 244 }
 245 
 246 int
 247 main(int argc, char *argv[])
 248 {
 249         int c, ifd, err;
 250         boolean_t keep = B_FALSE;
 251         uint_t flags = 0;
 252         uint_t nthreads = CTFCONVERT_DEFAULT_NTHREADS;
 253         const char *outfile = NULL;
 254         const char *label = NULL;
 255         const char *infile = NULL;
 256         char *tmpfile;
 257         ctf_file_t *ofp;
 258         long argj;
 259         char *eptr;
 260         char buf[4096];
 261         boolean_t optx = B_FALSE;
 262 
 263         ctfconvert_progname = basename(argv[0]);
 264 
 265         ctfconvert_altexec(argv);
 266 
 267         while ((c = getopt(argc, argv, ":j:kl:L:o:iX")) != -1) {
 268                 switch (c) {
 269                 case 'k':
 270                         keep = B_TRUE;
 271                         break;
 272                 case 'l':
 273                         label = optarg;
 274                         break;
 275                 case 'L':
 276                         label = getenv(optarg);
 277                         break;
 278                 case 'j':
 279                         errno = 0;
 280                         argj = strtol(optarg, &eptr, 10);
 281                         if (errno != 0 || argj == LONG_MAX ||
 282                             argj > 1024 || *eptr != '\0') {
 283                                 ctfconvert_fatal("invalid argument for -j: "
 284                                     "%s\n", optarg);
 285                         }
 286                         nthreads = (uint_t)argj;
 287                         break;
 288                 case 'o':
 289                         outfile = optarg;
 290                         break;
 291                 case 'i':
 292                         flags |= CTF_CONVERT_F_IGNNONC;
 293                         break;
 294                 case 'X':
 295                         optx = B_TRUE;
 296                         break;
 297                 case ':':
 298                         ctfconvert_usage("Option -%c requires an operand\n",
 299                             optopt);
 300                         return (CTFCONVERT_USAGE);
 301                 case '?':
 302                         ctfconvert_usage("Unknown option: -%c\n", optopt);
 303                         return (CTFCONVERT_USAGE);
 304                 }
 305         }
 306 
 307         argv += optind;
 308         argc -= optind;
 309 
 310         if (argc < 1) {
 311                 ctfconvert_usage("Missing required input file\n");
 312                 return (CTFCONVERT_USAGE);
 313         }
 314         infile = argv[0];
 315 
 316         if (elf_version(EV_CURRENT) == EV_NONE)
 317                 ctfconvert_fatal("failed to initialize libelf: library is "
 318                     "out of date\n");
 319 
 320         ifd = open(infile, O_RDONLY);
 321         if (ifd < 0) {
 322                 ctfconvert_fatal("failed to open input file %s: %s\n", infile,
 323                     strerror(errno));
 324         }
 325 
 326         /*
 327          * By default we remove the input file on failure unless we've been
 328          * given an output file or -k has been specified.
 329          */
 330         if (outfile != NULL && strcmp(infile, outfile) != 0)
 331                 keep = B_TRUE;
 332 
 333         ofp = ctf_fdconvert(ifd, label, nthreads, flags, &err, buf,
 334             sizeof (buf));
 335         if (ofp == NULL) {
 336                 /*
 337                  * -i says that we shouldn't concern ourselves with source files
 338                  * that weren't built from C source code in part. Because this
 339                  * has been traditionally used across all of illumos, we still
 340                  * honor it.
 341                  */
 342                 if ((flags & CTF_CONVERT_F_IGNNONC) != 0 &&
 343                     err == ECTF_CONVNOCSRC) {
 344                         exit(CTFCONVERT_OK);
 345                 }
 346                 if (keep == B_FALSE)
 347                         (void) unlink(infile);
 348                 ctfconvert_fatal("CTF conversion failed: %s\n",
 349                     err == ECTF_CONVBKERR ? buf : ctf_errmsg(err));
 350         }
 351 
 352         if (optx == B_TRUE)
 353                 ctfconvert_fixup_genunix(ofp);
 354 
 355         tmpfile = NULL;
 356         if (outfile == NULL || strcmp(infile, outfile) == 0) {
 357                 if (asprintf(&tmpfile, "%s.ctf", infile) == -1) {
 358                         if (keep == B_FALSE)
 359                                 (void) unlink(infile);
 360                         ctfconvert_fatal("failed to allocate memory for "
 361                             "temporary file: %s\n", strerror(errno));
 362                 }
 363                 outfile = tmpfile;
 364         }
 365         err = ctf_elfwrite(ofp, infile, outfile, CTF_ELFWRITE_F_COMPRESS);
 366         if (err == CTF_ERR) {
 367                 (void) unlink(outfile);
 368                 if (keep == B_FALSE)
 369                         (void) unlink(infile);
 370                 ctfconvert_fatal("failed to write CTF section to output file: "
 371                     "%s", ctf_errmsg(ctf_errno(ofp)));
 372         }
 373         ctf_close(ofp);
 374 
 375         if (tmpfile != NULL) {
 376                 if (rename(tmpfile, infile) != 0) {
 377                         int e = errno;
 378                         (void) unlink(outfile);
 379                         if (keep == B_FALSE)
 380                                 (void) unlink(infile);
 381                         ctfconvert_fatal("failed to rename temporary file: "
 382                             "%s\n", strerror(e));
 383                 }
 384         }
 385         free(tmpfile);
 386 
 387         return (CTFCONVERT_OK);
 388 }