1 /*
   2  * Copyright (c) 2003, 2013, 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 #ifdef INCLUDE_SA_ATTACH
  26 
  27 #include <stdio.h>
  28 #include <stdlib.h>
  29 #include <string.h>
  30 #include <signal.h>
  31 #include <errno.h>
  32 #include <elf.h>
  33 #include <sys/types.h>
  34 #include <sys/wait.h>
  35 #include <sys/ptrace.h>
  36 #include <sys/uio.h>
  37 #include "libproc_impl.h"
  38 
  39 #if defined(x86_64) && !defined(amd64)
  40 #define amd64 1
  41 #endif
  42 
  43 #ifndef __WALL
  44 #define __WALL          0x40000000  // Copied from /usr/include/linux/wait.h
  45 #endif
  46 
  47 // This file has the libproc implementation specific to live process
  48 // For core files, refer to ps_core.c
  49 
  50 static inline uintptr_t align(uintptr_t ptr, size_t size) {
  51   return (ptr & ~(size - 1));
  52 }
  53 
  54 // ---------------------------------------------
  55 // ptrace functions
  56 // ---------------------------------------------
  57 
  58 // read "size" bytes of data from "addr" within the target process.
  59 // unlike the standard ptrace() function, process_read_data() can handle
  60 // unaligned address - alignment check, if required, should be done
  61 // before calling process_read_data.
  62 
  63 static bool process_read_data(struct ps_prochandle* ph, uintptr_t addr, char *buf, size_t size) {
  64   long rslt;
  65   size_t i, words;
  66   uintptr_t end_addr = addr + size;
  67   uintptr_t aligned_addr = align(addr, sizeof(long));
  68 
  69   if (aligned_addr != addr) {
  70     char *ptr = (char *)&rslt;
  71     errno = 0;
  72     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  73     if (errno) {
  74       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  75       return false;
  76     }
  77     for (; aligned_addr != addr; aligned_addr++, ptr++);
  78     for (; ((intptr_t)aligned_addr % sizeof(long)) && aligned_addr < end_addr;
  79         aligned_addr++)
  80        *(buf++) = *(ptr++);
  81   }
  82 
  83   words = (end_addr - aligned_addr) / sizeof(long);
  84 
  85   // assert((intptr_t)aligned_addr % sizeof(long) == 0);
  86   for (i = 0; i < words; i++) {
  87     errno = 0;
  88     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  89     if (errno) {
  90       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  91       return false;
  92     }
  93     *(long *)buf = rslt;
  94     buf += sizeof(long);
  95     aligned_addr += sizeof(long);
  96   }
  97 
  98   if (aligned_addr != end_addr) {
  99     char *ptr = (char *)&rslt;
 100     errno = 0;
 101     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
 102     if (errno) {
 103       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
 104       return false;
 105     }
 106     for (; aligned_addr != end_addr; aligned_addr++)
 107        *(buf++) = *(ptr++);
 108   }
 109   return true;
 110 }
 111 
 112 // null implementation for write
 113 static bool process_write_data(struct ps_prochandle* ph,
 114                              uintptr_t addr, const char *buf , size_t size) {
 115   return false;
 116 }
 117 
 118 // "user" should be a pointer to a user_regs_struct
 119 static bool process_get_lwp_regs(struct ps_prochandle* ph, pid_t pid, struct user_regs_struct *user) {
 120   // we have already attached to all thread 'pid's, just use ptrace call
 121   // to get regset now. Note that we don't cache regset upfront for processes.
 122 // Linux on x86 and sparc are different.  On x86 ptrace(PTRACE_GETREGS, ...)
 123 // uses pointer from 4th argument and ignores 3rd argument.  On sparc it uses
 124 // pointer from 3rd argument and ignores 4th argument
 125 #if defined(sparc) || defined(sparcv9)
 126 #define ptrace_getregs(request, pid, addr, data) ptrace(request, pid, addr, data)
 127 #else
 128 #define ptrace_getregs(request, pid, addr, data) ptrace(request, pid, data, addr)
 129 #endif
 130 
 131 #if defined(_LP64) && defined(PTRACE_GETREGS64)
 132 #define PTRACE_GETREGS_REQ PTRACE_GETREGS64
 133 #elif defined(PTRACE_GETREGS)
 134 #define PTRACE_GETREGS_REQ PTRACE_GETREGS
 135 #elif defined(PT_GETREGS)
 136 #define PTRACE_GETREGS_REQ PT_GETREGS
 137 #endif
 138 
 139 #ifdef PTRACE_GETREGS_REQ
 140  if (ptrace_getregs(PTRACE_GETREGS_REQ, pid, user, NULL) < 0) {
 141    print_debug("ptrace(PTRACE_GETREGS, ...) failed for lwp %d\n", pid);
 142    return false;
 143  }
 144  return true;
 145 #elif defined(PTRACE_GETREGSET)
 146  struct iovec iov;
 147  iov.iov_base = user;
 148  iov.iov_len = sizeof(*user);
 149  if (ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, (void*) &iov) < 0) {
 150    print_debug("ptrace(PTRACE_GETREGSET, ...) failed for lwp %d\n", pid);
 151    return false;
 152  }
 153  return true;
 154 #else
 155  print_debug("ptrace(PTRACE_GETREGS, ...) not supported\n");
 156  return false;
 157 #endif
 158 
 159 }
 160 
 161 static bool ptrace_continue(pid_t pid, int signal) {
 162   // pass the signal to the process so we don't swallow it
 163   if (ptrace(PTRACE_CONT, pid, NULL, signal) < 0) {
 164     print_debug("ptrace(PTRACE_CONT, ..) failed for %d\n", pid);
 165     return false;
 166   }
 167   return true;
 168 }
 169 
 170 // waits until the ATTACH has stopped the process
 171 // by signal SIGSTOP
 172 static bool ptrace_waitpid(pid_t pid) {
 173   int ret;
 174   int status;
 175   while (true) {
 176     // Wait for debuggee to stop.
 177     ret = waitpid(pid, &status, 0);
 178     if (ret == -1 && errno == ECHILD) {
 179       // try cloned process.
 180       ret = waitpid(pid, &status, __WALL);
 181     }
 182     if (ret >= 0) {
 183       if (WIFSTOPPED(status)) {
 184         // Any signal will stop the thread, make sure it is SIGSTOP. Otherwise SIGSTOP
 185         // will still be pending and delivered when the process is DETACHED and the process
 186         // will go to sleep.
 187         if (WSTOPSIG(status) == SIGSTOP) {
 188           // Debuggee stopped by SIGSTOP.
 189           return true;
 190         }
 191         if (!ptrace_continue(pid, WSTOPSIG(status))) {
 192           print_error("Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status));
 193           return false;
 194         }
 195       } else {
 196         print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
 197         return false;
 198       }
 199     } else {
 200       switch (errno) {
 201         case EINTR:
 202           continue;
 203           break;
 204         case ECHILD:
 205           print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
 206           break;
 207         case EINVAL:
 208           print_debug("waitpid() failed. Invalid options argument.\n");
 209           break;
 210         default:
 211           print_debug("waitpid() failed. Unexpected error %d\n",errno);
 212           break;
 213       }
 214       return false;
 215     }
 216   }
 217 }
 218 
 219 // attach to a process/thread specified by "pid"
 220 static bool ptrace_attach(pid_t pid, char* err_buf, size_t err_buf_len) {
 221   if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
 222     char buf[200];
 223     char* msg = strerror_r(errno, buf, sizeof(buf));
 224     snprintf(err_buf, err_buf_len, "ptrace(PTRACE_ATTACH, ..) failed for %d: %s", pid, msg);
 225     print_debug("%s\n", err_buf);
 226     return false;
 227   } else {
 228     return ptrace_waitpid(pid);
 229   }
 230 }
 231 
 232 // -------------------------------------------------------
 233 // functions for obtaining library information
 234 // -------------------------------------------------------
 235 
 236 /*
 237  * splits a string _str_ into substrings with delimiter _delim_ by replacing old * delimiters with _new_delim_ (ideally, '\0'). the address of each substring
 238  * is stored in array _ptrs_ as the return value. the maximum capacity of _ptrs_ * array is specified by parameter _n_.
 239  * RETURN VALUE: total number of substrings (always <= _n_)
 240  * NOTE: string _str_ is modified if _delim_!=_new_delim_
 241  */
 242 static int split_n_str(char * str, int n, char ** ptrs, char delim, char new_delim)
 243 {
 244    int i;
 245    for(i = 0; i < n; i++) ptrs[i] = NULL;
 246    if (str == NULL || n < 1 ) return 0;
 247 
 248    i = 0;
 249 
 250    // skipping leading blanks
 251    while(*str&&*str==delim) str++;
 252 
 253    while(*str&&i<n){
 254      ptrs[i++] = str;
 255      while(*str&&*str!=delim) str++;
 256      while(*str&&*str==delim) *(str++) = new_delim;
 257    }
 258 
 259    return i;
 260 }
 261 
 262 /*
 263  * fgets without storing '\n' at the end of the string
 264  */
 265 static char * fgets_no_cr(char * buf, int n, FILE *fp)
 266 {
 267    char * rslt = fgets(buf, n, fp);
 268    if (rslt && buf && *buf){
 269        char *p = strchr(buf, '\0');
 270        if (*--p=='\n') *p='\0';
 271    }
 272    return rslt;
 273 }
 274 
 275 // callback for read_thread_info
 276 static bool add_new_thread(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
 277   return add_thread_info(ph, pthread_id, lwp_id) != NULL;
 278 }
 279 
 280 static bool read_lib_info(struct ps_prochandle* ph) {
 281   char fname[32];
 282   char buf[PATH_MAX];
 283   FILE *fp = NULL;
 284 
 285   sprintf(fname, "/proc/%d/maps", ph->pid);
 286   fp = fopen(fname, "r");
 287   if (fp == NULL) {
 288     print_debug("can't open /proc/%d/maps file\n", ph->pid);
 289     return false;
 290   }
 291 
 292   while(fgets_no_cr(buf, PATH_MAX, fp)){
 293     char * word[7];
 294     int nwords = split_n_str(buf, 7, word, ' ', '\0');
 295 
 296     if (nwords < 6) {
 297       // not a shared library entry. ignore.
 298       continue;
 299     }
 300 
 301     // SA does not handle the lines with patterns:
 302     //   "[stack]", "[heap]", "[vdso]", "[vsyscall]", etc.
 303     if (word[5][0] == '[') {
 304         // not a shared library entry. ignore.
 305         continue;
 306     }
 307 
 308     if (nwords > 6) {
 309       // prelink altered mapfile when the program is running.
 310       // Entries like one below have to be skipped
 311       //  /lib64/libc-2.15.so (deleted)
 312       // SO name in entries like one below have to be stripped.
 313       //  /lib64/libpthread-2.15.so.#prelink#.EECVts
 314       char *s = strstr(word[5],".#prelink#");
 315       if (s == NULL) {
 316         // No prelink keyword. skip deleted library
 317         print_debug("skip shared object %s deleted by prelink\n", word[5]);
 318         continue;
 319       }
 320 
 321       // Fall through
 322       print_debug("rectifying shared object name %s changed by prelink\n", word[5]);
 323       *s = 0;
 324     }
 325 
 326     if (find_lib(ph, word[5]) == false) {
 327        intptr_t base;
 328        lib_info* lib;
 329 #ifdef _LP64
 330        sscanf(word[0], "%lx", &base);
 331 #else
 332        sscanf(word[0], "%x", &base);
 333 #endif
 334        if ((lib = add_lib_info(ph, word[5], (uintptr_t)base)) == NULL)
 335           continue; // ignore, add_lib_info prints error
 336 
 337        // we don't need to keep the library open, symtab is already
 338        // built. Only for core dump we need to keep the fd open.
 339        close(lib->fd);
 340        lib->fd = -1;
 341     }
 342   }
 343   fclose(fp);
 344   return true;
 345 }
 346 
 347 // detach a given pid
 348 static bool ptrace_detach(pid_t pid) {
 349   if (pid && ptrace(PTRACE_DETACH, pid, NULL, NULL) < 0) {
 350     print_debug("ptrace(PTRACE_DETACH, ..) failed for %d\n", pid);
 351     return false;
 352   } else {
 353     return true;
 354   }
 355 }
 356 
 357 // detach all pids of a ps_prochandle
 358 static void detach_all_pids(struct ps_prochandle* ph) {
 359   thread_info* thr = ph->threads;
 360   while (thr) {
 361      ptrace_detach(thr->lwp_id);
 362      thr = thr->next;
 363   }
 364 }
 365 
 366 static void process_cleanup(struct ps_prochandle* ph) {
 367   detach_all_pids(ph);
 368 }
 369 
 370 static ps_prochandle_ops process_ops = {
 371   .release=  process_cleanup,
 372   .p_pread=  process_read_data,
 373   .p_pwrite= process_write_data,
 374   .get_lwp_regs= process_get_lwp_regs
 375 };
 376 
 377 // attach to the process. One and only one exposed stuff
 378 struct ps_prochandle* Pgrab(pid_t pid, char* err_buf, size_t err_buf_len) {
 379   struct ps_prochandle* ph = NULL;
 380   thread_info* thr = NULL;
 381 
 382   if ( (ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle))) == NULL) {
 383      snprintf(err_buf, err_buf_len, "can't allocate memory for ps_prochandle");
 384      print_debug("%s\n", err_buf);
 385      return NULL;
 386   }
 387 
 388   if (ptrace_attach(pid, err_buf, err_buf_len) != true) {
 389      free(ph);
 390      return NULL;
 391   }
 392 
 393   // initialize ps_prochandle
 394   ph->pid = pid;
 395 
 396   // initialize vtable
 397   ph->ops = &process_ops;
 398 
 399   // read library info and symbol tables, must do this before attaching threads,
 400   // as the symbols in the pthread library will be used to figure out
 401   // the list of threads within the same process.
 402   read_lib_info(ph);
 403 
 404   // read thread info
 405   read_thread_info(ph, add_new_thread);
 406 
 407   // attach to the threads
 408   thr = ph->threads;
 409   while (thr) {
 410      // don't attach to the main thread again
 411     if (ph->pid != thr->lwp_id && ptrace_attach(thr->lwp_id, err_buf, err_buf_len) != true) {
 412         // even if one attach fails, we get return NULL
 413         Prelease(ph);
 414         return NULL;
 415      }
 416      thr = thr->next;
 417   }
 418   return ph;
 419 }
 420 
 421 #endif // INCLUDE_SA_ATTACH