1 /*
   2  * Copyright (c) 2003, 2010, 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 
  25 #include <limits.h>
  26 #include <stdio.h>
  27 #include <stdlib.h>
  28 #include <string.h>
  29 #include <errno.h>
  30 #include <sys/types.h>
  31 #include <sys/wait.h>
  32 #include <sys/ptrace.h>
  33 #include <sys/param.h>
  34 #include <sys/user.h>
  35 #include <elf.h>
  36 #include <sys/elf_common.h>
  37 #include <sys/link_elf.h>
  38 #include <libutil.h>
  39 #include "libproc_impl.h"
  40 #include "elfmacros.h"
  41 
  42 // This file has the libproc implementation specific to live process
  43 // For core files, refer to ps_core.c
  44 
  45 static inline uintptr_t align(uintptr_t ptr, size_t size) {
  46   return (ptr & ~(size - 1));
  47 }
  48 
  49 // ---------------------------------------------
  50 // ptrace functions
  51 // ---------------------------------------------
  52 
  53 // read "size" bytes of data from "addr" within the target process.
  54 // unlike the standard ptrace() function, process_read_data() can handle
  55 // unaligned address - alignment check, if required, should be done
  56 // before calling process_read_data.
  57 
  58 static bool process_read_data(struct ps_prochandle* ph, uintptr_t addr, char *buf, size_t size) {
  59   int rslt;
  60   size_t i, words;
  61   uintptr_t end_addr = addr + size;
  62   uintptr_t aligned_addr = align(addr, sizeof(int));
  63 
  64   if (aligned_addr != addr) {
  65     char *ptr = (char *)&rslt;
  66     errno = 0;
  67     rslt = ptrace(PT_READ_D, ph->pid, (caddr_t) aligned_addr, 0);
  68     if (errno) {
  69       print_debug("ptrace(PT_READ_D, ..) failed for %d bytes @ %lx\n", size, addr);
  70       return false;
  71     }
  72     for (; aligned_addr != addr; aligned_addr++, ptr++);
  73     for (; ((intptr_t)aligned_addr % sizeof(int)) && aligned_addr < end_addr;
  74         aligned_addr++)
  75        *(buf++) = *(ptr++);
  76   }
  77 
  78   words = (end_addr - aligned_addr) / sizeof(int);
  79 
  80   // assert((intptr_t)aligned_addr % sizeof(int) == 0);
  81   for (i = 0; i < words; i++) {
  82     errno = 0;
  83     rslt = ptrace(PT_READ_D, ph->pid, (caddr_t) aligned_addr, 0);
  84     if (errno) {
  85       print_debug("ptrace(PT_READ_D, ..) failed for %d bytes @ %lx\n", size, addr);
  86       return false;
  87     }
  88     *(int *)buf = rslt;
  89     buf += sizeof(int);
  90     aligned_addr += sizeof(int);
  91   }
  92 
  93   if (aligned_addr != end_addr) {
  94     char *ptr = (char *)&rslt;
  95     errno = 0;
  96     rslt = ptrace(PT_READ_D, ph->pid, (caddr_t) aligned_addr, 0);
  97     if (errno) {
  98       print_debug("ptrace(PT_READ_D, ..) failed for %d bytes @ %lx\n", size, addr);
  99       return false;
 100     }
 101     for (; aligned_addr != end_addr; aligned_addr++)
 102        *(buf++) = *(ptr++);
 103   }
 104   return true;
 105 }
 106 
 107 // null implementation for write
 108 static bool process_write_data(struct ps_prochandle* ph,
 109                              uintptr_t addr, const char *buf , size_t size) {
 110   return false;
 111 }
 112 
 113 // "user" should be a pointer to a reg
 114 static bool process_get_lwp_regs(struct ps_prochandle* ph, pid_t pid, struct reg *user) {
 115   // we have already attached to all thread 'pid's, just use ptrace call
 116   // to get regset now. Note that we don't cache regset upfront for processes.
 117  if (ptrace(PT_GETREGS, pid, (caddr_t) user, 0) < 0) {
 118    print_debug("ptrace(PTRACE_GETREGS, ...) failed for lwp %d\n", pid);
 119    return false;
 120  }
 121  return true;
 122 }
 123 
 124 // fill in ptrace_lwpinfo for lid
 125 static bool process_get_lwp_info(struct ps_prochandle *ph, lwpid_t lwp_id, void *linfo) {
 126   errno = 0;
 127   ptrace(PT_LWPINFO, lwp_id, linfo, sizeof(struct ptrace_lwpinfo));
 128 
 129   return (errno == 0)? true: false;
 130 }
 131 
 132 // attach to a process/thread specified by "pid"
 133 static bool ptrace_attach(pid_t pid) {
 134   if (ptrace(PT_ATTACH, pid, NULL, 0) < 0) {
 135     print_debug("ptrace(PTRACE_ATTACH, ..) failed for %d\n", pid);
 136     return false;
 137   } else {
 138     int ret;
 139     int status;
 140     do {
 141       // Wait for debuggee to stop.
 142       ret = waitpid(pid, &status, 0);
 143       if (ret >= 0) {
 144         if (WIFSTOPPED(status)) {
 145           // Debuggee stopped.
 146           return true;
 147         } else {
 148           print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
 149           return false;
 150         }
 151       } else {
 152         switch (errno) {
 153           case EINTR:
 154             continue;
 155             break;
 156           case ECHILD:
 157             print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
 158             break;
 159           case EINVAL:
 160             print_debug("waitpid() failed. Invalid options argument.\n");
 161             break;
 162           default:
 163             print_debug("waitpid() failed. Unexpected error %d\n",errno);
 164         }
 165         return false;
 166       }
 167     } while(true);
 168   }
 169 }
 170 
 171 // -------------------------------------------------------
 172 // functions for obtaining library information
 173 // -------------------------------------------------------
 174 
 175 // callback for read_thread_info
 176 static bool add_new_thread(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
 177   return add_thread_info(ph, pthread_id, lwp_id) != NULL;
 178 }
 179 
 180 #if defined(__FreeBSD__) && __FreeBSD_version < 701000
 181 /*
 182  * TEXT_START_ADDR from binutils/ld/emulparams/<arch_spec>.sh
 183  * Not the most robust but good enough.
 184  */
 185 
 186 #if defined(amd64) || defined(x86_64)
 187 #define TEXT_START_ADDR 0x400000
 188 #elif defined(i386)
 189 #define TEXT_START_ADDR 0x8048000
 190 #else
 191 #error TEXT_START_ADDR not defined
 192 #endif
 193 
 194 #define BUF_SIZE (PATH_MAX + NAME_MAX + 1)
 195 
 196 uintptr_t linkmap_addr(struct ps_prochandle *ph) {
 197   uintptr_t ehdr_addr, phdr_addr, dyn_addr, dmap_addr, lmap_addr;
 198   ELF_EHDR ehdr;
 199   ELF_PHDR *phdrs, *phdr;
 200   ELF_DYN *dyns, *dyn;
 201   struct r_debug dmap;
 202   unsigned long hdrs_size;
 203   unsigned int i;
 204 
 205   /* read ELF_EHDR at TEXT_START_ADDR and validate */
 206 
 207   ehdr_addr = (uintptr_t)TEXT_START_ADDR;
 208 
 209   if (process_read_data(ph, ehdr_addr, (char *)&ehdr, sizeof(ehdr)) != true) {
 210     print_debug("process_read_data failed for ehdr_addr %p\n", ehdr_addr);
 211     return (0);
 212   }
 213 
 214   if (!IS_ELF(ehdr) ||
 215         ehdr.e_ident[EI_CLASS] != ELF_TARG_CLASS ||
 216         ehdr.e_ident[EI_DATA] != ELF_TARG_DATA ||
 217         ehdr.e_ident[EI_VERSION] != EV_CURRENT ||
 218         ehdr.e_phentsize != sizeof(ELF_PHDR) ||
 219         ehdr.e_version != ELF_TARG_VER ||
 220         ehdr.e_machine != ELF_TARG_MACH) {
 221     print_debug("not an ELF_EHDR at %p\n", ehdr_addr);
 222     return (0);
 223   }
 224 
 225   /* allocate space for all ELF_PHDR's and read */
 226 
 227   phdr_addr = ehdr_addr + ehdr.e_phoff;
 228   hdrs_size = ehdr.e_phnum * sizeof(ELF_PHDR);
 229 
 230   if ((phdrs = malloc(hdrs_size)) == NULL)
 231     return (0);
 232 
 233   if (process_read_data(ph, phdr_addr, (char *)phdrs, hdrs_size) != true) {
 234     print_debug("process_read_data failed for phdr_addr %p\n", phdr_addr);
 235     return (0);
 236   }
 237 
 238   /* find PT_DYNAMIC section */
 239 
 240   for (i = 0, phdr = phdrs; i < ehdr.e_phnum; i++, phdr++) {
 241     if (phdr->p_type == PT_DYNAMIC)
 242       break;
 243   }
 244 
 245   if (i >= ehdr.e_phnum) {
 246     print_debug("PT_DYNAMIC section not found!\n");
 247     free(phdrs);
 248     return (0);
 249   }
 250 
 251   /* allocate space and read in ELF_DYN headers */
 252 
 253   dyn_addr = phdr->p_vaddr;
 254   hdrs_size = phdr->p_memsz;
 255   free(phdrs);
 256 
 257   if ((dyns = malloc(hdrs_size)) == NULL)
 258     return (0);
 259 
 260   if (process_read_data(ph, dyn_addr, (char *)dyns, hdrs_size) != true) {
 261     print_debug("process_read_data failed for dyn_addr %p\n", dyn_addr);
 262     free(dyns);
 263     return (0);
 264   }
 265 
 266   /* find DT_DEBUG */
 267 
 268   dyn = dyns;
 269   while (dyn->d_tag != DT_DEBUG && dyn->d_tag != DT_NULL) {
 270     dyn++;
 271   }
 272 
 273   if (dyn->d_tag != DT_DEBUG) {
 274     print_debug("failed to find DT_DEBUG\n");
 275     free(dyns);
 276     return (0);
 277   }
 278 
 279   /* read struct r_debug into dmap */
 280 
 281   dmap_addr = (uintptr_t)dyn->d_un.d_ptr;
 282   free(dyns);
 283 
 284   if (process_read_data(ph, dmap_addr, (char *)&dmap, sizeof(dmap)) != true) {
 285     print_debug("process_read_data failed for dmap_addr %p\n", dmap_addr);
 286     return (0);
 287   }
 288 
 289   lmap_addr = (uintptr_t)dmap.r_map;
 290 
 291   return (lmap_addr);
 292 }
 293 #endif // __FreeBSD__ && __FreeBSD_version < 701000
 294 
 295 static bool read_lib_info(struct ps_prochandle* ph) {
 296 #if defined(__FreeBSD__) && __FreeBSD_version >= 701000
 297   struct kinfo_vmentry *freep, *kve;
 298   int i, cnt;
 299 
 300   freep = kinfo_getvmmap(ph->pid, &cnt);
 301   if (freep == NULL) {
 302       print_debug("can't get vm map for pid\n", ph->pid);
 303       return false;
 304   }
 305 
 306   for (i = 0; i < cnt; i++) {
 307     kve = &freep[i];
 308     if ((kve->kve_flags & KVME_FLAG_COW) &&
 309         kve->kve_path != NULL &&
 310         strlen(kve->kve_path) > 0) {
 311 
 312       if (find_lib(ph, kve->kve_path) == false) {
 313         lib_info* lib;
 314         if ((lib = add_lib_info(ph, kve->kve_path,
 315                                 (uintptr_t) kve->kve_start)) == NULL)
 316           continue; // ignore, add_lib_info prints error
 317 
 318         // we don't need to keep the library open, symtab is already
 319         // built. Only for core dump we need to keep the fd open.
 320         close(lib->fd);
 321         lib->fd = -1;
 322       }
 323     }
 324   }
 325 
 326   free(freep);
 327 
 328   return true;
 329 #else
 330   char *l_name;
 331   struct link_map *lmap;
 332   uintptr_t lmap_addr;
 333 
 334   if ((l_name = malloc(BUF_SIZE)) == NULL)
 335     return false;
 336 
 337   if ((lmap = malloc(sizeof(*lmap))) == NULL) {
 338     free(l_name);
 339     return false;
 340   }
 341 
 342   lmap_addr = linkmap_addr(ph);
 343 
 344   if (lmap_addr == 0) {
 345     free(l_name);
 346     free(lmap);
 347     return false;
 348   }
 349 
 350   do {
 351     if (process_read_data(ph, lmap_addr, (char *)lmap, sizeof(*lmap)) != true) {
 352       print_debug("process_read_data failed for lmap_addr %p\n", lmap_addr);
 353       free (l_name);
 354       free (lmap);
 355       return false;
 356     }
 357 
 358     if (process_read_data(ph, (uintptr_t)lmap->l_name, l_name,
 359         BUF_SIZE) != true) {
 360       print_debug("process_read_data failed for lmap->l_name %p\n",
 361           lmap->l_name);
 362       free (l_name);
 363       free (lmap);
 364       return false;
 365     }
 366 
 367     if (find_lib(ph, l_name) == false) {
 368       lib_info* lib;
 369       if ((lib = add_lib_info(ph, l_name,
 370                               (uintptr_t) lmap->l_addr)) == NULL)
 371         continue; // ignore, add_lib_info prints error
 372 
 373       // we don't need to keep the library open, symtab is already
 374       // built. Only for core dump we need to keep the fd open.
 375       close(lib->fd);
 376       lib->fd = -1;
 377     }
 378     lmap_addr = (uintptr_t)lmap->l_next;
 379   } while (lmap->l_next != NULL);
 380 
 381   free (l_name);
 382   free (lmap);
 383 
 384   return true;
 385 #endif
 386 }
 387 
 388 // detach a given pid
 389 static bool ptrace_detach(pid_t pid) {
 390   if (pid && ptrace(PT_DETACH, pid, (caddr_t)1, 0) < 0) {
 391     print_debug("ptrace(PTRACE_DETACH, ..) failed for %d\n", pid);
 392     return false;
 393   } else {
 394     return true;
 395   }
 396 }
 397 
 398 static void process_cleanup(struct ps_prochandle* ph) {
 399   ptrace_detach(ph->pid);
 400 }
 401 
 402 static ps_prochandle_ops process_ops = {
 403   .release=  process_cleanup,
 404   .p_pread=  process_read_data,
 405   .p_pwrite= process_write_data,
 406   .get_lwp_regs= process_get_lwp_regs,
 407   .get_lwp_info= process_get_lwp_info
 408 };
 409 
 410 // attach to the process. One and only one exposed stuff
 411 struct ps_prochandle* Pgrab(pid_t pid) {
 412   struct ps_prochandle* ph = NULL;
 413   thread_info* thr = NULL;
 414 
 415   if ( (ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle))) == NULL) {
 416      print_debug("can't allocate memory for ps_prochandle\n");
 417      return NULL;
 418   }
 419 
 420   if (ptrace_attach(pid) != true) {
 421      free(ph);
 422      return NULL;
 423   }
 424 
 425   // initialize ps_prochandle
 426   ph->pid = pid;
 427 
 428   // initialize vtable
 429   ph->ops = &process_ops;
 430 
 431   // read library info and symbol tables, must do this before attaching threads,
 432   // as the symbols in the pthread library will be used to figure out
 433   // the list of threads within the same process.
 434   if (read_lib_info(ph) != true) {
 435      ptrace_detach(pid);
 436      free(ph);
 437      return NULL;
 438   }
 439 
 440   // read thread info
 441   read_thread_info(ph, add_new_thread);
 442 
 443   return ph;
 444 }