1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)ps_proc.c    1.17 07/05/05 17:02:02 JVM"
   3 #endif
   4 /*
   5  * Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 #include <stdio.h>
  29 #include <stdlib.h>
  30 #include <string.h>
  31 #include <errno.h>
  32 #include <sys/ptrace.h>
  33 #include "libproc_impl.h"
  34 
  35 #if defined(x86_64) && !defined(amd64)
  36 #define amd64 1
  37 #endif
  38 
  39 #ifndef __WALL
  40 #define __WALL          0x40000000  // Copied from /usr/include/linux/wait.h
  41 #endif 
  42 
  43 // This file has the libproc implementation specific to live process
  44 // For core files, refer to ps_core.c
  45 
  46 static inline uintptr_t align(uintptr_t ptr, size_t size) {
  47   return (ptr & ~(size - 1));
  48 }
  49 
  50 // ---------------------------------------------
  51 // ptrace functions
  52 // ---------------------------------------------
  53 
  54 // read "size" bytes of data from "addr" within the target process.
  55 // unlike the standard ptrace() function, process_read_data() can handle
  56 // unaligned address - alignment check, if required, should be done 
  57 // before calling process_read_data.
  58 
  59 static bool process_read_data(struct ps_prochandle* ph, uintptr_t addr, char *buf, size_t size) {
  60   long rslt;
  61   size_t i, words;
  62   uintptr_t end_addr = addr + size;
  63   uintptr_t aligned_addr = align(addr, sizeof(long));
  64 
  65   if (aligned_addr != addr) {
  66     char *ptr = (char *)&rslt;
  67     errno = 0;
  68     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  69     if (errno) {
  70       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  71       return false;
  72     }
  73     for (; aligned_addr != addr; aligned_addr++, ptr++);
  74     for (; ((intptr_t)aligned_addr % sizeof(long)) && aligned_addr < end_addr; 
  75         aligned_addr++) 
  76        *(buf++) = *(ptr++);
  77   }
  78 
  79   words = (end_addr - aligned_addr) / sizeof(long);
  80 
  81   // assert((intptr_t)aligned_addr % sizeof(long) == 0);
  82   for (i = 0; i < words; i++) {
  83     errno = 0;
  84     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  85     if (errno) { 
  86       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  87       return false;
  88     }
  89     *(long *)buf = rslt;
  90     buf += sizeof(long);
  91     aligned_addr += sizeof(long);
  92   }
  93 
  94   if (aligned_addr != end_addr) {
  95     char *ptr = (char *)&rslt;
  96     errno = 0;
  97     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  98     if (errno) {
  99       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
 100       return false;
 101     }
 102     for (; aligned_addr != end_addr; aligned_addr++) 
 103        *(buf++) = *(ptr++);
 104   }
 105   return true;
 106 }
 107 
 108 // null implementation for write
 109 static bool process_write_data(struct ps_prochandle* ph, 
 110                              uintptr_t addr, const char *buf , size_t size) {
 111   return false;
 112 }
 113 
 114 // "user" should be a pointer to a user_regs_struct
 115 static bool process_get_lwp_regs(struct ps_prochandle* ph, pid_t pid, struct user_regs_struct *user) {
 116   // we have already attached to all thread 'pid's, just use ptrace call
 117   // to get regset now. Note that we don't cache regset upfront for processes.
 118 // Linux on x86 and sparc are different.  On x86 ptrace(PTRACE_GETREGS, ...)
 119 // uses pointer from 4th argument and ignores 3rd argument.  On sparc it uses
 120 // pointer from 3rd argument and ignores 4th argument
 121 #if defined(sparc) || defined(sparcv9)
 122 #define ptrace_getregs(request, pid, addr, data) ptrace(request, pid, addr, data)
 123 #else
 124 #define ptrace_getregs(request, pid, addr, data) ptrace(request, pid, data, addr)
 125 #endif
 126 
 127 #ifdef _LP64
 128 #ifdef PTRACE_GETREGS64
 129 #define PTRACE_GETREGS_REQ PTRACE_GETREGS64
 130 #endif
 131 #else
 132 #if defined(PTRACE_GETREGS) || defined(PT_GETREGS)
 133 #define PTRACE_GETREGS_REQ PTRACE_GETREGS
 134 #endif
 135 #endif /* _LP64 */
 136 
 137 #ifdef PTRACE_GETREGS_REQ
 138  if (ptrace_getregs(PTRACE_GETREGS_REQ, pid, user, NULL) < 0) {
 139    print_debug("ptrace(PTRACE_GETREGS, ...) failed for lwp %d\n", pid);
 140    return false;
 141  }
 142  return true;
 143 #else
 144  print_debug("ptrace(PTRACE_GETREGS, ...) not supported\n");
 145  return false;
 146 #endif 
 147 
 148 }
 149 
 150 // attach to a process/thread specified by "pid"
 151 static bool ptrace_attach(pid_t pid) {
 152   if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
 153     print_debug("ptrace(PTRACE_ATTACH, ..) failed for %d\n", pid);
 154     return false;
 155   } else {
 156     int ret;
 157     int status;
 158     do {
 159       // Wait for debuggee to stop. 
 160       ret = waitpid(pid, &status, 0);
 161       if (ret == -1 && errno == ECHILD) {
 162         // try cloned process.
 163         ret = waitpid(pid, &status, __WALL);
 164       }
 165       if (ret >= 0) {
 166         if (WIFSTOPPED(status)) {
 167           // Debuggee stopped.
 168           return true;
 169         } else {
 170           print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
 171           return false;
 172         }
 173       } else {
 174         switch (errno) {
 175           case EINTR: 
 176             continue;
 177             break;
 178           case ECHILD:
 179             print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
 180             break;
 181           case EINVAL:
 182             print_debug("waitpid() failed. Invalid options argument.\n");
 183             break;
 184           default:
 185             print_debug("waitpid() failed. Unexpected error %d\n",errno);
 186         }
 187         return false;
 188       } 
 189     } while(true);
 190   } 
 191 } 
 192   
 193 // -------------------------------------------------------
 194 // functions for obtaining library information
 195 // -------------------------------------------------------
 196 
 197 /*
 198  * splits a string _str_ into substrings with delimiter _delim_ by replacing old * delimiters with _new_delim_ (ideally, '\0'). the address of each substring
 199  * is stored in array _ptrs_ as the return value. the maximum capacity of _ptrs_ * array is specified by parameter _n_.
 200  * RETURN VALUE: total number of substrings (always <= _n_)
 201  * NOTE: string _str_ is modified if _delim_!=_new_delim_
 202  */
 203 static int split_n_str(char * str, int n, char ** ptrs, char delim, char new_delim)
 204 {
 205    int i;
 206    for(i = 0; i < n; i++) ptrs[i] = NULL;
 207    if (str == NULL || n < 1 ) return 0;
 208    
 209    i = 0;
 210 
 211    // skipping leading blanks
 212    while(*str&&*str==delim) str++;
 213    
 214    while(*str&&i<n){
 215      ptrs[i++] = str;
 216      while(*str&&*str!=delim) str++;
 217      while(*str&&*str==delim) *(str++) = new_delim;
 218    }
 219    
 220    return i;
 221 }
 222 
 223 /*
 224  * fgets without storing '\n' at the end of the string
 225  */
 226 static char * fgets_no_cr(char * buf, int n, FILE *fp)
 227 {
 228    char * rslt = fgets(buf, n, fp);
 229    if (rslt && buf && *buf){
 230        char *p = strchr(buf, '\0');
 231        if (*--p=='\n') *p='\0';
 232    }
 233    return rslt;
 234 }
 235 
 236 // callback for read_thread_info
 237 static bool add_new_thread(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
 238   return add_thread_info(ph, pthread_id, lwp_id) != NULL;
 239 }
 240 
 241 static bool read_lib_info(struct ps_prochandle* ph) {
 242   char fname[32];
 243   char buf[256];
 244   FILE *fp = NULL;
 245 
 246   sprintf(fname, "/proc/%d/maps", ph->pid);
 247   fp = fopen(fname, "r");
 248   if (fp == NULL) {
 249     print_debug("can't open /proc/%d/maps file\n", ph->pid);
 250     return false;
 251   }
 252 
 253   while(fgets_no_cr(buf, 256, fp)){
 254     char * word[6];
 255     int nwords = split_n_str(buf, 6, word, ' ', '\0');
 256     if (nwords > 5 && find_lib(ph, word[5]) == false) {
 257        intptr_t base;
 258        lib_info* lib;
 259        sscanf(word[0], "%lx", &base);
 260        if ((lib = add_lib_info(ph, word[5], (uintptr_t)base)) == NULL)
 261           continue; // ignore, add_lib_info prints error
 262 
 263        // we don't need to keep the library open, symtab is already
 264        // built. Only for core dump we need to keep the fd open.
 265        close(lib->fd);
 266        lib->fd = -1;
 267     }
 268   }
 269   fclose(fp);
 270   return true;
 271 }
 272 
 273 // detach a given pid
 274 static bool ptrace_detach(pid_t pid) {
 275   if (pid && ptrace(PTRACE_DETACH, pid, NULL, NULL) < 0) {
 276     print_debug("ptrace(PTRACE_DETACH, ..) failed for %d\n", pid);
 277     return false;
 278   } else {
 279     return true;
 280   } 
 281 }
 282 
 283 // detach all pids of a ps_prochandle
 284 static void detach_all_pids(struct ps_prochandle* ph) {
 285   thread_info* thr = ph->threads;
 286   while (thr) {
 287      ptrace_detach(thr->lwp_id);
 288      thr = thr->next;
 289   }
 290 }
 291 
 292 static void process_cleanup(struct ps_prochandle* ph) {
 293   detach_all_pids(ph);
 294 }
 295 
 296 static ps_prochandle_ops process_ops = {
 297   release:  process_cleanup,
 298   p_pread:  process_read_data,
 299   p_pwrite: process_write_data,
 300   get_lwp_regs: process_get_lwp_regs
 301 };
 302 
 303 // attach to the process. One and only one exposed stuff
 304 struct ps_prochandle* Pgrab(pid_t pid) {
 305   struct ps_prochandle* ph = NULL;
 306   thread_info* thr = NULL;
 307 
 308   if ( (ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle))) == NULL) {
 309      print_debug("can't allocate memory for ps_prochandle\n");
 310      return NULL;
 311   }
 312 
 313   if (ptrace_attach(pid) != true) {
 314      free(ph);
 315      return NULL;
 316   }
 317 
 318   // initialize ps_prochandle
 319   ph->pid = pid;
 320 
 321   // initialize vtable
 322   ph->ops = &process_ops;
 323 
 324   // read library info and symbol tables, must do this before attaching threads,
 325   // as the symbols in the pthread library will be used to figure out
 326   // the list of threads within the same process.
 327   read_lib_info(ph);
 328  
 329   // read thread info
 330   read_thread_info(ph, add_new_thread);
 331 
 332   // attach to the threads
 333   thr = ph->threads;
 334   while (thr) {
 335      // don't attach to the main thread again
 336      if (ph->pid != thr->lwp_id && ptrace_attach(thr->lwp_id) != true) {
 337         // even if one attach fails, we get return NULL
 338         Prelease(ph);
 339         return NULL;
 340      }
 341      thr = thr->next;
 342   }
 343   return ph;
 344 }