1 /*
   2  * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 #include <stdarg.h>
  25 #include <stdio.h>
  26 #include <stdlib.h>
  27 #include <string.h>
  28 #include <fcntl.h>
  29 #include <sys/procfs.h>
  30 #include "libproc_impl.h"
  31 #include "proc_service.h"
  32 #include "salibelf.h"
  33 
  34 #define SA_ALTROOT "SA_ALTROOT"
  35 
  36 int pathmap_open(const char* name) {
  37   static const char *alt_root = NULL;
  38   static int alt_root_initialized = 0;
  39 
  40   int fd;
  41   char alt_path[PATH_MAX + 1], *alt_path_end;
  42   const char *s;
  43   int free_space;
  44 
  45   if (!alt_root_initialized) {
  46     alt_root_initialized = -1;
  47     alt_root = getenv(SA_ALTROOT);
  48   }
  49 
  50   if (alt_root == NULL) {
  51     return open(name, O_RDONLY);
  52   }
  53 
  54 
  55   if (strlen(alt_root) + strlen(name) > PATH_MAX) {
  56     // Buffer too small.
  57     return -1;
  58   }
  59 
  60   strncpy(alt_path, alt_root, PATH_MAX);
  61   alt_path[PATH_MAX] = '\0';
  62   alt_path_end = alt_path + strlen(alt_path);
  63   free_space = PATH_MAX + 1 - (alt_path_end-alt_path);
  64 
  65   // Strip path items one by one and try to open file with alt_root prepended.
  66   s = name;
  67   while (1) {
  68     strncat(alt_path, s, free_space);
  69     s += 1;  // Skip /.
  70 
  71     fd = open(alt_path, O_RDONLY);
  72     if (fd >= 0) {
  73       print_debug("path %s substituted for %s\n", alt_path, name);
  74       return fd;
  75     }
  76 
  77     // Linker always put full path to solib to process, so we can rely
  78     // on presence of /. If slash is not present, it means, that SOlib doesn't
  79     // physically exist (e.g. linux-gate.so) and we fail opening it anyway
  80     if ((s = strchr(s, '/')) == NULL) {
  81       break;
  82     }
  83 
  84     // Cut off what we appended above.
  85     *alt_path_end = '\0';
  86   }
  87 
  88   return -1;
  89 }
  90 
  91 static bool _libsaproc_debug;
  92 
  93 void print_debug(const char* format,...) {
  94    if (_libsaproc_debug) {
  95      va_list alist;
  96 
  97      va_start(alist, format);
  98      fputs("libsaproc DEBUG: ", stderr);
  99      vfprintf(stderr, format, alist);
 100      va_end(alist);
 101    }
 102 }
 103 
 104 void print_error(const char* format,...) {
 105   va_list alist;
 106   va_start(alist, format);
 107   fputs("ERROR: ", stderr);
 108   vfprintf(stderr, format, alist);
 109   va_end(alist);
 110 }
 111 
 112 bool is_debug() {
 113    return _libsaproc_debug;
 114 }
 115 
 116 // initialize libproc
 117 JNIEXPORT bool JNICALL
 118 init_libproc(bool debug) {
 119    // init debug mode
 120    _libsaproc_debug = debug;
 121    return true;
 122 }
 123 
 124 static void destroy_lib_info(struct ps_prochandle* ph) {
 125    lib_info* lib = ph->libs;
 126    while (lib) {
 127      lib_info *next = lib->next;
 128      if (lib->symtab) {
 129         destroy_symtab(lib->symtab);
 130      }
 131      if (lib->eh_frame.data) {
 132        free(lib->eh_frame.data);
 133      }
 134      free(lib);
 135      lib = next;
 136    }
 137 }
 138 
 139 static void destroy_thread_info(struct ps_prochandle* ph) {
 140    thread_info* thr = ph->threads;
 141    while (thr) {
 142      thread_info *next = thr->next;
 143      free(thr);
 144      thr = next;
 145    }
 146 }
 147 
 148 // ps_prochandle cleanup
 149 
 150 // ps_prochandle cleanup
 151 JNIEXPORT void JNICALL
 152 Prelease(struct ps_prochandle* ph) {
 153    // do the "derived class" clean-up first
 154    ph->ops->release(ph);
 155    destroy_lib_info(ph);
 156    destroy_thread_info(ph);
 157    free(ph);
 158 }
 159 
 160 lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base) {
 161    return add_lib_info_fd(ph, libname, -1, base);
 162 }
 163 
 164 static bool fill_instr_info(lib_info* lib) {
 165   off_t current_pos;
 166   ELF_EHDR ehdr;
 167   ELF_PHDR* phbuf = NULL;
 168   ELF_PHDR* ph = NULL;
 169   int cnt;
 170   long align = sysconf(_SC_PAGE_SIZE);
 171 
 172   current_pos = lseek(lib->fd, (off_t)0L, SEEK_CUR);
 173   lseek(lib->fd, (off_t)0L, SEEK_SET);
 174   read_elf_header(lib->fd, &ehdr);
 175   if ((phbuf = read_program_header_table(lib->fd, &ehdr)) == NULL) {
 176     lseek(lib->fd, current_pos, SEEK_SET);
 177     return false;
 178   }
 179 
 180   lib->exec_start = 0L;
 181   lib->exec_end = 0L;
 182   for (ph = phbuf, cnt = 0; cnt < ehdr.e_phnum; cnt++, ph++) {
 183     if ((ph->p_type == PT_LOAD) && (ph->p_flags & PF_X)) {
 184       print_debug("[%d] vaddr = 0x%lx, memsz = 0x%lx, filesz = 0x%lx\n", cnt, ph->p_vaddr, ph->p_memsz, ph->p_filesz);
 185       if ((lib->exec_start == 0L) || (lib->exec_start > ph->p_vaddr)) {
 186         lib->exec_start = ph->p_vaddr;
 187       }
 188       if (lib->exec_end < (ph->p_vaddr + ph->p_memsz)) {
 189         lib->exec_end = ph->p_vaddr + ph->p_memsz;
 190       }
 191       align = ph->p_align;
 192     }
 193   }
 194 
 195   free(phbuf);
 196   lseek(lib->fd, current_pos, SEEK_SET);
 197 
 198   if ((lib->exec_start == 0L) || (lib->exec_end == 0L)) {
 199     return false;
 200   } else {
 201     lib->exec_start = (lib->exec_start + lib->base) & ~(align - 1);
 202     lib->exec_end = (lib->exec_end + lib->base + align) & ~(align - 1);
 203     return true;
 204   }
 205 
 206 }
 207 
 208 bool read_eh_frame(struct ps_prochandle* ph, lib_info* lib) {
 209   off_t current_pos = -1;
 210   ELF_EHDR ehdr;
 211   ELF_SHDR* shbuf = NULL;
 212   ELF_SHDR* sh = NULL;
 213   char* strtab = NULL;
 214   void* result = NULL;
 215   int cnt;
 216 
 217   current_pos = lseek(lib->fd, (off_t)0L, SEEK_CUR);
 218   lseek(lib->fd, (off_t)0L, SEEK_SET);
 219 
 220   read_elf_header(lib->fd, &ehdr);
 221   shbuf = read_section_header_table(lib->fd, &ehdr);
 222   strtab = read_section_data(lib->fd, &ehdr, &shbuf[ehdr.e_shstrndx]);
 223 
 224   for (cnt = 0, sh = shbuf; cnt < ehdr.e_shnum; cnt++, sh++) {
 225     if (strcmp(".eh_frame", sh->sh_name + strtab) == 0) {
 226       lib->eh_frame.library_base_addr = lib->base;
 227       lib->eh_frame.v_addr = sh->sh_addr;
 228       lib->eh_frame.data = read_section_data(lib->fd, &ehdr, sh);
 229       break;
 230     }
 231   }
 232 
 233   free(strtab);
 234   free(shbuf);
 235   lseek(lib->fd, current_pos, SEEK_SET);
 236   return lib->eh_frame.data != NULL;
 237 }
 238 
 239 lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd, uintptr_t base) {
 240    lib_info* newlib;
 241 
 242    if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
 243       print_debug("can't allocate memory for lib_info\n");
 244       return NULL;
 245    }
 246 
 247    if (strlen(libname) >= sizeof(newlib->name)) {
 248      print_debug("libname %s too long\n", libname);
 249      free(newlib);
 250      return NULL;
 251    }
 252    strcpy(newlib->name, libname);
 253 
 254    newlib->base = base;
 255 
 256    if (fd == -1) {
 257       if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
 258          print_debug("can't open shared object %s\n", newlib->name);
 259          free(newlib);
 260          return NULL;
 261       }
 262    } else {
 263       newlib->fd = fd;
 264    }
 265 
 266    // check whether we have got an ELF file. /proc/<pid>/map
 267    // gives out all file mappings and not just shared objects
 268    if (is_elf_file(newlib->fd) == false) {
 269       close(newlib->fd);
 270       free(newlib);
 271       return NULL;
 272    }
 273 
 274    newlib->symtab = build_symtab(newlib->fd, libname);
 275    if (newlib->symtab == NULL) {
 276       print_debug("symbol table build failed for %s\n", newlib->name);
 277    }
 278 
 279    if (fill_instr_info(newlib)) {
 280      if (!read_eh_frame(ph, newlib)) {
 281        print_debug("Could not find .eh_frame section in %s\n", newlib->name);
 282      }
 283    } else {
 284       print_debug("Could not find executable section in %s\n", newlib->name);
 285    }
 286 
 287    // even if symbol table building fails, we add the lib_info.
 288    // This is because we may need to read from the ELF file for core file
 289    // address read functionality. lookup_symbol checks for NULL symtab.
 290    if (ph->libs) {
 291       ph->lib_tail->next = newlib;
 292       ph->lib_tail = newlib;
 293    }  else {
 294       ph->libs = ph->lib_tail = newlib;
 295    }
 296    ph->num_libs++;
 297 
 298    return newlib;
 299 }
 300 
 301 // lookup for a specific symbol
 302 uintptr_t lookup_symbol(struct ps_prochandle* ph,  const char* object_name,
 303                        const char* sym_name) {
 304    // ignore object_name. search in all libraries
 305    // FIXME: what should we do with object_name?? The library names are obtained
 306    // by parsing /proc/<pid>/maps, which may not be the same as object_name.
 307    // What we need is a utility to map object_name to real file name, something
 308    // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
 309    // now, we just ignore object_name and do a global search for the symbol.
 310 
 311    lib_info* lib = ph->libs;
 312    while (lib) {
 313       if (lib->symtab) {
 314          uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
 315          if (res) return res;
 316       }
 317       lib = lib->next;
 318    }
 319 
 320    print_debug("lookup failed for symbol '%s' in obj '%s'\n",
 321                           sym_name, object_name);
 322    return (uintptr_t) NULL;
 323 }
 324 
 325 
 326 const char* symbol_for_pc(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* poffset) {
 327    const char* res = NULL;
 328    lib_info* lib = ph->libs;
 329    while (lib) {
 330       if (lib->symtab && addr >= lib->base) {
 331          res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
 332          if (res) return res;
 333       }
 334       lib = lib->next;
 335    }
 336    return NULL;
 337 }
 338 
 339 // add a thread to ps_prochandle
 340 thread_info* add_thread_info(struct ps_prochandle* ph, lwpid_t lwp_id) {
 341    thread_info* newthr;
 342    if ( (newthr = (thread_info*) calloc(1, sizeof(thread_info))) == NULL) {
 343       print_debug("can't allocate memory for thread_info\n");
 344       return NULL;
 345    }
 346 
 347    // initialize thread info
 348    newthr->lwp_id = lwp_id;
 349 
 350    // add new thread to the list
 351    newthr->next = ph->threads;
 352    ph->threads = newthr;
 353    ph->num_threads++;
 354    return newthr;
 355 }
 356 
 357 void delete_thread_info(struct ps_prochandle* ph, thread_info* thr_to_be_removed) {
 358     thread_info* current_thr = ph->threads;
 359 
 360     if (thr_to_be_removed == ph->threads) {
 361       ph->threads = ph->threads->next;
 362     } else {
 363       thread_info* previous_thr;
 364       while (current_thr && current_thr != thr_to_be_removed) {
 365         previous_thr = current_thr;
 366         current_thr = current_thr->next;
 367       }
 368       if (current_thr == NULL) {
 369         print_error("Could not find the thread to be removed");
 370         return;
 371       }
 372       previous_thr->next = current_thr->next;
 373     }
 374     ph->num_threads--;
 375     free(current_thr);
 376 }
 377 
 378 // get number of threads
 379 int get_num_threads(struct ps_prochandle* ph) {
 380    return ph->num_threads;
 381 }
 382 
 383 // get lwp_id of n'th thread
 384 lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
 385    int count = 0;
 386    thread_info* thr = ph->threads;
 387    while (thr) {
 388       if (count == index) {
 389          return thr->lwp_id;
 390       }
 391       count++;
 392       thr = thr->next;
 393    }
 394    return -1;
 395 }
 396 
 397 // get regs for a given lwp
 398 bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct user_regs_struct* regs) {
 399   return ph->ops->get_lwp_regs(ph, lwp_id, regs);
 400 }
 401 
 402 // get number of shared objects
 403 int get_num_libs(struct ps_prochandle* ph) {
 404    return ph->num_libs;
 405 }
 406 
 407 // get name of n'th solib
 408 const char* get_lib_name(struct ps_prochandle* ph, int index) {
 409    int count = 0;
 410    lib_info* lib = ph->libs;
 411    while (lib) {
 412       if (count == index) {
 413          return lib->name;
 414       }
 415       count++;
 416       lib = lib->next;
 417    }
 418    return NULL;
 419 }
 420 
 421 // get base address of a lib
 422 uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
 423    int count = 0;
 424    lib_info* lib = ph->libs;
 425    while (lib) {
 426       if (count == index) {
 427          return lib->base;
 428       }
 429       count++;
 430       lib = lib->next;
 431    }
 432    return (uintptr_t)NULL;
 433 }
 434 
 435 bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
 436   lib_info *p = ph->libs;
 437   while (p) {
 438     if (strcmp(p->name, lib_name) == 0) {
 439       return true;
 440     }
 441     p = p->next;
 442   }
 443   return false;
 444 }
 445 
 446 struct lib_info *find_lib_by_address(struct ps_prochandle* ph, uintptr_t pc) {
 447   lib_info *p = ph->libs;
 448   while (p) {
 449     if ((p->exec_start <= pc) && (pc < p->exec_end)) {
 450       return p;
 451     }
 452     p = p->next;
 453   }
 454   return NULL;
 455 }
 456 
 457 //--------------------------------------------------------------------------
 458 // proc service functions
 459 
 460 // get process id
 461 JNIEXPORT pid_t JNICALL
 462 ps_getpid(struct ps_prochandle *ph) {
 463    return ph->pid;
 464 }
 465 
 466 // ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
 467 // of the load object object_name in the target process identified by ph.
 468 // It returns the symbol's value as an address in the target process in
 469 // *sym_addr.
 470 
 471 JNIEXPORT ps_err_e JNICALL
 472 ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
 473                     const char *sym_name, psaddr_t *sym_addr) {
 474   *sym_addr = (psaddr_t) lookup_symbol(ph, object_name, sym_name);
 475   return (*sym_addr ? PS_OK : PS_NOSYM);
 476 }
 477 
 478 // read "size" bytes info "buf" from address "addr"
 479 JNIEXPORT ps_err_e JNICALL
 480 ps_pdread(struct ps_prochandle *ph, psaddr_t  addr,
 481                    void *buf, size_t size) {
 482   return ph->ops->p_pread(ph, (uintptr_t) addr, buf, size)? PS_OK: PS_ERR;
 483 }
 484 
 485 // write "size" bytes of data to debuggee at address "addr"
 486 JNIEXPORT ps_err_e JNICALL
 487 ps_pdwrite(struct ps_prochandle *ph, psaddr_t addr,
 488                     const void *buf, size_t size) {
 489   return ph->ops->p_pwrite(ph, (uintptr_t)addr, buf, size)? PS_OK: PS_ERR;
 490 }
 491 
 492 // ------------------------------------------------------------------------
 493 // Functions below this point are not yet implemented. They are here only
 494 // to make the linker happy.
 495 
 496 JNIEXPORT ps_err_e JNICALL
 497 ps_lsetfpregs(struct ps_prochandle *ph, lwpid_t lid, const prfpregset_t *fpregs) {
 498   print_debug("ps_lsetfpregs not implemented\n");
 499   return PS_OK;
 500 }
 501 
 502 JNIEXPORT ps_err_e JNICALL
 503 ps_lsetregs(struct ps_prochandle *ph, lwpid_t lid, const prgregset_t gregset) {
 504   print_debug("ps_lsetregs not implemented\n");
 505   return PS_OK;
 506 }
 507 
 508 JNIEXPORT ps_err_e  JNICALL
 509 ps_lgetfpregs(struct  ps_prochandle  *ph,  lwpid_t lid, prfpregset_t *fpregs) {
 510   print_debug("ps_lgetfpregs not implemented\n");
 511   return PS_OK;
 512 }
 513 
 514 JNIEXPORT ps_err_e JNICALL
 515 ps_lgetregs(struct ps_prochandle *ph, lwpid_t lid, prgregset_t gregset) {
 516   print_debug("ps_lgetfpregs not implemented\n");
 517   return PS_OK;
 518 }
 519