1 /*
   2  * Copyright (c) 2003, 2020, 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      free(lib->eh_frame.data);
 132      free(lib);
 133      lib = next;
 134    }
 135 }
 136 
 137 static void destroy_thread_info(struct ps_prochandle* ph) {
 138    thread_info* thr = ph->threads;
 139    while (thr) {
 140      thread_info *next = thr->next;
 141      free(thr);
 142      thr = next;
 143    }
 144 }
 145 
 146 // ps_prochandle cleanup
 147 
 148 // ps_prochandle cleanup
 149 JNIEXPORT void JNICALL
 150 Prelease(struct ps_prochandle* ph) {
 151    // do the "derived class" clean-up first
 152    ph->ops->release(ph);
 153    destroy_lib_info(ph);
 154    destroy_thread_info(ph);
 155    free(ph);
 156 }
 157 
 158 lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base) {
 159    return add_lib_info_fd(ph, libname, -1, base);
 160 }
 161 
 162 static bool fill_instr_info(lib_info* lib) {
 163   off_t current_pos;
 164   ELF_EHDR ehdr;
 165   ELF_PHDR* phbuf = NULL;
 166   ELF_PHDR* ph = NULL;
 167   int cnt;
 168   long align = sysconf(_SC_PAGE_SIZE);
 169 
 170   current_pos = lseek(lib->fd, (off_t)0L, SEEK_CUR);
 171   lseek(lib->fd, (off_t)0L, SEEK_SET);
 172   read_elf_header(lib->fd, &ehdr);
 173   if ((phbuf = read_program_header_table(lib->fd, &ehdr)) == NULL) {
 174     lseek(lib->fd, current_pos, SEEK_SET);
 175     return false;
 176   }
 177 
 178   lib->exec_start = (uintptr_t)-1L;
 179   lib->exec_end = (uintptr_t)-1L;
 180   for (ph = phbuf, cnt = 0; cnt < ehdr.e_phnum; cnt++, ph++) {
 181     if ((ph->p_type == PT_LOAD) && (ph->p_flags & PF_X)) {
 182       print_debug("[%d] vaddr = 0x%lx, memsz = 0x%lx, filesz = 0x%lx\n", cnt, ph->p_vaddr, ph->p_memsz, ph->p_filesz);
 183       if ((lib->exec_start == -1L) || (lib->exec_start > ph->p_vaddr)) {
 184         lib->exec_start = ph->p_vaddr;
 185       }
 186       if ((lib->exec_end == (uintptr_t)-1L) || (lib->exec_end < (ph->p_vaddr + ph->p_memsz))) {
 187         lib->exec_end = ph->p_vaddr + ph->p_memsz;
 188       }
 189       align = ph->p_align;
 190     }
 191   }
 192 
 193   free(phbuf);
 194   lseek(lib->fd, current_pos, SEEK_SET);
 195 
 196   if ((lib->exec_start == -1L) || (lib->exec_end == -1L)) {
 197     return false;
 198   } else {
 199     lib->exec_start = (lib->exec_start + lib->base) & ~(align - 1);
 200     lib->exec_end = (lib->exec_end + lib->base + align) & ~(align - 1);
 201     return true;
 202   }
 203 
 204 }
 205 
 206 bool read_eh_frame(struct ps_prochandle* ph, lib_info* lib) {
 207   off_t current_pos = -1;
 208   ELF_EHDR ehdr;
 209   ELF_SHDR* shbuf = NULL;
 210   ELF_SHDR* sh = NULL;
 211   char* strtab = NULL;
 212   void* result = NULL;
 213   int cnt;
 214 
 215   current_pos = lseek(lib->fd, (off_t)0L, SEEK_CUR);
 216   lseek(lib->fd, (off_t)0L, SEEK_SET);
 217 
 218   read_elf_header(lib->fd, &ehdr);
 219   shbuf = read_section_header_table(lib->fd, &ehdr);
 220   strtab = read_section_data(lib->fd, &ehdr, &shbuf[ehdr.e_shstrndx]);
 221 
 222   for (cnt = 0, sh = shbuf; cnt < ehdr.e_shnum; cnt++, sh++) {
 223     if (strcmp(".eh_frame", sh->sh_name + strtab) == 0) {
 224       lib->eh_frame.library_base_addr = lib->base;
 225       lib->eh_frame.v_addr = sh->sh_addr;
 226       lib->eh_frame.data = read_section_data(lib->fd, &ehdr, sh);
 227       lib->eh_frame.size = sh->sh_size;
 228       break;
 229     }
 230   }
 231 
 232   free(strtab);
 233   free(shbuf);
 234   lseek(lib->fd, current_pos, SEEK_SET);
 235   return lib->eh_frame.data != NULL;
 236 }
 237 
 238 lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd, uintptr_t base) {
 239    lib_info* newlib;
 240 
 241    if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
 242       print_debug("can't allocate memory for lib_info\n");
 243       return NULL;
 244    }
 245 
 246    if (strlen(libname) >= sizeof(newlib->name)) {
 247      print_debug("libname %s too long\n", libname);
 248      free(newlib);
 249      return NULL;
 250    }
 251    strcpy(newlib->name, libname);
 252 
 253    newlib->base = base;
 254 
 255    if (fd == -1) {
 256       if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
 257          print_debug("can't open shared object %s\n", newlib->name);
 258          free(newlib);
 259          return NULL;
 260       }
 261    } else {
 262       newlib->fd = fd;
 263    }
 264 
 265    // check whether we have got an ELF file. /proc/<pid>/map
 266    // gives out all file mappings and not just shared objects
 267    if (is_elf_file(newlib->fd) == false) {
 268       close(newlib->fd);
 269       free(newlib);
 270       return NULL;
 271    }
 272 
 273    newlib->symtab = build_symtab(newlib->fd, libname);
 274    if (newlib->symtab == NULL) {
 275       print_debug("symbol table build failed for %s\n", newlib->name);
 276    }
 277 
 278    if (fill_instr_info(newlib)) {
 279      if (!read_eh_frame(ph, newlib)) {
 280        print_debug("Could not find .eh_frame section in %s\n", newlib->name);
 281      }
 282    } else {
 283       print_debug("Could not find executable section in %s\n", newlib->name);
 284    }
 285 
 286    // even if symbol table building fails, we add the lib_info.
 287    // This is because we may need to read from the ELF file for core file
 288    // address read functionality. lookup_symbol checks for NULL symtab.
 289    if (ph->libs) {
 290       ph->lib_tail->next = newlib;
 291       ph->lib_tail = newlib;
 292    }  else {
 293       ph->libs = ph->lib_tail = newlib;
 294    }
 295    ph->num_libs++;
 296 
 297    return newlib;
 298 }
 299 
 300 // lookup for a specific symbol
 301 uintptr_t lookup_symbol(struct ps_prochandle* ph,  const char* object_name,
 302                        const char* sym_name) {
 303    // ignore object_name. search in all libraries
 304    // FIXME: what should we do with object_name?? The library names are obtained
 305    // by parsing /proc/<pid>/maps, which may not be the same as object_name.
 306    // What we need is a utility to map object_name to real file name, something
 307    // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
 308    // now, we just ignore object_name and do a global search for the symbol.
 309 
 310    lib_info* lib = ph->libs;
 311    while (lib) {
 312       if (lib->symtab) {
 313          uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
 314          if (res) return res;
 315       }
 316       lib = lib->next;
 317    }
 318 
 319    print_debug("lookup failed for symbol '%s' in obj '%s'\n",
 320                           sym_name, object_name);
 321    return (uintptr_t) NULL;
 322 }
 323 
 324 
 325 const char* symbol_for_pc(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* poffset) {
 326    const char* res = NULL;
 327    lib_info* lib = ph->libs;
 328    while (lib) {
 329       if (lib->symtab && addr >= lib->base) {
 330          res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
 331          if (res) return res;
 332       }
 333       lib = lib->next;
 334    }
 335    return NULL;
 336 }
 337 
 338 // add a thread to ps_prochandle
 339 thread_info* add_thread_info(struct ps_prochandle* ph, lwpid_t lwp_id) {
 340    thread_info* newthr;
 341    if ( (newthr = (thread_info*) calloc(1, sizeof(thread_info))) == NULL) {
 342       print_debug("can't allocate memory for thread_info\n");
 343       return NULL;
 344    }
 345 
 346    // initialize thread info
 347    newthr->lwp_id = lwp_id;
 348 
 349    // add new thread to the list
 350    newthr->next = ph->threads;
 351    ph->threads = newthr;
 352    ph->num_threads++;
 353    return newthr;
 354 }
 355 
 356 void delete_thread_info(struct ps_prochandle* ph, thread_info* thr_to_be_removed) {
 357     thread_info* current_thr = ph->threads;
 358 
 359     if (thr_to_be_removed == ph->threads) {
 360       ph->threads = ph->threads->next;
 361     } else {
 362       thread_info* previous_thr = NULL;
 363       while (current_thr && current_thr != thr_to_be_removed) {
 364         previous_thr = current_thr;
 365         current_thr = current_thr->next;
 366       }
 367       if (current_thr == NULL) {
 368         print_error("Could not find the thread to be removed");
 369         return;
 370       }
 371       previous_thr->next = current_thr->next;
 372     }
 373     ph->num_threads--;
 374     free(current_thr);
 375 }
 376 
 377 // get number of threads
 378 int get_num_threads(struct ps_prochandle* ph) {
 379    return ph->num_threads;
 380 }
 381 
 382 // get lwp_id of n'th thread
 383 lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
 384    int count = 0;
 385    thread_info* thr = ph->threads;
 386    while (thr) {
 387       if (count == index) {
 388          return thr->lwp_id;
 389       }
 390       count++;
 391       thr = thr->next;
 392    }
 393    return -1;
 394 }
 395 
 396 // get regs for a given lwp
 397 bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct user_regs_struct* regs) {
 398   return ph->ops->get_lwp_regs(ph, lwp_id, regs);
 399 }
 400 
 401 // get number of shared objects
 402 int get_num_libs(struct ps_prochandle* ph) {
 403    return ph->num_libs;
 404 }
 405 
 406 // get name of n'th solib
 407 const char* get_lib_name(struct ps_prochandle* ph, int index) {
 408    int count = 0;
 409    lib_info* lib = ph->libs;
 410    while (lib) {
 411       if (count == index) {
 412          return lib->name;
 413       }
 414       count++;
 415       lib = lib->next;
 416    }
 417    return NULL;
 418 }
 419 
 420 // get base address of a lib
 421 uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
 422    int count = 0;
 423    lib_info* lib = ph->libs;
 424    while (lib) {
 425       if (count == index) {
 426          return lib->base;
 427       }
 428       count++;
 429       lib = lib->next;
 430    }
 431    return (uintptr_t)NULL;
 432 }
 433 
 434 bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
 435   lib_info *p = ph->libs;
 436   while (p) {
 437     if (strcmp(p->name, lib_name) == 0) {
 438       return true;
 439     }
 440     p = p->next;
 441   }
 442   return false;
 443 }
 444 
 445 struct lib_info *find_lib_by_address(struct ps_prochandle* ph, uintptr_t pc) {
 446   lib_info *p = ph->libs;
 447   while (p) {
 448     if ((p->exec_start <= pc) && (pc < p->exec_end)) {
 449       return p;
 450     }
 451     p = p->next;
 452   }
 453   return NULL;
 454 }
 455 
 456 //--------------------------------------------------------------------------
 457 // proc service functions
 458 
 459 // get process id
 460 JNIEXPORT pid_t JNICALL
 461 ps_getpid(struct ps_prochandle *ph) {
 462    return ph->pid;
 463 }
 464 
 465 // ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
 466 // of the load object object_name in the target process identified by ph.
 467 // It returns the symbol's value as an address in the target process in
 468 // *sym_addr.
 469 
 470 JNIEXPORT ps_err_e JNICALL
 471 ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
 472                     const char *sym_name, psaddr_t *sym_addr) {
 473   *sym_addr = (psaddr_t) lookup_symbol(ph, object_name, sym_name);
 474   return (*sym_addr ? PS_OK : PS_NOSYM);
 475 }
 476 
 477 // read "size" bytes info "buf" from address "addr"
 478 JNIEXPORT ps_err_e JNICALL
 479 ps_pdread(struct ps_prochandle *ph, psaddr_t  addr,
 480                    void *buf, size_t size) {
 481   return ph->ops->p_pread(ph, (uintptr_t) addr, buf, size)? PS_OK: PS_ERR;
 482 }
 483 
 484 // write "size" bytes of data to debuggee at address "addr"
 485 JNIEXPORT ps_err_e JNICALL
 486 ps_pdwrite(struct ps_prochandle *ph, psaddr_t addr,
 487                     const void *buf, size_t size) {
 488   return ph->ops->p_pwrite(ph, (uintptr_t)addr, buf, size)? PS_OK: PS_ERR;
 489 }
 490 
 491 // ------------------------------------------------------------------------
 492 // Functions below this point are not yet implemented. They are here only
 493 // to make the linker happy.
 494 
 495 JNIEXPORT ps_err_e JNICALL
 496 ps_lsetfpregs(struct ps_prochandle *ph, lwpid_t lid, const prfpregset_t *fpregs) {
 497   print_debug("ps_lsetfpregs not implemented\n");
 498   return PS_OK;
 499 }
 500 
 501 JNIEXPORT ps_err_e JNICALL
 502 ps_lsetregs(struct ps_prochandle *ph, lwpid_t lid, const prgregset_t gregset) {
 503   print_debug("ps_lsetregs not implemented\n");
 504   return PS_OK;
 505 }
 506 
 507 JNIEXPORT ps_err_e  JNICALL
 508 ps_lgetfpregs(struct  ps_prochandle  *ph,  lwpid_t lid, prfpregset_t *fpregs) {
 509   print_debug("ps_lgetfpregs not implemented\n");
 510   return PS_OK;
 511 }
 512 
 513 JNIEXPORT ps_err_e JNICALL
 514 ps_lgetregs(struct ps_prochandle *ph, lwpid_t lid, prgregset_t gregset) {
 515   print_debug("ps_lgetfpregs not implemented\n");
 516   return PS_OK;
 517 }
 518