Mirror of strace – the linux syscall tracer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

strace.c 74KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053
  1. /*
  2. * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
  3. * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
  4. * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
  5. * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
  6. * Copyright (c) 1999-2019 The strace developers.
  7. * All rights reserved.
  8. *
  9. * SPDX-License-Identifier: LGPL-2.1-or-later
  10. */
  11. #include "defs.h"
  12. #include <stdarg.h>
  13. #include <limits.h>
  14. #include <fcntl.h>
  15. #include "ptrace.h"
  16. #include <signal.h>
  17. #include <sys/resource.h>
  18. #include <sys/stat.h>
  19. #ifdef HAVE_PATHS_H
  20. # include <paths.h>
  21. #endif
  22. #include <getopt.h>
  23. #include <pwd.h>
  24. #include <grp.h>
  25. #include <dirent.h>
  26. #include <locale.h>
  27. #include <sys/utsname.h>
  28. #ifdef HAVE_PRCTL
  29. # include <sys/prctl.h>
  30. #endif
  31. #include "kill_save_errno.h"
  32. #include "filter_seccomp.h"
  33. #include "largefile_wrappers.h"
  34. #include "mmap_cache.h"
  35. #include "number_set.h"
  36. #include "ptrace_syscall_info.h"
  37. #include "scno.h"
  38. #include "printsiginfo.h"
  39. #include "trace_event.h"
  40. #include "xstring.h"
  41. #include "delay.h"
  42. #include "wait.h"
  43. /* In some libc, these aren't declared. Do it ourself: */
  44. extern char **environ;
  45. extern int optind;
  46. extern char *optarg;
  47. #ifdef ENABLE_STACKTRACE
  48. /* if this is true do the stack trace for every system call */
  49. bool stack_trace_enabled;
  50. #endif
  51. #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
  52. /* Glue for systems without a MMU that cannot provide fork() */
  53. #if !defined(HAVE_FORK)
  54. # undef NOMMU_SYSTEM
  55. # define NOMMU_SYSTEM 1
  56. #endif
  57. #if NOMMU_SYSTEM
  58. # define fork() vfork()
  59. #endif
  60. const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
  61. cflag_t cflag = CFLAG_NONE;
  62. unsigned int followfork;
  63. unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
  64. | PTRACE_O_TRACEEXIT;
  65. unsigned int xflag;
  66. bool debug_flag;
  67. bool Tflag;
  68. bool iflag;
  69. bool count_wallclock;
  70. unsigned int qflag;
  71. static unsigned int tflag;
  72. static bool rflag;
  73. static bool print_pid_pfx;
  74. /* -I n */
  75. enum {
  76. INTR_NOT_SET = 0,
  77. INTR_ANYWHERE = 1, /* don't block/ignore any signals */
  78. INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
  79. INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
  80. INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z); default if -D */
  81. NUM_INTR_OPTS
  82. };
  83. static int opt_intr;
  84. /* We play with signal mask only if this mode is active: */
  85. #define interactive (opt_intr == INTR_WHILE_WAIT)
  86. enum {
  87. DAEMONIZE_NONE = 0,
  88. DAEMONIZE_GRANDCHILD = 1,
  89. DAEMONIZE_NEW_PGROUP = 2,
  90. DAEMONIZE_NEW_SESSION = 3,
  91. DAEMONIZE_OPTS_GUARD__,
  92. MAX_DAEMONIZE_OPTS = DAEMONIZE_OPTS_GUARD__ - 1
  93. };
  94. /*
  95. * daemonized_tracer supports -D option.
  96. * With this option, strace forks twice.
  97. * Unlike normal case, with -D *grandparent* process exec's,
  98. * becoming a traced process. Child exits (this prevents traced process
  99. * from having children it doesn't expect to have), and grandchild
  100. * attaches to grandparent similarly to strace -p PID.
  101. * This allows for more transparent interaction in cases
  102. * when process and its parent are communicating via signals,
  103. * wait() etc. Without -D, strace process gets lodged in between,
  104. * disrupting parent<->child link.
  105. */
  106. static unsigned int daemonized_tracer;
  107. static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
  108. #define use_seize (post_attach_sigstop == 0)
  109. /* Show path associated with fd arguments */
  110. unsigned int show_fd_path;
  111. static bool detach_on_execve;
  112. static int exit_code;
  113. static int strace_child;
  114. static int strace_tracer_pid;
  115. static const char *username;
  116. static uid_t run_uid;
  117. static gid_t run_gid;
  118. unsigned int max_strlen = DEFAULT_STRLEN;
  119. static int acolumn = DEFAULT_ACOLUMN;
  120. static char *acolumn_spaces;
  121. /* Default output style for xlat entities */
  122. enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
  123. static const char *outfname;
  124. /* If -ff, points to stderr. Else, it's our common output log */
  125. static FILE *shared_log;
  126. static bool open_append;
  127. struct tcb *printing_tcp;
  128. static struct tcb *current_tcp;
  129. struct tcb_wait_data {
  130. enum trace_event te; /**< Event passed to dispatch_event() */
  131. int status; /**< status, returned by wait4() */
  132. unsigned long msg; /**< Value returned by PTRACE_GETEVENTMSG */
  133. siginfo_t si; /**< siginfo, returned by PTRACE_GETSIGINFO */
  134. };
  135. static struct tcb **tcbtab;
  136. static unsigned int nprocs;
  137. static size_t tcbtabsize;
  138. static struct tcb_wait_data *tcb_wait_tab;
  139. static size_t tcb_wait_tab_size;
  140. #ifndef HAVE_PROGRAM_INVOCATION_NAME
  141. char *program_invocation_name;
  142. #endif
  143. unsigned os_release; /* generated from uname()'s u.release */
  144. static void detach(struct tcb *tcp);
  145. static void cleanup(int sig);
  146. static void interrupt(int sig);
  147. #ifdef HAVE_SIG_ATOMIC_T
  148. static volatile sig_atomic_t interrupted, restart_failed;
  149. #else
  150. static volatile int interrupted, restart_failed;
  151. #endif
  152. static sigset_t timer_set;
  153. static void timer_sighandler(int);
  154. #ifndef HAVE_STRERROR
  155. # if !HAVE_DECL_SYS_ERRLIST
  156. extern int sys_nerr;
  157. extern char *sys_errlist[];
  158. # endif
  159. const char *
  160. strerror(int err_no)
  161. {
  162. static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
  163. if (err_no < 1 || err_no >= sys_nerr) {
  164. xsprintf(buf, "Unknown error %d", err_no);
  165. return buf;
  166. }
  167. return sys_errlist[err_no];
  168. }
  169. #endif /* HAVE_STERRROR */
  170. static void
  171. print_version(void)
  172. {
  173. static const char features[] =
  174. #ifdef ENABLE_STACKTRACE
  175. " stack-trace=" USE_UNWINDER
  176. #endif
  177. #ifdef USE_DEMANGLE
  178. " stack-demangle"
  179. #endif
  180. #if SUPPORTED_PERSONALITIES > 1
  181. # if defined HAVE_M32_MPERS
  182. " m32-mpers"
  183. # else
  184. " no-m32-mpers"
  185. # endif
  186. #endif /* SUPPORTED_PERSONALITIES > 1 */
  187. #if SUPPORTED_PERSONALITIES > 2
  188. # if defined HAVE_MX32_MPERS
  189. " mx32-mpers"
  190. # else
  191. " no-mx32-mpers"
  192. # endif
  193. #endif /* SUPPORTED_PERSONALITIES > 2 */
  194. "";
  195. printf("%s -- version %s\n"
  196. "Copyright (c) 1991-%s The strace developers <%s>.\n"
  197. "This is free software; see the source for copying conditions. There is NO\n"
  198. "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
  199. PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
  200. printf("\nOptional features enabled:%s\n",
  201. features[0] ? features : " (none)");
  202. }
  203. static void
  204. usage(void)
  205. {
  206. #ifdef ENABLE_STACKTRACE
  207. # define K_OPT "k"
  208. #else
  209. # define K_OPT ""
  210. #endif
  211. printf("\
  212. usage: strace [-ACdffhi" K_OPT "qqrtttTvVwxxyyzZ] [-I n] [-b execve] [-e expr]...\n\
  213. [-a column] [-o file] [-s strsize] [-X format] [-P path]...\n\
  214. [-p pid]... [--seccomp-bpf]\n\
  215. { -p pid | [-DDD] [-E var=val]... [-u username] PROG [ARGS] }\n\
  216. or: strace -c[dfwzZ] [-I n] [-b execve] [-e expr]... [-O overhead]\n\
  217. [-S sortby] [-P path]... [-p pid]... [--seccomp-bpf]\n\
  218. { -p pid | [-DDD] [-E var=val]... [-u username] PROG [ARGS] }\n\
  219. \n\
  220. Output format:\n\
  221. -A open the file provided in the -o option in append mode\n\
  222. -a column alignment COLUMN for printing syscall results (default %d)\n\
  223. -i print instruction pointer at time of syscall\n\
  224. "
  225. #ifdef ENABLE_STACKTRACE
  226. "\
  227. -k obtain stack trace between each syscall\n\
  228. "
  229. #endif
  230. "\
  231. -o file send trace output to FILE instead of stderr\n\
  232. -q suppress messages about attaching, detaching, etc.\n\
  233. -qq suppress messages about process exit status as well.\n\
  234. -r print relative timestamp\n\
  235. -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
  236. -t print absolute timestamp\n\
  237. -tt print absolute timestamp with usecs\n\
  238. -T print time spent in each syscall\n\
  239. -v verbose mode: print entities unabbreviated\n\
  240. -x print non-ascii strings in hex\n\
  241. -xx print all strings in hex\n\
  242. -X format set the format for printing of named constants and flags\n\
  243. -y print paths associated with file descriptor arguments\n\
  244. -yy print protocol specific information associated with socket\n\
  245. file descriptors\n\
  246. \n\
  247. Statistics:\n\
  248. -c count time, calls, and errors for each syscall and report\n\
  249. summary\n\
  250. -C like -c but also print regular output\n\
  251. -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
  252. -S sortby sort syscall counts by: time, calls, errors, name, nothing\n\
  253. (default %s)\n\
  254. -w summarise syscall latency (default is system time)\n\
  255. \n\
  256. Filtering:\n\
  257. -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
  258. options: trace, abbrev, verbose, raw, signal, read, write, fault,\n\
  259. inject, status, kvm\n\
  260. -P path trace accesses to path\n\
  261. -z print only syscalls that returned without an error code\n\
  262. -Z print only syscalls that returned with an error code\n\
  263. \n\
  264. Tracing:\n\
  265. -b execve detach on execve syscall\n\
  266. -D run tracer process as a grandchild, not as a parent\n\
  267. -DD run tracer process in a separate process group\n\
  268. -DDD run tracer process in a separate session\n\
  269. -f follow forks\n\
  270. -ff follow forks with output into separate files\n\
  271. -I interruptible\n\
  272. 1: no signals are blocked\n\
  273. 2: fatal signals are blocked while decoding syscall (default)\n\
  274. 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
  275. 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
  276. (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
  277. \n\
  278. Startup:\n\
  279. -E var remove var from the environment for command\n\
  280. -E var=val put var=val in the environment for command\n\
  281. -p pid trace process with process id PID, may be repeated\n\
  282. -u username run command as username handling setuid and/or setgid\n\
  283. \n\
  284. Miscellaneous:\n\
  285. --seccomp-bpf enable seccomp-bpf filtering\n\
  286. -d enable debug output to stderr\n\
  287. -h, --help print help message\n\
  288. -V, --version print version\n\
  289. "
  290. /* ancient, no one should use it
  291. -F -- attempt to follow vforks (deprecated, use -f)\n\
  292. */
  293. , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
  294. exit(0);
  295. #undef K_OPT
  296. }
  297. void ATTRIBUTE_NORETURN
  298. die(void)
  299. {
  300. if (strace_tracer_pid == getpid()) {
  301. cleanup(0);
  302. exit(1);
  303. }
  304. _exit(1);
  305. }
  306. static void
  307. error_opt_arg(int opt, const char *arg)
  308. {
  309. error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
  310. }
  311. static const char *ptrace_attach_cmd;
  312. static int
  313. ptrace_attach_or_seize(int pid)
  314. {
  315. int r;
  316. if (!use_seize)
  317. return ptrace_attach_cmd = "PTRACE_ATTACH",
  318. ptrace(PTRACE_ATTACH, pid, 0L, 0L);
  319. r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
  320. if (r)
  321. return ptrace_attach_cmd = "PTRACE_SEIZE", r;
  322. r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
  323. return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
  324. }
  325. static const char *
  326. ptrace_op_str(unsigned int op)
  327. {
  328. const char *str = xlookup(ptrace_cmds, op);
  329. if (str)
  330. return str;
  331. static char buf[sizeof(op) * 3];
  332. xsprintf(buf, "%u", op);
  333. return buf;
  334. }
  335. /*
  336. * Used when we want to unblock stopped traced process.
  337. * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
  338. * Returns 0 on success or if error was ESRCH
  339. * (presumably process was killed while we talk to it).
  340. * Otherwise prints error message and returns -1.
  341. */
  342. static int
  343. ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
  344. {
  345. int err;
  346. errno = 0;
  347. ptrace(op, tcp->pid, 0L, (unsigned long) sig);
  348. err = errno;
  349. if (!err || err == ESRCH)
  350. return 0;
  351. /*
  352. * Why curcol != 0? Otherwise sometimes we get this:
  353. *
  354. * 10252 kill(10253, SIGKILL) = 0
  355. * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
  356. *
  357. * 10252 died after we retrieved syscall exit data,
  358. * but before we tried to restart it. Log looks ugly.
  359. */
  360. if (current_tcp && current_tcp->curcol != 0) {
  361. tprintf(" <Cannot restart pid %d with ptrace(%s): %s>\n",
  362. tcp->pid, ptrace_op_str(op), strerror(err));
  363. line_ended();
  364. }
  365. errno = err;
  366. perror_msg("ptrace(%s,pid:%d,sig:%u)",
  367. ptrace_op_str(op), tcp->pid, sig);
  368. return -1;
  369. }
  370. static void
  371. set_cloexec_flag(int fd)
  372. {
  373. int flags, newflags;
  374. flags = fcntl_fd(fd, F_GETFD);
  375. if (flags < 0) {
  376. /* Can happen only if fd is bad.
  377. * Should never happen: if it does, we have a bug
  378. * in the caller. Therefore we just abort
  379. * instead of propagating the error.
  380. */
  381. perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
  382. }
  383. newflags = flags | FD_CLOEXEC;
  384. if (flags == newflags)
  385. return;
  386. if (fcntl_fd(fd, F_SETFD, newflags)) /* never fails */
  387. perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
  388. }
  389. /*
  390. * When strace is setuid executable, we have to swap uids
  391. * before and after filesystem and process management operations.
  392. */
  393. static void
  394. swap_uid(void)
  395. {
  396. int euid = geteuid(), uid = getuid();
  397. if (euid != uid && setreuid(euid, uid) < 0) {
  398. perror_msg_and_die("setreuid");
  399. }
  400. }
  401. static FILE *
  402. strace_fopen(const char *path)
  403. {
  404. FILE *fp;
  405. swap_uid();
  406. fp = fopen_stream(path, open_append ? "a" : "w");
  407. if (!fp)
  408. perror_msg_and_die("Can't fopen '%s'", path);
  409. swap_uid();
  410. set_cloexec_flag(fileno(fp));
  411. return fp;
  412. }
  413. static int popen_pid;
  414. #ifndef _PATH_BSHELL
  415. # define _PATH_BSHELL "/bin/sh"
  416. #endif
  417. /*
  418. * We cannot use standard popen(3) here because we have to distinguish
  419. * popen child process from other processes we trace, and standard popen(3)
  420. * does not export its child's pid.
  421. */
  422. static FILE *
  423. strace_popen(const char *command)
  424. {
  425. FILE *fp;
  426. int pid;
  427. int fds[2];
  428. swap_uid();
  429. if (pipe(fds) < 0)
  430. perror_msg_and_die("pipe");
  431. set_cloexec_flag(fds[1]); /* never fails */
  432. pid = vfork();
  433. if (pid < 0)
  434. perror_msg_and_die("vfork");
  435. if (pid == 0) {
  436. /* child */
  437. close(fds[1]);
  438. if (fds[0] != 0) {
  439. if (dup2(fds[0], 0))
  440. perror_msg_and_die("dup2");
  441. close(fds[0]);
  442. }
  443. execl(_PATH_BSHELL, "sh", "-c", command, NULL);
  444. perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
  445. }
  446. /* parent */
  447. popen_pid = pid;
  448. close(fds[0]);
  449. swap_uid();
  450. fp = fdopen(fds[1], "w");
  451. if (!fp)
  452. perror_msg_and_die("fdopen");
  453. return fp;
  454. }
  455. static void
  456. outf_perror(const struct tcb * const tcp)
  457. {
  458. if (tcp->outf == stderr)
  459. return;
  460. /* This is ugly, but we don't store separate file names */
  461. if (followfork >= 2)
  462. perror_msg("%s.%u", outfname, tcp->pid);
  463. else
  464. perror_msg("%s", outfname);
  465. }
  466. ATTRIBUTE_FORMAT((printf, 1, 0))
  467. static void
  468. tvprintf(const char *const fmt, va_list args)
  469. {
  470. if (current_tcp) {
  471. int n = vfprintf(current_tcp->outf, fmt, args);
  472. if (n < 0) {
  473. /* very unlikely due to vfprintf buffering */
  474. outf_perror(current_tcp);
  475. } else
  476. current_tcp->curcol += n;
  477. }
  478. }
  479. void
  480. tprintf(const char *fmt, ...)
  481. {
  482. va_list args;
  483. va_start(args, fmt);
  484. tvprintf(fmt, args);
  485. va_end(args);
  486. }
  487. #ifndef HAVE_FPUTS_UNLOCKED
  488. # define fputs_unlocked fputs
  489. #endif
  490. void
  491. tprints(const char *str)
  492. {
  493. if (current_tcp) {
  494. int n = fputs_unlocked(str, current_tcp->outf);
  495. if (n >= 0) {
  496. current_tcp->curcol += strlen(str);
  497. return;
  498. }
  499. /* very unlikely due to fputs_unlocked buffering */
  500. outf_perror(current_tcp);
  501. }
  502. }
  503. void
  504. tprints_comment(const char *const str)
  505. {
  506. if (str && *str)
  507. tprintf(" /* %s */", str);
  508. }
  509. void
  510. tprintf_comment(const char *fmt, ...)
  511. {
  512. if (!fmt || !*fmt)
  513. return;
  514. va_list args;
  515. va_start(args, fmt);
  516. tprints(" /* ");
  517. tvprintf(fmt, args);
  518. tprints(" */");
  519. va_end(args);
  520. }
  521. static void
  522. flush_tcp_output(const struct tcb *const tcp)
  523. {
  524. if (fflush(tcp->outf))
  525. outf_perror(tcp);
  526. }
  527. void
  528. line_ended(void)
  529. {
  530. if (current_tcp) {
  531. current_tcp->curcol = 0;
  532. flush_tcp_output(current_tcp);
  533. }
  534. if (printing_tcp) {
  535. printing_tcp->curcol = 0;
  536. printing_tcp = NULL;
  537. }
  538. }
  539. void
  540. set_current_tcp(const struct tcb *tcp)
  541. {
  542. current_tcp = (struct tcb *) tcp;
  543. /* Sync current_personality and stuff */
  544. if (current_tcp)
  545. set_personality(current_tcp->currpers);
  546. }
  547. void
  548. printleader(struct tcb *tcp)
  549. {
  550. /* If -ff, "previous tcb we printed" is always the same as current,
  551. * because we have per-tcb output files.
  552. */
  553. if (followfork >= 2)
  554. printing_tcp = tcp;
  555. if (printing_tcp) {
  556. set_current_tcp(printing_tcp);
  557. if (!tcp->staged_output_data && printing_tcp->curcol != 0 &&
  558. (followfork < 2 || printing_tcp == tcp)) {
  559. /*
  560. * case 1: we have a shared log (i.e. not -ff), and last line
  561. * wasn't finished (same or different tcb, doesn't matter).
  562. * case 2: split log, we are the same tcb, but our last line
  563. * didn't finish ("SIGKILL nuked us after syscall entry" etc).
  564. */
  565. tprints(" <unfinished ...>\n");
  566. printing_tcp->curcol = 0;
  567. }
  568. }
  569. printing_tcp = tcp;
  570. set_current_tcp(tcp);
  571. current_tcp->curcol = 0;
  572. if (print_pid_pfx)
  573. tprintf("%-5d ", tcp->pid);
  574. else if (nprocs > 1 && !outfname)
  575. tprintf("[pid %5u] ", tcp->pid);
  576. if (tflag) {
  577. struct timespec ts;
  578. clock_gettime(CLOCK_REALTIME, &ts);
  579. if (tflag > 2) {
  580. tprintf("%lld.%06ld ",
  581. (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
  582. } else {
  583. time_t local = ts.tv_sec;
  584. char str[MAX(sizeof("HH:MM:SS"), sizeof(ts.tv_sec) * 3)];
  585. struct tm *tm = localtime(&local);
  586. if (tm)
  587. strftime(str, sizeof(str), "%T", tm);
  588. else
  589. xsprintf(str, "%lld", (long long) local);
  590. if (tflag > 1)
  591. tprintf("%s.%06ld ",
  592. str, (long) ts.tv_nsec / 1000);
  593. else
  594. tprintf("%s ", str);
  595. }
  596. }
  597. if (rflag) {
  598. struct timespec ts;
  599. clock_gettime(CLOCK_MONOTONIC, &ts);
  600. static struct timespec ots;
  601. if (ots.tv_sec == 0)
  602. ots = ts;
  603. struct timespec dts;
  604. ts_sub(&dts, &ts, &ots);
  605. ots = ts;
  606. tprintf("%s%6ld.%06ld%s ",
  607. tflag ? "(+" : "",
  608. (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
  609. tflag ? ")" : "");
  610. }
  611. if (iflag)
  612. print_instruction_pointer(tcp);
  613. }
  614. void
  615. tabto(void)
  616. {
  617. if (current_tcp->curcol < acolumn)
  618. tprints(acolumn_spaces + current_tcp->curcol);
  619. }
  620. /* Should be only called directly *after successful attach* to a tracee.
  621. * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
  622. * may create bogus empty FILE.<nonexistant_pid>, and then die.
  623. */
  624. static void
  625. after_successful_attach(struct tcb *tcp, const unsigned int flags)
  626. {
  627. tcp->flags |= TCB_ATTACHED | TCB_STARTUP | flags;
  628. tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
  629. if (followfork >= 2) {
  630. char name[PATH_MAX];
  631. xsprintf(name, "%s.%u", outfname, tcp->pid);
  632. tcp->outf = strace_fopen(name);
  633. }
  634. #ifdef ENABLE_STACKTRACE
  635. if (stack_trace_enabled)
  636. unwind_tcb_init(tcp);
  637. #endif
  638. }
  639. static void
  640. expand_tcbtab(void)
  641. {
  642. /* Allocate some (more) TCBs (and expand the table).
  643. We don't want to relocate the TCBs because our
  644. callers have pointers and it would be a pain.
  645. So tcbtab is a table of pointers. Since we never
  646. free the TCBs, we allocate a single chunk of many. */
  647. size_t old_tcbtabsize;
  648. struct tcb *newtcbs;
  649. struct tcb **tcb_ptr;
  650. old_tcbtabsize = tcbtabsize;
  651. tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
  652. newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
  653. for (tcb_ptr = tcbtab + old_tcbtabsize;
  654. tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
  655. *tcb_ptr = newtcbs;
  656. }
  657. static struct tcb *
  658. alloctcb(int pid)
  659. {
  660. unsigned int i;
  661. struct tcb *tcp;
  662. if (nprocs == tcbtabsize)
  663. expand_tcbtab();
  664. for (i = 0; i < tcbtabsize; i++) {
  665. tcp = tcbtab[i];
  666. if (!tcp->pid) {
  667. memset(tcp, 0, sizeof(*tcp));
  668. list_init(&tcp->wait_list);
  669. tcp->pid = pid;
  670. #if SUPPORTED_PERSONALITIES > 1
  671. tcp->currpers = current_personality;
  672. #endif
  673. nprocs++;
  674. debug_msg("new tcb for pid %d, active tcbs:%d",
  675. tcp->pid, nprocs);
  676. return tcp;
  677. }
  678. }
  679. error_msg_and_die("bug in alloctcb");
  680. }
  681. void *
  682. get_tcb_priv_data(const struct tcb *tcp)
  683. {
  684. return tcp->_priv_data;
  685. }
  686. int
  687. set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
  688. void (*const free_priv_data)(void *))
  689. {
  690. if (tcp->_priv_data)
  691. return -1;
  692. tcp->_free_priv_data = free_priv_data;
  693. tcp->_priv_data = priv_data;
  694. return 0;
  695. }
  696. void
  697. free_tcb_priv_data(struct tcb *tcp)
  698. {
  699. if (tcp->_priv_data) {
  700. if (tcp->_free_priv_data) {
  701. tcp->_free_priv_data(tcp->_priv_data);
  702. tcp->_free_priv_data = NULL;
  703. }
  704. tcp->_priv_data = NULL;
  705. }
  706. }
  707. static void
  708. droptcb(struct tcb *tcp)
  709. {
  710. if (tcp->pid == 0)
  711. return;
  712. if (cflag && debug_flag) {
  713. struct timespec dt;
  714. ts_sub(&dt, &tcp->stime, &tcp->atime);
  715. debug_func_msg("pid %d: %.9f seconds of system time spent "
  716. "since attach", tcp->pid, ts_float(&dt));
  717. }
  718. int p;
  719. for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
  720. free(tcp->inject_vec[p]);
  721. free_tcb_priv_data(tcp);
  722. #ifdef ENABLE_STACKTRACE
  723. if (stack_trace_enabled)
  724. unwind_tcb_fin(tcp);
  725. #endif
  726. #ifdef HAVE_LINUX_KVM_H
  727. kvm_vcpu_info_free(tcp);
  728. #endif
  729. if (tcp->mmap_cache)
  730. tcp->mmap_cache->free_fn(tcp, __func__);
  731. nprocs--;
  732. debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
  733. if (tcp->outf) {
  734. bool publish = true;
  735. if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
  736. publish = is_number_in_set(STATUS_DETACHED, status_set);
  737. strace_close_memstream(tcp, publish);
  738. }
  739. if (followfork >= 2) {
  740. if (tcp->curcol != 0 && publish)
  741. fprintf(tcp->outf, " <detached ...>\n");
  742. fclose(tcp->outf);
  743. } else {
  744. if (printing_tcp == tcp && tcp->curcol != 0 && publish)
  745. fprintf(tcp->outf, " <detached ...>\n");
  746. flush_tcp_output(tcp);
  747. }
  748. }
  749. if (current_tcp == tcp)
  750. set_current_tcp(NULL);
  751. if (printing_tcp == tcp)
  752. printing_tcp = NULL;
  753. list_remove(&tcp->wait_list);
  754. memset(tcp, 0, sizeof(*tcp));
  755. }
  756. /* Detach traced process.
  757. * Never call DETACH twice on the same process as both unattached and
  758. * attached-unstopped processes give the same ESRCH. For unattached process we
  759. * would SIGSTOP it and wait for its SIGSTOP notification forever.
  760. */
  761. static void
  762. detach(struct tcb *tcp)
  763. {
  764. int error;
  765. int status;
  766. /*
  767. * Linux wrongly insists the child be stopped
  768. * before detaching. Arghh. We go through hoops
  769. * to make a clean break of things.
  770. */
  771. if (!(tcp->flags & TCB_ATTACHED))
  772. goto drop;
  773. /* We attached but possibly didn't see the expected SIGSTOP.
  774. * We must catch exactly one as otherwise the detached process
  775. * would be left stopped (process state T).
  776. */
  777. if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
  778. goto wait_loop;
  779. error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
  780. if (!error) {
  781. /* On a clear day, you can see forever. */
  782. goto drop;
  783. }
  784. if (errno != ESRCH) {
  785. /* Shouldn't happen. */
  786. perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
  787. goto drop;
  788. }
  789. /* ESRCH: process is either not stopped or doesn't exist. */
  790. if (my_tkill(tcp->pid, 0) < 0) {
  791. if (errno != ESRCH)
  792. /* Shouldn't happen. */
  793. perror_func_msg("tkill(%u,0)", tcp->pid);
  794. /* else: process doesn't exist. */
  795. goto drop;
  796. }
  797. /* Process is not stopped, need to stop it. */
  798. if (use_seize) {
  799. /*
  800. * With SEIZE, tracee can be in group-stop already.
  801. * In this state sending it another SIGSTOP does nothing.
  802. * Need to use INTERRUPT.
  803. * Testcase: trying to ^C a "strace -p <stopped_process>".
  804. */
  805. error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
  806. if (!error)
  807. goto wait_loop;
  808. if (errno != ESRCH)
  809. perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
  810. } else {
  811. error = my_tkill(tcp->pid, SIGSTOP);
  812. if (!error)
  813. goto wait_loop;
  814. if (errno != ESRCH)
  815. perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
  816. }
  817. /* Either process doesn't exist, or some weird error. */
  818. goto drop;
  819. wait_loop:
  820. /* We end up here in three cases:
  821. * 1. We sent PTRACE_INTERRUPT (use_seize case)
  822. * 2. We sent SIGSTOP (!use_seize)
  823. * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
  824. */
  825. for (;;) {
  826. unsigned int sig;
  827. if (waitpid(tcp->pid, &status, __WALL) < 0) {
  828. if (errno == EINTR)
  829. continue;
  830. /*
  831. * if (errno == ECHILD) break;
  832. * ^^^ WRONG! We expect this PID to exist,
  833. * and want to emit a message otherwise:
  834. */
  835. perror_func_msg("waitpid(%u)", tcp->pid);
  836. break;
  837. }
  838. if (!WIFSTOPPED(status)) {
  839. /*
  840. * Tracee exited or was killed by signal.
  841. * We shouldn't normally reach this place:
  842. * we don't want to consume exit status.
  843. * Consider "strace -p PID" being ^C-ed:
  844. * we want merely to detach from PID.
  845. *
  846. * However, we _can_ end up here if tracee
  847. * was SIGKILLed.
  848. */
  849. break;
  850. }
  851. sig = WSTOPSIG(status);
  852. debug_msg("detach wait: event:%d sig:%d",
  853. (unsigned) status >> 16, sig);
  854. if (use_seize) {
  855. unsigned event = (unsigned)status >> 16;
  856. if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
  857. /*
  858. * sig == SIGTRAP: PTRACE_INTERRUPT stop.
  859. * sig == other: process was already stopped
  860. * with this stopping sig (see tests/detach-stopped).
  861. * Looks like re-injecting this sig is not necessary
  862. * in DETACH for the tracee to remain stopped.
  863. */
  864. sig = 0;
  865. }
  866. /*
  867. * PTRACE_INTERRUPT is not guaranteed to produce
  868. * the above event if other ptrace-stop is pending.
  869. * See tests/detach-sleeping testcase:
  870. * strace got SIGINT while tracee is sleeping.
  871. * We sent PTRACE_INTERRUPT.
  872. * We see syscall exit, not PTRACE_INTERRUPT stop.
  873. * We won't get PTRACE_INTERRUPT stop
  874. * if we would CONT now. Need to DETACH.
  875. */
  876. if (sig == syscall_trap_sig)
  877. sig = 0;
  878. /* else: not sure in which case we can be here.
  879. * Signal stop? Inject it while detaching.
  880. */
  881. ptrace_restart(PTRACE_DETACH, tcp, sig);
  882. break;
  883. }
  884. /* Note: this check has to be after use_seize check */
  885. /* (else, in use_seize case SIGSTOP will be mistreated) */
  886. if (sig == SIGSTOP) {
  887. /* Detach, suppressing SIGSTOP */
  888. ptrace_restart(PTRACE_DETACH, tcp, 0);
  889. break;
  890. }
  891. if (sig == syscall_trap_sig)
  892. sig = 0;
  893. /* Can't detach just yet, may need to wait for SIGSTOP */
  894. error = ptrace_restart(PTRACE_CONT, tcp, sig);
  895. if (error < 0) {
  896. /* Should not happen.
  897. * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
  898. * ptrace_restart already emitted error message.
  899. */
  900. break;
  901. }
  902. }
  903. drop:
  904. if (!qflag && (tcp->flags & TCB_ATTACHED))
  905. error_msg("Process %u detached", tcp->pid);
  906. droptcb(tcp);
  907. }
  908. static void
  909. process_opt_p_list(char *opt)
  910. {
  911. while (*opt) {
  912. /*
  913. * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
  914. * pidof uses space as delim, pgrep uses newline. :(
  915. */
  916. int pid;
  917. char *delim = opt + strcspn(opt, "\n\t ,");
  918. char c = *delim;
  919. *delim = '\0';
  920. pid = string_to_uint(opt);
  921. if (pid <= 0) {
  922. error_msg_and_die("Invalid process id: '%s'", opt);
  923. }
  924. if (pid == strace_tracer_pid) {
  925. error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
  926. }
  927. *delim = c;
  928. alloctcb(pid);
  929. if (c == '\0')
  930. break;
  931. opt = delim + 1;
  932. }
  933. }
  934. static void
  935. attach_tcb(struct tcb *const tcp)
  936. {
  937. if (ptrace_attach_or_seize(tcp->pid) < 0) {
  938. perror_msg("attach: ptrace(%s, %d)",
  939. ptrace_attach_cmd, tcp->pid);
  940. droptcb(tcp);
  941. return;
  942. }
  943. after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
  944. debug_msg("attach to pid %d (main) succeeded", tcp->pid);
  945. static const char task_path[] = "/proc/%d/task";
  946. char procdir[sizeof(task_path) + sizeof(int) * 3];
  947. DIR *dir;
  948. unsigned int ntid = 0, nerr = 0;
  949. if (followfork && tcp->pid != strace_child &&
  950. xsprintf(procdir, task_path, tcp->pid) > 0 &&
  951. (dir = opendir(procdir)) != NULL) {
  952. struct_dirent *de;
  953. while ((de = read_dir(dir)) != NULL) {
  954. if (de->d_fileno == 0)
  955. continue;
  956. int tid = string_to_uint(de->d_name);
  957. if (tid <= 0 || tid == tcp->pid)
  958. continue;
  959. ++ntid;
  960. if (ptrace_attach_or_seize(tid) < 0) {
  961. ++nerr;
  962. debug_perror_msg("attach: ptrace(%s, %d)",
  963. ptrace_attach_cmd, tid);
  964. continue;
  965. }
  966. after_successful_attach(alloctcb(tid),
  967. TCB_GRABBED | post_attach_sigstop);
  968. debug_msg("attach to pid %d succeeded", tid);
  969. }
  970. closedir(dir);
  971. }
  972. if (!qflag) {
  973. if (ntid > nerr)
  974. error_msg("Process %u attached"
  975. " with %u threads",
  976. tcp->pid, ntid - nerr + 1);
  977. else
  978. error_msg("Process %u attached",
  979. tcp->pid);
  980. }
  981. }
  982. static void
  983. startup_attach(void)
  984. {
  985. pid_t parent_pid = strace_tracer_pid;
  986. unsigned int tcbi;
  987. struct tcb *tcp;
  988. if (daemonized_tracer) {
  989. pid_t pid = fork();
  990. if (pid < 0)
  991. perror_func_msg_and_die("fork");
  992. if (pid) { /* parent */
  993. /*
  994. * Wait for grandchild to attach to straced process
  995. * (grandparent). Grandchild SIGKILLs us after it attached.
  996. * Grandparent's wait() is unblocked by our death,
  997. * it proceeds to exec the straced program.
  998. */
  999. pause();
  1000. _exit(0); /* paranoia */
  1001. }
  1002. /* grandchild */
  1003. /* We will be the tracer process. Remember our new pid: */
  1004. strace_tracer_pid = getpid();
  1005. switch (daemonized_tracer) {
  1006. case DAEMONIZE_NEW_PGROUP:
  1007. /*
  1008. * If -D is passed twice, create a new process group,
  1009. * so we won't be killed by kill(0, ...).
  1010. */
  1011. if (setpgid(0, 0) < 0)
  1012. perror_msg_and_die("Cannot create a new"
  1013. " process group");
  1014. break;
  1015. case DAEMONIZE_NEW_SESSION:
  1016. /*
  1017. * If -D is passed thrice, create a new session,
  1018. * so we won't be killed upon session termination.
  1019. */
  1020. if (setsid() < 0)
  1021. perror_msg_and_die("Cannot create a new"
  1022. " session");
  1023. break;
  1024. }
  1025. }
  1026. for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
  1027. tcp = tcbtab[tcbi];
  1028. if (!tcp->pid)
  1029. continue;
  1030. /* Is this a process we should attach to, but not yet attached? */
  1031. if (tcp->flags & TCB_ATTACHED)
  1032. continue; /* no, we already attached it */
  1033. if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
  1034. errno = EPERM;
  1035. perror_msg("attach: pid %d", tcp->pid);
  1036. droptcb(tcp);
  1037. continue;
  1038. }
  1039. attach_tcb(tcp);
  1040. if (interrupted)
  1041. return;
  1042. } /* for each tcbtab[] */
  1043. if (daemonized_tracer) {
  1044. /*
  1045. * Make parent go away.
  1046. * Also makes grandparent's wait() unblock.
  1047. */
  1048. kill(parent_pid, SIGKILL);
  1049. strace_child = 0;
  1050. }
  1051. }
  1052. /* Stack-o-phobic exec helper, in the hope to work around
  1053. * NOMMU + "daemonized tracer" difficulty.
  1054. */
  1055. struct exec_params {
  1056. int fd_to_close;
  1057. uid_t run_euid;
  1058. gid_t run_egid;
  1059. char **argv;
  1060. char *pathname;
  1061. struct sigaction child_sa;
  1062. };
  1063. static struct exec_params params_for_tracee;
  1064. static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
  1065. exec_or_die(void)
  1066. {
  1067. struct exec_params *params = &params_for_tracee;
  1068. if (params->fd_to_close >= 0)
  1069. close(params->fd_to_close);
  1070. if (!daemonized_tracer && !use_seize) {
  1071. if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
  1072. perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
  1073. }
  1074. }
  1075. if (username != NULL) {
  1076. /*
  1077. * It is important to set groups before we
  1078. * lose privileges on setuid.
  1079. */
  1080. if (initgroups(username, run_gid) < 0) {
  1081. perror_msg_and_die("initgroups");
  1082. }
  1083. if (setregid(run_gid, params->run_egid) < 0) {
  1084. perror_msg_and_die("setregid");
  1085. }
  1086. if (setreuid(run_uid, params->run_euid) < 0) {
  1087. perror_msg_and_die("setreuid");
  1088. }
  1089. } else if (geteuid() != 0)
  1090. if (setreuid(run_uid, run_uid) < 0) {
  1091. perror_msg_and_die("setreuid");
  1092. }
  1093. if (!daemonized_tracer) {
  1094. /*
  1095. * Induce a ptrace stop. Tracer (our parent)
  1096. * will resume us with PTRACE_SYSCALL and display
  1097. * the immediately following execve syscall.
  1098. * Can't do this on NOMMU systems, we are after
  1099. * vfork: parent is blocked, stopping would deadlock.
  1100. */
  1101. if (!NOMMU_SYSTEM)
  1102. kill(getpid(), SIGSTOP);
  1103. } else {
  1104. alarm(3);
  1105. /* we depend on SIGCHLD set to SIG_DFL by init code */
  1106. /* if it happens to be SIG_IGN'ed, wait won't block */
  1107. wait(NULL);
  1108. alarm(0);
  1109. }
  1110. if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
  1111. sigaction(SIGCHLD, &params_for_tracee.child_sa, NULL);
  1112. debug_msg("seccomp filter %s",
  1113. seccomp_filtering ? "enabled" : "disabled");
  1114. if (seccomp_filtering)
  1115. init_seccomp_filter();
  1116. execv(params->pathname, params->argv);
  1117. perror_msg_and_die("exec");
  1118. }
  1119. /*
  1120. * Open a dummy descriptor for use as a placeholder.
  1121. * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
  1122. * A read attempt from such descriptor ends with EOF,
  1123. * a write attempt is rejected with EBADF.
  1124. */
  1125. static int
  1126. open_dummy_desc(void)
  1127. {
  1128. int fds[2];
  1129. if (pipe(fds))
  1130. perror_func_msg_and_die("pipe");
  1131. close(fds[1]);
  1132. set_cloexec_flag(fds[0]);
  1133. return fds[0];
  1134. }
  1135. /* placeholder fds status for stdin and stdout */
  1136. static bool fd_is_placeholder[2];
  1137. /*
  1138. * Ensure that all standard file descriptors are open by opening placeholder
  1139. * file descriptors for those standard file descriptors that are not open.
  1140. *
  1141. * The information which descriptors have been made open is saved
  1142. * in fd_is_placeholder for later use.
  1143. */
  1144. static void
  1145. ensure_standard_fds_opened(void)
  1146. {
  1147. int fd;
  1148. while ((fd = open_dummy_desc()) <= 2) {
  1149. if (fd == 2)
  1150. break;
  1151. fd_is_placeholder[fd] = true;
  1152. }
  1153. if (fd > 2)
  1154. close(fd);
  1155. }
  1156. /*
  1157. * Redirect stdin and stdout unless they have been opened earlier
  1158. * by ensure_standard_fds_opened as placeholders.
  1159. */
  1160. static void
  1161. redirect_standard_fds(void)
  1162. {
  1163. int i;
  1164. /*
  1165. * It might be a good idea to redirect stderr as well,
  1166. * but we sometimes need to print error messages.
  1167. */
  1168. for (i = 0; i <= 1; ++i) {
  1169. if (!fd_is_placeholder[i]) {
  1170. close(i);
  1171. open_dummy_desc();
  1172. }
  1173. }
  1174. }
  1175. static void
  1176. startup_child(char **argv)
  1177. {
  1178. strace_stat_t statbuf;
  1179. const char *filename;
  1180. size_t filename_len;
  1181. char pathname[PATH_MAX];
  1182. int pid;
  1183. struct tcb *tcp;
  1184. filename = argv[0];
  1185. filename_len = strlen(filename);
  1186. if (filename_len > sizeof(pathname) - 1) {
  1187. errno = ENAMETOOLONG;
  1188. perror_msg_and_die("exec");
  1189. }
  1190. if (strchr(filename, '/')) {
  1191. strcpy(pathname, filename);
  1192. }
  1193. #ifdef USE_DEBUGGING_EXEC
  1194. /*
  1195. * Debuggers customarily check the current directory
  1196. * first regardless of the path but doing that gives
  1197. * security geeks a panic attack.
  1198. */
  1199. else if (stat_file(filename, &statbuf) == 0)
  1200. strcpy(pathname, filename);
  1201. #endif /* USE_DEBUGGING_EXEC */
  1202. else {
  1203. const char *path;
  1204. size_t m, n, len;
  1205. for (path = getenv("PATH"); path && *path; path += m) {
  1206. const char *colon = strchr(path, ':');
  1207. if (colon) {
  1208. n = colon - path;
  1209. m = n + 1;
  1210. } else
  1211. m = n = strlen(path);
  1212. if (n == 0) {
  1213. if (!getcwd(pathname, PATH_MAX))
  1214. continue;
  1215. len = strlen(pathname);
  1216. } else if (n > sizeof(pathname) - 1)
  1217. continue;
  1218. else {
  1219. strncpy(pathname, path, n);
  1220. len = n;
  1221. }
  1222. if (len && pathname[len - 1] != '/')
  1223. pathname[len++] = '/';
  1224. if (filename_len + len > sizeof(pathname) - 1)
  1225. continue;
  1226. strcpy(pathname + len, filename);
  1227. if (stat_file(pathname, &statbuf) == 0 &&
  1228. /* Accept only regular files
  1229. with some execute bits set.
  1230. XXX not perfect, might still fail */
  1231. S_ISREG(statbuf.st_mode) &&
  1232. (statbuf.st_mode & 0111))
  1233. break;
  1234. }
  1235. if (!path || !*path)
  1236. pathname[0] = '\0';
  1237. }
  1238. if (stat_file(pathname, &statbuf) < 0) {
  1239. perror_msg_and_die("Can't stat '%s'", filename);
  1240. }
  1241. params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
  1242. params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
  1243. params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
  1244. params_for_tracee.argv = argv;
  1245. /*
  1246. * On NOMMU, can be safely freed only after execve in tracee.
  1247. * It's hard to know when that happens, so we just leak it.
  1248. */
  1249. params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
  1250. #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
  1251. if (daemonized_tracer)
  1252. prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
  1253. #endif
  1254. pid = fork();
  1255. if (pid < 0)
  1256. perror_func_msg_and_die("fork");
  1257. if ((pid != 0 && daemonized_tracer)
  1258. || (pid == 0 && !daemonized_tracer)
  1259. ) {
  1260. /* We are to become the tracee. Two cases:
  1261. * -D: we are parent
  1262. * not -D: we are child
  1263. */
  1264. exec_or_die();
  1265. }
  1266. /* We are the tracer */
  1267. if (!daemonized_tracer) {
  1268. strace_child = pid;
  1269. if (!use_seize) {
  1270. /* child did PTRACE_TRACEME, nothing to do in parent */
  1271. } else {
  1272. if (!NOMMU_SYSTEM) {
  1273. /* Wait until child stopped itself */
  1274. int status;
  1275. while (waitpid(pid, &status, WSTOPPED) < 0) {
  1276. if (errno == EINTR)
  1277. continue;
  1278. perror_msg_and_die("waitpid");
  1279. }
  1280. if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
  1281. kill_save_errno(pid, SIGKILL);
  1282. perror_msg_and_die("Unexpected wait status %#x",
  1283. status);
  1284. }
  1285. }
  1286. /* Else: NOMMU case, we have no way to sync.
  1287. * Just attach to it as soon as possible.
  1288. * This means that we may miss a few first syscalls...
  1289. */
  1290. if (ptrace_attach_or_seize(pid)) {
  1291. kill_save_errno(pid, SIGKILL);
  1292. perror_msg_and_die("attach: ptrace(%s, %d)",
  1293. ptrace_attach_cmd, pid);
  1294. }
  1295. if (!NOMMU_SYSTEM)
  1296. kill(pid, SIGCONT);
  1297. }
  1298. tcp = alloctcb(pid);
  1299. after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
  1300. | (NOMMU_SYSTEM ? 0
  1301. : (TCB_HIDE_LOG
  1302. | post_attach_sigstop)));
  1303. } else {
  1304. /* With -D, we are *child* here, the tracee is our parent. */
  1305. strace_child = strace_tracer_pid;
  1306. strace_tracer_pid = getpid();
  1307. tcp = alloctcb(strace_child);
  1308. tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
  1309. /*
  1310. * Attaching will be done later, by startup_attach.
  1311. * Note: we don't do after_successful_attach() here either!
  1312. */
  1313. /* NOMMU BUG! -D mode is active, we (child) return,
  1314. * and we will scribble over parent's stack!
  1315. * When parent later unpauses, it segfaults.
  1316. *
  1317. * We work around it
  1318. * (1) by declaring exec_or_die() NORETURN,
  1319. * hopefully compiler will just jump to it
  1320. * instead of call (won't push anything to stack),
  1321. * (2) by trying very hard in exec_or_die()
  1322. * to not use any stack,
  1323. * (3) having a really big (PATH_MAX) stack object
  1324. * in this function, which creates a "buffer" between
  1325. * child's and parent's stack pointers.
  1326. * This may save us if (1) and (2) failed
  1327. * and compiler decided to use stack in exec_or_die() anyway
  1328. * (happens on i386 because of stack parameter passing).
  1329. *
  1330. * A cleaner solution is to use makecontext + setcontext
  1331. * to create a genuine separate stack and execute on it.
  1332. */
  1333. }
  1334. if (seccomp_filtering)
  1335. tcp->flags |= TCB_SECCOMP_FILTER;
  1336. /*
  1337. * A case where straced process is part of a pipe:
  1338. * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
  1339. * If strace won't close its fd#0, closing it in tracee is not enough:
  1340. * the pipe is still open, it has a reader. Thus, "head" will not get its
  1341. * SIGPIPE at once, on the first write.
  1342. *
  1343. * Preventing it by redirecting strace's stdin/out.
  1344. * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
  1345. * will reuse them, unexpectedly making a newly opened object "stdin").
  1346. */
  1347. redirect_standard_fds();
  1348. }
  1349. static void
  1350. test_ptrace_seize(void)
  1351. {
  1352. int pid;
  1353. /* Need fork for test. NOMMU has no forks */
  1354. if (NOMMU_SYSTEM) {
  1355. post_attach_sigstop = 0; /* this sets use_seize to 1 */
  1356. return;
  1357. }
  1358. pid = fork();
  1359. if (pid < 0)
  1360. perror_func_msg_and_die("fork");
  1361. if (pid == 0) {
  1362. pause();
  1363. _exit(0);
  1364. }
  1365. /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
  1366. * attaching tracee continues to run unless a trap condition occurs.
  1367. * PTRACE_SEIZE doesn't affect signal or group stop state.
  1368. */
  1369. if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
  1370. post_attach_sigstop = 0; /* this sets use_seize to 1 */
  1371. } else {
  1372. debug_msg("PTRACE_SEIZE doesn't work");
  1373. }
  1374. kill(pid, SIGKILL);
  1375. while (1) {
  1376. int status, tracee_pid;
  1377. errno = 0;
  1378. tracee_pid = waitpid(pid, &status, 0);
  1379. if (tracee_pid <= 0) {
  1380. if (errno == EINTR)
  1381. continue;
  1382. perror_func_msg_and_die("unexpected wait result %d",
  1383. tracee_pid);
  1384. }
  1385. if (WIFSIGNALED(status))
  1386. return;
  1387. error_func_msg_and_die("unexpected wait status %#x", status);
  1388. }
  1389. }
  1390. static unsigned int
  1391. get_os_release(void)
  1392. {
  1393. struct utsname u;
  1394. if (uname(&u) < 0)
  1395. perror_msg_and_die("uname");
  1396. /*
  1397. * u.release string consists of at most three parts
  1398. * and normally has this form: "3.2.9[-some-garbage]",
  1399. * "X.Y-something" means "X.Y.0".
  1400. */
  1401. const char *p = u.release;
  1402. unsigned int rel = 0;
  1403. for (unsigned int parts = 0; parts < 3; ++parts) {
  1404. unsigned int n = 0;
  1405. for (; (*p >= '0') && (*p <= '9'); ++p) {
  1406. n *= 10;
  1407. n += *p - '0';
  1408. }
  1409. rel <<= 8;
  1410. rel |= n;
  1411. if (*p == '.')
  1412. ++p;
  1413. }
  1414. return rel;
  1415. }
  1416. static void
  1417. set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
  1418. {
  1419. const struct sigaction sa = { .sa_handler = sighandler };
  1420. sigaction(signo, &sa, oldact);
  1421. }
  1422. /*
  1423. * Initialization part of main() was eating much stack (~0.5k),
  1424. * which was unused after init.
  1425. * We can reuse it if we move init code into a separate function.
  1426. *
  1427. * Don't want main() to inline us and defeat the reason
  1428. * we have a separate function.
  1429. */
  1430. static void ATTRIBUTE_NOINLINE
  1431. init(int argc, char *argv[])
  1432. {
  1433. int c, i;
  1434. int optF = 0, zflags = 0;
  1435. if (!program_invocation_name || !*program_invocation_name) {
  1436. static char name[] = "strace";
  1437. program_invocation_name =
  1438. (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
  1439. }
  1440. strace_tracer_pid = getpid();
  1441. os_release = get_os_release();
  1442. shared_log = stderr;
  1443. set_sortby(DEFAULT_SORTBY);
  1444. set_personality(DEFAULT_PERSONALITY);
  1445. qualify("trace=all");
  1446. qualify("abbrev=all");
  1447. qualify("verbose=all");
  1448. qualify("status=all");
  1449. #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
  1450. # error Bug in DEFAULT_QUAL_FLAGS
  1451. #endif
  1452. qualify("signal=all");
  1453. static const char optstring[] = "+"
  1454. #ifdef ENABLE_STACKTRACE
  1455. "k"
  1456. #endif
  1457. "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yzZ";
  1458. enum {
  1459. SECCOMP_OPTION = 0x100
  1460. };
  1461. static const struct option longopts[] = {
  1462. { "seccomp-bpf", no_argument, 0, SECCOMP_OPTION },
  1463. { "help", no_argument, 0, 'h' },
  1464. { "version", no_argument, 0, 'V' },
  1465. { 0, 0, 0, 0 }
  1466. };
  1467. while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != EOF) {
  1468. switch (c) {
  1469. case 'a':
  1470. acolumn = string_to_uint(optarg);
  1471. if (acolumn < 0)
  1472. error_opt_arg(c, optarg);
  1473. break;
  1474. case 'A':
  1475. open_append = true;
  1476. break;
  1477. case 'b':
  1478. if (strcmp(optarg, "execve") != 0)
  1479. error_msg_and_die("Syscall '%s' for -b isn't supported",
  1480. optarg);
  1481. detach_on_execve = 1;
  1482. break;
  1483. case 'c':
  1484. if (cflag == CFLAG_BOTH) {
  1485. error_msg_and_help("-c and -C are mutually exclusive");
  1486. }
  1487. cflag = CFLAG_ONLY_STATS;
  1488. break;
  1489. case 'C':
  1490. if (cflag == CFLAG_ONLY_STATS) {
  1491. error_msg_and_help("-c and -C are mutually exclusive");
  1492. }
  1493. cflag = CFLAG_BOTH;
  1494. break;
  1495. case 'd':
  1496. debug_flag = 1;
  1497. break;
  1498. case 'D':
  1499. daemonized_tracer++;
  1500. break;
  1501. case 'e':
  1502. qualify(optarg);
  1503. break;
  1504. case 'E':
  1505. if (putenv(optarg) < 0)
  1506. perror_msg_and_die("putenv");
  1507. break;
  1508. case 'f':
  1509. followfork++;
  1510. break;
  1511. case 'F':
  1512. optF = 1;
  1513. break;
  1514. case 'h':
  1515. usage();
  1516. break;
  1517. case 'i':
  1518. iflag = 1;
  1519. break;
  1520. case 'I':
  1521. opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
  1522. if (opt_intr <= 0)
  1523. error_opt_arg(c, optarg);
  1524. break;
  1525. #ifdef ENABLE_STACKTRACE
  1526. case 'k':
  1527. stack_trace_enabled = true;
  1528. break;
  1529. #endif
  1530. case 'o':
  1531. outfname = optarg;
  1532. break;
  1533. case 'O':
  1534. if (set_overhead(optarg) < 0)
  1535. error_opt_arg(c, optarg);
  1536. break;
  1537. case 'p':
  1538. process_opt_p_list(optarg);
  1539. break;
  1540. case 'P':
  1541. pathtrace_select(optarg);
  1542. break;
  1543. case 'q':
  1544. qflag++;
  1545. break;
  1546. case 'r':
  1547. rflag = 1;
  1548. break;
  1549. case 's':
  1550. i = string_to_uint(optarg);
  1551. if (i < 0 || (unsigned int) i > -1U / 4)
  1552. error_opt_arg(c, optarg);
  1553. max_strlen = i;
  1554. break;
  1555. case 'S':
  1556. set_sortby(optarg);
  1557. break;
  1558. case 't':
  1559. tflag++;
  1560. break;
  1561. case 'T':
  1562. Tflag = 1;
  1563. break;
  1564. case 'u':
  1565. username = optarg;
  1566. break;
  1567. case 'v':
  1568. qualify("abbrev=none");
  1569. break;
  1570. case 'V':
  1571. print_version();
  1572. exit(0);
  1573. break;
  1574. case 'w':
  1575. count_wallclock = 1;
  1576. break;
  1577. case 'x':
  1578. xflag++;
  1579. break;
  1580. case 'X':
  1581. if (!strcmp(optarg, "raw"))
  1582. xlat_verbosity = XLAT_STYLE_RAW;
  1583. else if (!strcmp(optarg, "abbrev"))
  1584. xlat_verbosity = XLAT_STYLE_ABBREV;
  1585. else if (!strcmp(optarg, "verbose"))
  1586. xlat_verbosity = XLAT_STYLE_VERBOSE;
  1587. else
  1588. error_opt_arg(c, optarg);
  1589. break;
  1590. case 'y':
  1591. show_fd_path++;
  1592. break;
  1593. case 'z':
  1594. clear_number_set_array(status_set, 1);
  1595. add_number_to_set(STATUS_SUCCESSFUL, status_set);
  1596. zflags++;
  1597. break;
  1598. case 'Z':
  1599. clear_number_set_array(status_set, 1);
  1600. add_number_to_set(STATUS_FAILED, status_set);
  1601. zflags++;
  1602. break;
  1603. case SECCOMP_OPTION:
  1604. seccomp_filtering = true;
  1605. break;
  1606. default:
  1607. error_msg_and_help(NULL);
  1608. break;
  1609. }
  1610. }
  1611. argv += optind;
  1612. argc -= optind;
  1613. if (argc < 0 || (!nprocs && !argc)) {
  1614. error_msg_and_help("must have PROG [ARGS] or -p PID");
  1615. }
  1616. if (!argc && daemonized_tracer) {
  1617. error_msg_and_help("PROG [ARGS] must be specified with -D");
  1618. }
  1619. if (daemonized_tracer > (unsigned int) MAX_DAEMONIZE_OPTS)
  1620. error_msg_and_help("Too many -D's (%u), maximum supported -D "
  1621. "count is %d",
  1622. daemonized_tracer, MAX_DAEMONIZE_OPTS);
  1623. if (seccomp_filtering && detach_on_execve) {
  1624. error_msg("--seccomp-bpf is not enabled because"
  1625. " it is not compatible with -b");
  1626. seccomp_filtering = false;
  1627. }
  1628. if (seccomp_filtering) {
  1629. if (nprocs && (!argc || debug_flag))
  1630. error_msg("--seccomp-bpf is not enabled for processes"
  1631. " attached with -p");
  1632. if (!followfork) {
  1633. error_msg("--seccomp-bpf implies -f");
  1634. followfork = 1;
  1635. }
  1636. }
  1637. if (optF) {
  1638. if (followfork) {
  1639. error_msg("deprecated option -F ignored");
  1640. } else {
  1641. error_msg("option -F is deprecated, "
  1642. "please use -f instead");
  1643. followfork = optF;
  1644. }
  1645. }
  1646. if (followfork >= 2 && cflag) {
  1647. error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
  1648. }
  1649. if (count_wallclock && !cflag) {
  1650. error_msg_and_help("-w must be given with (-c or -C)");
  1651. }
  1652. if (cflag == CFLAG_ONLY_STATS) {
  1653. if (iflag)
  1654. error_msg("-%c has no effect with -c", 'i');
  1655. if (stack_trace_enabled)
  1656. error_msg("-%c has no effect with -c", 'k');
  1657. if (rflag)
  1658. error_msg("-%c has no effect with -c", 'r');
  1659. if (tflag)
  1660. error_msg("-%c has no effect with -c", 't');
  1661. if (Tflag)
  1662. error_msg("-%c has no effect with -c", 'T');
  1663. if (show_fd_path)
  1664. error_msg("-%c has no effect with -c", 'y');
  1665. }
  1666. #ifndef HAVE_OPEN_MEMSTREAM
  1667. if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
  1668. error_msg_and_help("open_memstream is required to use -z, -Z, or -e status");
  1669. #endif
  1670. if (zflags > 1)
  1671. error_msg("Only the last of -z/-Z options will take effect. "
  1672. "See status qualifier for more complex filters.");
  1673. acolumn_spaces = xmalloc(acolumn + 1);
  1674. memset(acolumn_spaces, ' ', acolumn);
  1675. acolumn_spaces[acolumn] = '\0';
  1676. set_sighandler(SIGCHLD, SIG_DFL, &params_for_tracee.child_sa);
  1677. #ifdef ENABLE_STACKTRACE
  1678. if (stack_trace_enabled)
  1679. unwind_init();
  1680. #endif
  1681. /* See if they want to run as another user. */
  1682. if (username != NULL) {
  1683. struct passwd *pent;
  1684. if (getuid() != 0 || geteuid() != 0) {
  1685. error_msg_and_die("You must be root to use the -u option");
  1686. }
  1687. pent = getpwnam(username);
  1688. if (pent == NULL) {
  1689. error_msg_and_die("Cannot find user '%s'", username);
  1690. }
  1691. run_uid = pent->pw_uid;
  1692. run_gid = pent->pw_gid;
  1693. } else {
  1694. run_uid = getuid();
  1695. run_gid = getgid();
  1696. }
  1697. if (followfork)
  1698. ptrace_setoptions |= PTRACE_O_TRACECLONE |
  1699. PTRACE_O_TRACEFORK |
  1700. PTRACE_O_TRACEVFORK;
  1701. if (seccomp_filtering)
  1702. check_seccomp_filter();
  1703. if (seccomp_filtering)
  1704. ptrace_setoptions |= PTRACE_O_TRACESECCOMP;
  1705. debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
  1706. test_ptrace_seize();
  1707. test_ptrace_get_syscall_info();
  1708. /*
  1709. * Is something weird with our stdin and/or stdout -
  1710. * for example, may they be not open? In this case,
  1711. * ensure that none of the future opens uses them.
  1712. *
  1713. * This was seen in the wild when /proc/sys/kernel/core_pattern
  1714. * was set to "|/bin/strace -o/tmp/LOG PROG":
  1715. * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
  1716. * therefore LOG gets opened to fd#1, and fd#1 is closed by
  1717. * "don't hold up stdin/out open" code soon after.
  1718. */
  1719. ensure_standard_fds_opened();
  1720. /* Check if they want to redirect the output. */
  1721. if (outfname) {
  1722. /* See if they want to pipe the output. */
  1723. if (outfname[0] == '|' || outfname[0] == '!') {
  1724. /*
  1725. * We can't do the <outfname>.PID funny business
  1726. * when using popen, so prohibit it.
  1727. */
  1728. if (followfork >= 2)
  1729. error_msg_and_help("piping the output and -ff "
  1730. "are mutually exclusive");
  1731. shared_log = strace_popen(outfname + 1);
  1732. } else if (followfork < 2) {
  1733. shared_log = strace_fopen(outfname);
  1734. } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
  1735. errno = ENAMETOOLONG;
  1736. perror_msg_and_die("%s", outfname);
  1737. }
  1738. } else {
  1739. /* -ff without -o FILE is the same as single -f */
  1740. if (followfork >= 2)
  1741. followfork = 1;
  1742. }
  1743. if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
  1744. setvbuf(shared_log, NULL, _IOLBF, 0);
  1745. }
  1746. /*
  1747. * argv[0] -pPID -oFILE Default interactive setting
  1748. * yes * 0 INTR_WHILE_WAIT
  1749. * no 1 0 INTR_WHILE_WAIT
  1750. * yes * 1 INTR_NEVER
  1751. * no 1 1 INTR_WHILE_WAIT
  1752. */
  1753. if (daemonized_tracer && !opt_intr)
  1754. opt_intr = INTR_BLOCK_TSTP_TOO;
  1755. if (outfname && argc) {
  1756. if (!opt_intr)
  1757. opt_intr = INTR_NEVER;
  1758. if (!qflag)
  1759. qflag = 1;
  1760. }
  1761. if (!opt_intr)
  1762. opt_intr = INTR_WHILE_WAIT;
  1763. /*
  1764. * startup_child() must be called before the signal handlers get
  1765. * installed below as they are inherited into the spawned process.
  1766. * Also we do not need to be protected by them as during interruption
  1767. * in the startup_child() mode we kill the spawned process anyway.
  1768. */
  1769. if (argc) {
  1770. startup_child(argv);
  1771. }
  1772. set_sighandler(SIGTTOU, SIG_IGN, NULL);
  1773. set_sighandler(SIGTTIN, SIG_IGN, NULL);
  1774. if (opt_intr != INTR_ANYWHERE) {
  1775. if (opt_intr == INTR_BLOCK_TSTP_TOO)
  1776. set_sighandler(SIGTSTP, SIG_IGN, NULL);
  1777. /*
  1778. * In interactive mode (if no -o OUTFILE, or -p PID is used),
  1779. * fatal signals are handled asynchronously and acted
  1780. * when waiting for process state changes.
  1781. * In non-interactive mode these signals are ignored.
  1782. */
  1783. set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
  1784. set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
  1785. set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
  1786. set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
  1787. set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
  1788. }
  1789. sigemptyset(&timer_set);
  1790. sigaddset(&timer_set, SIGALRM);
  1791. sigprocmask(SIG_BLOCK, &timer_set, NULL);
  1792. set_sighandler(SIGALRM, timer_sighandler, NULL);
  1793. if (nprocs != 0 || daemonized_tracer)
  1794. startup_attach();
  1795. /* Do we want pids printed in our -o OUTFILE?
  1796. * -ff: no (every pid has its own file); or
  1797. * -f: yes (there can be more pids in the future); or
  1798. * -p PID1,PID2: yes (there are already more than one pid)
  1799. */
  1800. print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
  1801. }
  1802. static struct tcb *
  1803. pid2tcb(const int pid)
  1804. {
  1805. if (pid <= 0)
  1806. return NULL;
  1807. #define PID2TCB_CACHE_SIZE 1024U
  1808. #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
  1809. static struct tcb *pid2tcb_cache[PID2TCB_CACHE_SIZE];
  1810. struct tcb **const ptcp = &pid2tcb_cache[pid & PID2TCB_CACHE_MASK];
  1811. struct tcb *tcp = *ptcp;
  1812. if (tcp && tcp->pid == pid)
  1813. return tcp;
  1814. for (unsigned int i = 0; i < tcbtabsize; ++i) {
  1815. tcp = tcbtab[i];
  1816. if (tcp->pid == pid)
  1817. return *ptcp = tcp;
  1818. }
  1819. return NULL;
  1820. }
  1821. static void
  1822. cleanup(int fatal_sig)
  1823. {
  1824. unsigned int i;
  1825. struct tcb *tcp;
  1826. if (!fatal_sig)
  1827. fatal_sig = SIGTERM;
  1828. for (i = 0; i < tcbtabsize; i++) {
  1829. tcp = tcbtab[i];
  1830. if (!tcp->pid)
  1831. continue;
  1832. debug_func_msg("looking at pid %u", tcp->pid);
  1833. if (tcp->pid == strace_child) {
  1834. kill(tcp->pid, SIGCONT);
  1835. kill(tcp->pid, fatal_sig);
  1836. }
  1837. detach(tcp);
  1838. }
  1839. }
  1840. static void
  1841. interrupt(int sig)
  1842. {
  1843. interrupted = sig;
  1844. }
  1845. static void
  1846. print_debug_info(const int pid, int status)
  1847. {
  1848. const unsigned int event = (unsigned int) status >> 16;
  1849. char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
  1850. char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
  1851. strcpy(buf, "???");
  1852. if (WIFSIGNALED(status))
  1853. xsprintf(buf, "WIFSIGNALED,%ssig=%s",
  1854. WCOREDUMP(status) ? "core," : "",
  1855. sprintsigname(WTERMSIG(status)));
  1856. if (WIFEXITED(status))
  1857. xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
  1858. if (WIFSTOPPED(status))
  1859. xsprintf(buf, "WIFSTOPPED,sig=%s",
  1860. sprintsigname(WSTOPSIG(status)));
  1861. evbuf[0] = '\0';
  1862. if (event != 0) {
  1863. static const char *const event_names[] = {
  1864. [PTRACE_EVENT_CLONE] = "CLONE",
  1865. [PTRACE_EVENT_FORK] = "FORK",
  1866. [PTRACE_EVENT_VFORK] = "VFORK",
  1867. [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
  1868. [PTRACE_EVENT_EXEC] = "EXEC",
  1869. [PTRACE_EVENT_EXIT] = "EXIT",
  1870. [PTRACE_EVENT_SECCOMP] = "SECCOMP",
  1871. /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
  1872. };
  1873. const char *e = "??";
  1874. if (event < ARRAY_SIZE(event_names))
  1875. e = event_names[event];
  1876. else if (event == PTRACE_EVENT_STOP)
  1877. e = "STOP";
  1878. xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
  1879. }
  1880. error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
  1881. }
  1882. static struct tcb *
  1883. maybe_allocate_tcb(const int pid, int status)
  1884. {
  1885. if (!WIFSTOPPED(status)) {
  1886. if (detach_on_execve && pid == strace_child) {
  1887. /* example: strace -bexecve sh -c 'exec true' */
  1888. strace_child = 0;
  1889. return NULL;
  1890. }
  1891. /*
  1892. * This can happen if we inherited an unknown child.
  1893. * Example: (sleep 1 & exec strace true)
  1894. */
  1895. error_msg("Exit of unknown pid %u ignored", pid);
  1896. return NULL;
  1897. }
  1898. if (followfork) {
  1899. /* We assume it's a fork/vfork/clone child */
  1900. struct tcb *tcp = alloctcb(pid);
  1901. after_successful_attach(tcp, post_attach_sigstop);
  1902. if (!qflag)
  1903. error_msg("Process %d attached", pid);
  1904. return tcp;
  1905. } else {
  1906. /*
  1907. * This can happen if a clone call misused CLONE_PTRACE itself.
  1908. *
  1909. * There used to be a dance around possible re-injection of
  1910. * WSTOPSIG(status), but it was later removed as the only
  1911. * observable stop here is the initial ptrace-stop.
  1912. */
  1913. ptrace(PTRACE_DETACH, pid, NULL, 0L);
  1914. error_msg("Detached unknown pid %d", pid);
  1915. return NULL;
  1916. }
  1917. }
  1918. /*
  1919. * Under Linux, execve changes pid to thread leader's pid, and we see this
  1920. * changed pid on EVENT_EXEC and later, execve sysexit. Leader "disappears"
  1921. * without exit notification. Let user know that, drop leader's tcb, and fix
  1922. * up pid in execve thread's tcb. Effectively, execve thread's tcb replaces
  1923. * leader's tcb.
  1924. *
  1925. * BTW, leader is 'stuck undead' (doesn't report WIFEXITED on exit syscall)
  1926. * in multi-threaded programs exactly in order to handle this case.
  1927. */
  1928. static struct tcb *
  1929. maybe_switch_tcbs(struct tcb *tcp, const int pid)
  1930. {
  1931. /*
  1932. * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
  1933. * On 2.6 and earlier it can return garbage.
  1934. */
  1935. if (os_release < KERNEL_VERSION(3, 0, 0))
  1936. return NULL;
  1937. const long old_pid = tcb_wait_tab[tcp->wait_data_idx].msg;
  1938. /* Avoid truncation in pid2tcb() param passing */
  1939. if (old_pid <= 0 || old_pid == pid)
  1940. return NULL;
  1941. if ((unsigned long) old_pid > UINT_MAX)
  1942. return NULL;
  1943. struct tcb *execve_thread = pid2tcb(old_pid);
  1944. /* It should be !NULL, but I feel paranoid */
  1945. if (!execve_thread)
  1946. return NULL;
  1947. if (execve_thread->curcol != 0) {
  1948. /*
  1949. * One case we are here is -ff, try
  1950. * "strace -oLOG -ff test/threaded_execve".
  1951. * Another case is demonstrated by
  1952. * tests/maybe_switch_current_tcp.c
  1953. */
  1954. fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
  1955. /*execve_thread->curcol = 0; - no need, see code below */
  1956. }
  1957. /* Swap output FILEs and memstream (needed for -ff) */
  1958. FILE *fp = execve_thread->outf;
  1959. execve_thread->outf = tcp->outf;
  1960. tcp->outf = fp;
  1961. if (execve_thread->staged_output_data || tcp->staged_output_data) {
  1962. struct staged_output_data *staged_output_data;
  1963. staged_output_data = execve_thread->staged_output_data;
  1964. execve_thread->staged_output_data = tcp->staged_output_data;
  1965. tcp->staged_output_data = staged_output_data;
  1966. }
  1967. /* And their column positions */
  1968. execve_thread->curcol = tcp->curcol;
  1969. tcp->curcol = 0;
  1970. /* Drop leader, but close execve'd thread outfile (if -ff) */
  1971. droptcb(tcp);
  1972. /* Switch to the thread, reusing leader's outfile and pid */
  1973. tcp = execve_thread;
  1974. tcp->pid = pid;
  1975. if (cflag != CFLAG_ONLY_STATS) {
  1976. printleader(tcp);
  1977. tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
  1978. line_ended();
  1979. /*
  1980. * Need to reopen memstream for thread
  1981. * as we closed it in droptcb.
  1982. */
  1983. if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
  1984. strace_open_memstream(tcp);
  1985. tcp->flags |= TCB_REPRINT;
  1986. }
  1987. return tcp;
  1988. }
  1989. static struct tcb *
  1990. maybe_switch_current_tcp(void)
  1991. {
  1992. struct tcb *tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
  1993. if (tcp)
  1994. set_current_tcp(tcp);
  1995. return tcp;
  1996. }
  1997. static void
  1998. print_signalled(struct tcb *tcp, const int pid, int status)
  1999. {
  2000. if (pid == strace_child) {
  2001. exit_code = 0x100 | WTERMSIG(status);
  2002. strace_child = 0;
  2003. }
  2004. if (cflag != CFLAG_ONLY_STATS
  2005. && is_number_in_set(WTERMSIG(status), signal_set)) {
  2006. printleader(tcp);
  2007. tprintf("+++ killed by %s %s+++\n",
  2008. sprintsigname(WTERMSIG(status)),
  2009. WCOREDUMP(status) ? "(core dumped) " : "");
  2010. line_ended();
  2011. }
  2012. }
  2013. static void
  2014. print_exited(struct tcb *tcp, const int pid, int status)
  2015. {
  2016. if (pid == strace_child) {
  2017. exit_code = WEXITSTATUS(status);
  2018. strace_child = 0;
  2019. }
  2020. if (cflag != CFLAG_ONLY_STATS &&
  2021. qflag < 2) {
  2022. printleader(tcp);
  2023. tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
  2024. line_ended();
  2025. }
  2026. }
  2027. static void
  2028. print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
  2029. {
  2030. if (cflag != CFLAG_ONLY_STATS
  2031. && !hide_log(tcp)
  2032. && is_number_in_set(sig, signal_set)) {
  2033. printleader(tcp);
  2034. if (si) {
  2035. tprintf("--- %s ", sprintsigname(sig));
  2036. printsiginfo(si);
  2037. tprints(" ---\n");
  2038. } else
  2039. tprintf("--- stopped by %s ---\n", sprintsigname(sig));
  2040. line_ended();
  2041. #ifdef ENABLE_STACKTRACE
  2042. if (stack_trace_enabled)
  2043. unwind_tcb_print(tcp);
  2044. #endif
  2045. }
  2046. }
  2047. static void
  2048. startup_tcb(struct tcb *tcp)
  2049. {
  2050. debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
  2051. tcp->flags &= ~TCB_STARTUP;
  2052. if (!use_seize) {
  2053. debug_msg("setting opts 0x%x on pid %d",
  2054. ptrace_setoptions, tcp->pid);
  2055. if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
  2056. if (errno != ESRCH) {
  2057. /* Should never happen, really */
  2058. perror_msg_and_die("PTRACE_SETOPTIONS");
  2059. }
  2060. }
  2061. }
  2062. if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
  2063. tcp->s_prev_ent = tcp->s_ent;
  2064. if (cflag) {
  2065. tcp->atime = tcp->stime;
  2066. }
  2067. }
  2068. static void
  2069. print_event_exit(struct tcb *tcp)
  2070. {
  2071. if (entering(tcp) || filtered(tcp) || hide_log(tcp)
  2072. || cflag == CFLAG_ONLY_STATS) {
  2073. return;
  2074. }
  2075. if (followfork < 2 && printing_tcp && printing_tcp != tcp
  2076. && printing_tcp->curcol != 0) {
  2077. set_current_tcp(printing_tcp);
  2078. tprints(" <unfinished ...>\n");
  2079. flush_tcp_output(printing_tcp);
  2080. printing_tcp->curcol = 0;
  2081. set_current_tcp(tcp);
  2082. }
  2083. print_syscall_resume(tcp);
  2084. if (!(tcp->sys_func_rval & RVAL_DECODED)) {
  2085. /*
  2086. * The decoder has probably decided to print something
  2087. * on exiting syscall which is not going to happen.
  2088. */
  2089. tprints(" <unfinished ...>");
  2090. }
  2091. printing_tcp = tcp;
  2092. tprints(") ");
  2093. tabto();
  2094. tprints("= ?\n");
  2095. if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
  2096. bool publish = is_number_in_set(STATUS_UNFINISHED, status_set);
  2097. strace_close_memstream(tcp, publish);
  2098. }
  2099. line_ended();
  2100. }
  2101. static size_t
  2102. trace_wait_data_size(struct tcb *tcp)
  2103. {
  2104. return sizeof(struct tcb_wait_data);
  2105. }
  2106. static struct tcb_wait_data *
  2107. init_trace_wait_data(void *p)
  2108. {
  2109. struct tcb_wait_data *wd = p;
  2110. memset(wd, 0, sizeof(*wd));
  2111. return wd;
  2112. }
  2113. static struct tcb_wait_data *
  2114. copy_trace_wait_data(const struct tcb_wait_data *wd)
  2115. {
  2116. struct tcb_wait_data *new_wd = xmalloc(sizeof(*new_wd));
  2117. memcpy(new_wd, wd, sizeof(*wd));
  2118. return new_wd;
  2119. }
  2120. static void
  2121. free_trace_wait_data(struct tcb_wait_data *wd)
  2122. {
  2123. free(wd);
  2124. }
  2125. static void
  2126. tcb_wait_tab_check_size(const size_t size)
  2127. {
  2128. while (size >= tcb_wait_tab_size) {
  2129. tcb_wait_tab = xgrowarray(tcb_wait_tab,
  2130. &tcb_wait_tab_size,
  2131. sizeof(tcb_wait_tab[0]));
  2132. }
  2133. }
  2134. static const struct tcb_wait_data *
  2135. next_event(void)
  2136. {
  2137. if (interrupted)
  2138. return NULL;
  2139. invalidate_umove_cache();
  2140. struct tcb *tcp = NULL;
  2141. struct list_item *elem;
  2142. static EMPTY_LIST(pending_tcps);
  2143. /* Handle the queued tcbs before waiting for new events. */
  2144. if (!list_is_empty(&pending_tcps))
  2145. goto next_event_get_tcp;
  2146. static struct tcb *extra_tcp;
  2147. static size_t wait_extra_data_idx;
  2148. /* Handle the extra tcb event. */
  2149. if (extra_tcp) {
  2150. tcp = extra_tcp;
  2151. extra_tcp = NULL;
  2152. tcp->wait_data_idx = wait_extra_data_idx;
  2153. debug_msg("dequeued extra event for pid %u", tcp->pid);
  2154. goto next_event_exit;
  2155. }
  2156. /*
  2157. * Used to exit simply when nprocs hits zero, but in this testcase:
  2158. * int main(void) { _exit(!!fork()); }
  2159. * under strace -f, parent sometimes (rarely) manages
  2160. * to exit before we see the first stop of the child,
  2161. * and we are losing track of it:
  2162. * 19923 clone(...) = 19924
  2163. * 19923 exit_group(1) = ?
  2164. * 19923 +++ exited with 1 +++
  2165. * Exiting only when wait() returns ECHILD works better.
  2166. */
  2167. if (popen_pid != 0) {
  2168. /* However, if -o|logger is in use, we can't do that.
  2169. * Can work around that by double-forking the logger,
  2170. * but that loses the ability to wait for its completion
  2171. * on exit. Oh well...
  2172. */
  2173. if (nprocs == 0)
  2174. return NULL;
  2175. }
  2176. const bool unblock_delay_timer = is_delay_timer_armed();
  2177. /*
  2178. * The window of opportunity to handle expirations
  2179. * of the delay timer opens here.
  2180. *
  2181. * Unblock the signal handler for the delay timer
  2182. * iff the delay timer is already created.
  2183. */
  2184. if (unblock_delay_timer)
  2185. sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
  2186. /*
  2187. * If the delay timer has expired, then its expiration
  2188. * has been handled already by the signal handler.
  2189. *
  2190. * If the delay timer expires during wait4(),
  2191. * then the system call will be interrupted and
  2192. * the expiration will be handled by the signal handler.
  2193. */
  2194. int status;
  2195. struct rusage ru;
  2196. int pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
  2197. int wait_errno = errno;
  2198. /*
  2199. * The window of opportunity to handle expirations
  2200. * of the delay timer closes here.
  2201. *
  2202. * Block the signal handler for the delay timer
  2203. * iff it was unblocked earlier.
  2204. */
  2205. if (unblock_delay_timer) {
  2206. sigprocmask(SIG_BLOCK, &timer_set, NULL);
  2207. if (restart_failed)
  2208. return NULL;
  2209. }
  2210. size_t wait_tab_pos = 0;
  2211. bool wait_nohang = false;
  2212. /*
  2213. * Wait for new events until wait4() returns 0 (meaning that there's
  2214. * nothing more to wait for for now), or a second event for some tcb
  2215. * appears (which may happen if a tracee was SIGKILL'ed, for example).
  2216. */
  2217. for (;;) {
  2218. struct tcb_wait_data *wd;
  2219. if (pid < 0) {
  2220. if (wait_errno == EINTR)
  2221. break;
  2222. if (wait_nohang)
  2223. break;
  2224. if (nprocs == 0 && wait_errno == ECHILD)
  2225. return NULL;
  2226. /*
  2227. * If nprocs > 0, ECHILD is not expected,
  2228. * treat it as any other error here:
  2229. */
  2230. errno = wait_errno;
  2231. perror_msg_and_die("wait4(__WALL)");
  2232. }
  2233. if (!pid)
  2234. break;
  2235. if (pid == popen_pid) {
  2236. if (!WIFSTOPPED(status))
  2237. popen_pid = 0;
  2238. break;
  2239. }
  2240. if (debug_flag)
  2241. print_debug_info(pid, status);
  2242. /* Look up 'pid' in our table. */
  2243. tcp = pid2tcb(pid);
  2244. if (!tcp) {
  2245. tcp = maybe_allocate_tcb(pid, status);
  2246. if (!tcp)
  2247. goto next_event_wait_next;
  2248. }
  2249. if (cflag) {
  2250. tcp->stime.tv_sec = ru.ru_stime.tv_sec;
  2251. tcp->stime.tv_nsec = ru.ru_stime.tv_usec * 1000;
  2252. }
  2253. tcb_wait_tab_check_size(wait_tab_pos);
  2254. /* Initialise a new wait data structure. */
  2255. wd = tcb_wait_tab + wait_tab_pos;
  2256. init_trace_wait_data(wd);
  2257. wd->status = status;
  2258. if (WIFSIGNALED(status)) {
  2259. wd->te = TE_SIGNALLED;
  2260. } else if (WIFEXITED(status)) {
  2261. wd->te = TE_EXITED;
  2262. } else {
  2263. /*
  2264. * As WCONTINUED flag has not been specified to wait4,
  2265. * it cannot be WIFCONTINUED(status), so the only case
  2266. * that remains is WIFSTOPPED(status).
  2267. */
  2268. const unsigned int sig = WSTOPSIG(status);
  2269. const unsigned int event = (unsigned int) status >> 16;
  2270. switch (event) {
  2271. case 0:
  2272. /*
  2273. * Is this post-attach SIGSTOP?
  2274. * Interestingly, the process may stop
  2275. * with STOPSIG equal to some other signal
  2276. * than SIGSTOP if we happened to attach
  2277. * just before the process takes a signal.
  2278. */
  2279. if (sig == SIGSTOP &&
  2280. (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
  2281. debug_func_msg("ignored SIGSTOP on "
  2282. "pid %d", tcp->pid);
  2283. tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
  2284. wd->te = TE_RESTART;
  2285. } else if (sig == syscall_trap_sig) {
  2286. wd->te = TE_SYSCALL_STOP;
  2287. } else {
  2288. /*
  2289. * True if tracee is stopped by signal
  2290. * (as opposed to "tracee received
  2291. * signal").
  2292. * TODO: shouldn't we check for
  2293. * errno == EINVAL too?
  2294. * We can get ESRCH instead, you know...
  2295. */
  2296. bool stopped = ptrace(PTRACE_GETSIGINFO,
  2297. pid, 0, &wd->si) < 0;
  2298. wd->te = stopped ? TE_GROUP_STOP
  2299. : TE_SIGNAL_DELIVERY_STOP;
  2300. }
  2301. break;
  2302. case PTRACE_EVENT_STOP:
  2303. /*
  2304. * PTRACE_INTERRUPT-stop or group-stop.
  2305. * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
  2306. */
  2307. switch (sig) {
  2308. case SIGSTOP:
  2309. case SIGTSTP:
  2310. case SIGTTIN:
  2311. case SIGTTOU:
  2312. wd->te = TE_GROUP_STOP;
  2313. break;
  2314. default:
  2315. wd->te = TE_RESTART;
  2316. }
  2317. break;
  2318. case PTRACE_EVENT_EXEC:
  2319. /*
  2320. * TODO: shouldn't we check for
  2321. * errno == EINVAL here, too?
  2322. * We can get ESRCH instead, you know...
  2323. */
  2324. if (ptrace(PTRACE_GETEVENTMSG, pid, NULL,
  2325. &wd->msg) < 0)
  2326. wd->msg = 0;
  2327. wd->te = TE_STOP_BEFORE_EXECVE;
  2328. break;
  2329. case PTRACE_EVENT_EXIT:
  2330. wd->te = TE_STOP_BEFORE_EXIT;
  2331. break;
  2332. case PTRACE_EVENT_SECCOMP:
  2333. wd->te = TE_SECCOMP;
  2334. break;
  2335. default:
  2336. wd->te = TE_RESTART;
  2337. }
  2338. }
  2339. if (!wd->te)
  2340. error_func_msg("Tracing event hasn't been determined "
  2341. "for pid %d, status %0#x", pid, status);
  2342. if (!list_is_empty(&tcp->wait_list)) {
  2343. wait_extra_data_idx = wait_tab_pos;
  2344. extra_tcp = tcp;
  2345. debug_func_msg("queued extra pid %d", tcp->pid);
  2346. } else {
  2347. tcp->wait_data_idx = wait_tab_pos;
  2348. list_append(&pending_tcps, &tcp->wait_list);
  2349. debug_func_msg("queued pid %d", tcp->pid);
  2350. }
  2351. wait_tab_pos++;
  2352. if (extra_tcp)
  2353. break;
  2354. next_event_wait_next:
  2355. pid = wait4(-1, &status, __WALL | WNOHANG, (cflag ? &ru : NULL));
  2356. wait_errno = errno;
  2357. wait_nohang = true;
  2358. }
  2359. next_event_get_tcp:
  2360. elem = list_remove_head(&pending_tcps);
  2361. if (!elem) {
  2362. tcb_wait_tab_check_size(0);
  2363. memset(tcb_wait_tab, 0, sizeof(*tcb_wait_tab));
  2364. tcb_wait_tab->te = TE_NEXT;
  2365. return tcb_wait_tab;
  2366. } else {
  2367. tcp = list_elem(elem, struct tcb, wait_list);
  2368. debug_func_msg("dequeued pid %d", tcp->pid);
  2369. }
  2370. next_event_exit:
  2371. /* Is this the very first time we see this tracee stopped? */
  2372. if (tcp->flags & TCB_STARTUP)
  2373. startup_tcb(tcp);
  2374. clear_regs(tcp);
  2375. /* Set current output file */
  2376. set_current_tcp(tcp);
  2377. return tcb_wait_tab + tcp->wait_data_idx;
  2378. }
  2379. static int
  2380. trace_syscall(struct tcb *tcp, unsigned int *sig)
  2381. {
  2382. if (entering(tcp)) {
  2383. int res = syscall_entering_decode(tcp);
  2384. switch (res) {
  2385. case 0:
  2386. return 0;
  2387. case 1:
  2388. res = syscall_entering_trace(tcp, sig);
  2389. }
  2390. syscall_entering_finish(tcp, res);
  2391. return res;
  2392. } else {
  2393. struct timespec ts = {};
  2394. int res = syscall_exiting_decode(tcp, &ts);
  2395. if (res != 0) {
  2396. res = syscall_exiting_trace(tcp, &ts, res);
  2397. }
  2398. syscall_exiting_finish(tcp);
  2399. return res;
  2400. }
  2401. }
  2402. /* Returns true iff the main trace loop has to continue. */
  2403. static bool
  2404. dispatch_event(const struct tcb_wait_data *wd)
  2405. {
  2406. unsigned int restart_op;
  2407. unsigned int restart_sig = 0;
  2408. enum trace_event te = wd ? wd->te : TE_BREAK;
  2409. /*
  2410. * Copy wd->status to a non-const variable to workaround glibc bugs
  2411. * around union wait fixed by glibc commit glibc-2.24~391
  2412. */
  2413. int status = wd ? wd->status : 0;
  2414. if (current_tcp && has_seccomp_filter(current_tcp))
  2415. restart_op = seccomp_filter_restart_operator(current_tcp);
  2416. else
  2417. restart_op = PTRACE_SYSCALL;
  2418. switch (te) {
  2419. case TE_BREAK:
  2420. return false;
  2421. case TE_NEXT:
  2422. return true;
  2423. case TE_RESTART:
  2424. break;
  2425. case TE_SECCOMP:
  2426. if (!has_seccomp_filter(current_tcp)) {
  2427. /*
  2428. * We don't know if forks/clones have a seccomp filter
  2429. * when they are created, but we can detect it when we
  2430. * have a seccomp-stop.
  2431. * In such a case, if !seccomp_before_sysentry, we have
  2432. * already processed the syscall entry, so we avoid
  2433. * processing it a second time.
  2434. */
  2435. current_tcp->flags |= TCB_SECCOMP_FILTER;
  2436. restart_op = PTRACE_SYSCALL;
  2437. break;
  2438. }
  2439. if (seccomp_before_sysentry) {
  2440. restart_op = PTRACE_SYSCALL;
  2441. break;
  2442. }
  2443. ATTRIBUTE_FALLTHROUGH;
  2444. case TE_SYSCALL_STOP:
  2445. if (trace_syscall(current_tcp, &restart_sig) < 0) {
  2446. /*
  2447. * ptrace() failed in trace_syscall().
  2448. * Likely a result of process disappearing mid-flight.
  2449. * Observed case: exit_group() or SIGKILL terminating
  2450. * all processes in thread group.
  2451. * We assume that ptrace error was caused by process death.
  2452. * We used to detach(current_tcp) here, but since we no
  2453. * longer implement "detach before death" policy/hack,
  2454. * we can let this process to report its death to us
  2455. * normally, via WIFEXITED or WIFSIGNALED wait status.
  2456. */
  2457. return true;
  2458. }
  2459. if (has_seccomp_filter(current_tcp)) {
  2460. /*
  2461. * Syscall and seccomp stops can happen in different
  2462. * orders depending on kernel. strace tests this in
  2463. * check_seccomp_order_tracer().
  2464. *
  2465. * Linux 3.5--4.7:
  2466. * (seccomp-stop before syscall-entry-stop)
  2467. * +--> seccomp-stop ->-PTRACE_SYSCALL->-+
  2468. * | |
  2469. * PTRACE_CONT syscall-entry-stop
  2470. * | |
  2471. * syscall-exit-stop <---PTRACE_SYSCALL-----<----+
  2472. *
  2473. * Linux 4.8+:
  2474. * (seccomp-stop after syscall-entry-stop)
  2475. * syscall-entry-stop
  2476. *
  2477. * +---->-----PTRACE_CONT---->----+
  2478. * | |
  2479. * syscall-exit-stop seccomp-stop
  2480. * | |
  2481. * +----<----PTRACE_SYSCALL---<---+
  2482. *
  2483. * Note in Linux 4.8+, we restart in PTRACE_CONT
  2484. * after syscall-exit to skip the syscall-entry-stop.
  2485. * The next seccomp-stop will be treated as a syscall
  2486. * entry.
  2487. *
  2488. * The line below implements this behavior.
  2489. * Note that exiting(current_tcp) actually marks
  2490. * a syscall-entry-stop because the flag was inverted
  2491. * in the above call to trace_syscall.
  2492. */
  2493. restart_op = exiting(current_tcp) ? PTRACE_SYSCALL : PTRACE_CONT;
  2494. }
  2495. break;
  2496. case TE_SIGNAL_DELIVERY_STOP:
  2497. restart_sig = WSTOPSIG(status);
  2498. print_stopped(current_tcp, &wd->si, restart_sig);
  2499. break;
  2500. case TE_SIGNALLED:
  2501. print_signalled(current_tcp, current_tcp->pid, status);
  2502. droptcb(current_tcp);
  2503. return true;
  2504. case TE_GROUP_STOP:
  2505. restart_sig = WSTOPSIG(status);
  2506. print_stopped(current_tcp, NULL, restart_sig);
  2507. if (use_seize) {
  2508. /*
  2509. * This ends ptrace-stop, but does *not* end group-stop.
  2510. * This makes stopping signals work properly on straced
  2511. * process (that is, process really stops. It used to
  2512. * continue to run).
  2513. */
  2514. restart_op = PTRACE_LISTEN;
  2515. restart_sig = 0;
  2516. }
  2517. break;
  2518. case TE_EXITED:
  2519. print_exited(current_tcp, current_tcp->pid, status);
  2520. droptcb(current_tcp);
  2521. return true;
  2522. case TE_STOP_BEFORE_EXECVE:
  2523. /* The syscall succeeded, clear the flag. */
  2524. current_tcp->flags &= ~TCB_CHECK_EXEC_SYSCALL;
  2525. /*
  2526. * Check that we are inside syscall now (next event after
  2527. * PTRACE_EVENT_EXEC should be for syscall exiting). If it is
  2528. * not the case, we might have a situation when we attach to a
  2529. * process and the first thing we see is a PTRACE_EVENT_EXEC
  2530. * and all the following syscall state tracking is screwed up
  2531. * otherwise.
  2532. */
  2533. if (!maybe_switch_current_tcp() && entering(current_tcp)) {
  2534. int ret;
  2535. error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
  2536. ", trying to recover...",
  2537. current_tcp->pid);
  2538. current_tcp->flags |= TCB_RECOVERING;
  2539. ret = trace_syscall(current_tcp, &restart_sig);
  2540. current_tcp->flags &= ~TCB_RECOVERING;
  2541. if (ret < 0) {
  2542. /* The reason is described in TE_SYSCALL_STOP */
  2543. return true;
  2544. }
  2545. }
  2546. if (detach_on_execve) {
  2547. if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
  2548. current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
  2549. } else {
  2550. detach(current_tcp); /* do "-b execve" thingy */
  2551. return true;
  2552. }
  2553. }
  2554. break;
  2555. case TE_STOP_BEFORE_EXIT:
  2556. print_event_exit(current_tcp);
  2557. break;
  2558. }
  2559. /* We handled quick cases, we are permitted to interrupt now. */
  2560. if (interrupted)
  2561. return false;
  2562. /* If the process is being delayed, do not ptrace_restart just yet */
  2563. if (syscall_delayed(current_tcp)) {
  2564. if (current_tcp->delayed_wait_data)
  2565. error_func_msg("pid %d has delayed wait data set"
  2566. " already", current_tcp->pid);
  2567. current_tcp->delayed_wait_data = copy_trace_wait_data(wd);
  2568. return true;
  2569. }
  2570. if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
  2571. /* Note: ptrace_restart emitted error message */
  2572. exit_code = 1;
  2573. return false;
  2574. }
  2575. return true;
  2576. }
  2577. static bool
  2578. restart_delayed_tcb(struct tcb *const tcp)
  2579. {
  2580. struct tcb_wait_data *wd = tcp->delayed_wait_data;
  2581. if (!wd) {
  2582. error_func_msg("No delayed wait data found for pid %d",
  2583. tcp->pid);
  2584. wd = init_trace_wait_data(alloca(trace_wait_data_size(tcp)));
  2585. }
  2586. wd->te = TE_RESTART;
  2587. debug_func_msg("pid %d", tcp->pid);
  2588. tcp->flags &= ~TCB_DELAYED;
  2589. struct tcb *const prev_tcp = current_tcp;
  2590. current_tcp = tcp;
  2591. bool ret = dispatch_event(wd);
  2592. current_tcp = prev_tcp;
  2593. free_trace_wait_data(tcp->delayed_wait_data);
  2594. tcp->delayed_wait_data = NULL;
  2595. return ret;
  2596. }
  2597. static bool
  2598. restart_delayed_tcbs(void)
  2599. {
  2600. struct tcb *tcp_next = NULL;
  2601. struct timespec ts_now;
  2602. clock_gettime(CLOCK_MONOTONIC, &ts_now);
  2603. for (size_t i = 0; i < tcbtabsize; i++) {
  2604. struct tcb *tcp = tcbtab[i];
  2605. if (tcp->pid && syscall_delayed(tcp)) {
  2606. if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
  2607. if (!restart_delayed_tcb(tcp))
  2608. return false;
  2609. } else {
  2610. /* Check whether this tcb is the next. */
  2611. if (!tcp_next ||
  2612. ts_cmp(&tcp_next->delay_expiration_time,
  2613. &tcp->delay_expiration_time) > 0) {
  2614. tcp_next = tcp;
  2615. }
  2616. }
  2617. }
  2618. }
  2619. if (tcp_next)
  2620. arm_delay_timer(tcp_next);
  2621. return true;
  2622. }
  2623. /*
  2624. * As this signal handler does a lot of work that is not suitable
  2625. * for signal handlers, extra care must be taken to ensure that
  2626. * it is enabled only in those places where it's safe.
  2627. */
  2628. static void
  2629. timer_sighandler(int sig)
  2630. {
  2631. delay_timer_expired();
  2632. if (restart_failed)
  2633. return;
  2634. int saved_errno = errno;
  2635. if (!restart_delayed_tcbs())
  2636. restart_failed = 1;
  2637. errno = saved_errno;
  2638. }
  2639. static void ATTRIBUTE_NORETURN
  2640. terminate(void)
  2641. {
  2642. int sig = interrupted;
  2643. cleanup(sig);
  2644. if (cflag)
  2645. call_summary(shared_log);
  2646. fflush(NULL);
  2647. if (shared_log != stderr)
  2648. fclose(shared_log);
  2649. if (popen_pid) {
  2650. while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
  2651. ;
  2652. }
  2653. if (sig) {
  2654. exit_code = 0x100 | sig;
  2655. }
  2656. if (exit_code > 0xff) {
  2657. /* Avoid potential core file clobbering. */
  2658. struct_rlimit rlim = {0, 0};
  2659. set_rlimit(RLIMIT_CORE, &rlim);
  2660. /* Child was killed by a signal, mimic that. */
  2661. exit_code &= 0xff;
  2662. signal(exit_code, SIG_DFL);
  2663. GCOV_DUMP;
  2664. raise(exit_code);
  2665. /* Unblock the signal. */
  2666. sigset_t mask;
  2667. sigemptyset(&mask);
  2668. sigaddset(&mask, exit_code);
  2669. GCOV_DUMP;
  2670. sigprocmask(SIG_UNBLOCK, &mask, NULL);
  2671. /* Paranoia - what if this signal is not fatal?
  2672. Exit with 128 + signo then. */
  2673. exit_code += 128;
  2674. }
  2675. exit(exit_code);
  2676. }
  2677. int
  2678. main(int argc, char *argv[])
  2679. {
  2680. setlocale(LC_ALL, "");
  2681. init(argc, argv);
  2682. exit_code = !nprocs;
  2683. while (dispatch_event(next_event()))
  2684. ;
  2685. terminate();
  2686. }