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