LinuxProcessTable.c 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831
  1. /*
  2. htop - LinuxProcessTable.c
  3. (C) 2014 Hisham H. Muhammad
  4. Released under the GNU GPLv2+, see the COPYING file
  5. in the source distribution for its full text.
  6. */
  7. #include "config.h" // IWYU pragma: keep
  8. #include "linux/LinuxProcessTable.h"
  9. #include <assert.h>
  10. #include <ctype.h>
  11. #include <dirent.h>
  12. #include <fcntl.h>
  13. #include <inttypes.h>
  14. #include <limits.h>
  15. #include <math.h>
  16. #include <stdbool.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <syscall.h>
  21. #include <unistd.h>
  22. #include <linux/capability.h> // raw syscall, no libcap // IWYU pragma: keep // IWYU pragma: no_include <sys/capability.h>
  23. #include <sys/stat.h>
  24. #include "Compat.h"
  25. #include "Hashtable.h"
  26. #include "Machine.h"
  27. #include "Macros.h"
  28. #include "Object.h"
  29. #include "Process.h"
  30. #include "Row.h"
  31. #include "RowField.h"
  32. #include "Scheduling.h"
  33. #include "Settings.h"
  34. #include "Table.h"
  35. #include "UsersTable.h"
  36. #include "XUtils.h"
  37. #include "linux/CGroupUtils.h"
  38. #include "linux/GPU.h"
  39. #include "linux/GPUMeter.h"
  40. #include "linux/LinuxMachine.h"
  41. #include "linux/LinuxProcess.h"
  42. #include "linux/Platform.h" // needed for GNU/hurd to get PATH_MAX // IWYU pragma: keep
  43. #ifdef HAVE_DELAYACCT
  44. #include "linux/LibNl.h"
  45. #endif
  46. #if defined(MAJOR_IN_MKDEV)
  47. #include <sys/mkdev.h>
  48. #elif defined(MAJOR_IN_SYSMACROS)
  49. #include <sys/sysmacros.h>
  50. #endif
  51. /* Not exposed yet. Defined at include/linux/sched.h */
  52. #ifndef PF_KTHREAD
  53. #define PF_KTHREAD 0x00200000
  54. #endif
  55. /* Inode number of the PID namespace of htop */
  56. static ino_t rootPidNs = (ino_t)-1;
  57. static FILE* fopenat(openat_arg_t openatArg, const char* pathname, const char* mode) {
  58. assert(String_eq(mode, "r")); /* only currently supported mode */
  59. int fd = Compat_openat(openatArg, pathname, O_RDONLY);
  60. if (fd < 0)
  61. return NULL;
  62. FILE* fp = fdopen(fd, mode);
  63. if (!fp)
  64. close(fd);
  65. return fp;
  66. }
  67. static inline uint64_t fast_strtoull_dec(char** str, int maxlen) {
  68. uint64_t result = 0;
  69. if (!maxlen)
  70. maxlen = 20; // length of maximum value of 18446744073709551615
  71. while (maxlen-- && **str >= '0' && **str <= '9') {
  72. result *= 10;
  73. result += **str - '0';
  74. (*str)++;
  75. }
  76. return result;
  77. }
  78. static long long fast_strtoll_dec(char** str, int maxlen) {
  79. bool neg = false;
  80. if (**str == '-') {
  81. neg = true;
  82. (*str)++;
  83. }
  84. unsigned long long res = fast_strtoull_dec(str, maxlen);
  85. assert(res <= LLONG_MAX);
  86. long long result = (long long)res;
  87. return neg ? -result : result;
  88. }
  89. static long fast_strtol_dec(char** str, int maxlen) {
  90. long long result = fast_strtoll_dec(str, maxlen);
  91. assert(result <= LONG_MAX);
  92. assert(result >= LONG_MIN);
  93. return (long)result;
  94. }
  95. static unsigned long fast_strtoul_dec(char** str, int maxlen) {
  96. unsigned long long result = fast_strtoull_dec(str, maxlen);
  97. assert(result <= ULONG_MAX);
  98. return (unsigned long)result;
  99. }
  100. static inline uint64_t fast_strtoull_hex(char** str, int maxlen) {
  101. register uint64_t result = 0;
  102. register int nibble, letter;
  103. const long valid_mask = 0x03FF007E;
  104. if (!maxlen)
  105. --maxlen;
  106. while (maxlen--) {
  107. nibble = (unsigned char)**str;
  108. if (!(valid_mask & (1 << (nibble & 0x1F))))
  109. break;
  110. if ((nibble < '0') || (nibble & ~0x20) > 'F')
  111. break;
  112. letter = (nibble & 0x40) ? 'A' - '9' - 1 : 0;
  113. nibble &=~0x20; // to upper
  114. nibble ^= 0x10; // switch letters and digits
  115. nibble -= letter;
  116. nibble &= 0x0f;
  117. result <<= 4;
  118. result += (uint64_t)nibble;
  119. (*str)++;
  120. }
  121. return result;
  122. }
  123. static int sortTtyDrivers(const void* va, const void* vb) {
  124. const TtyDriver* a = (const TtyDriver*) va;
  125. const TtyDriver* b = (const TtyDriver*) vb;
  126. int r = SPACESHIP_NUMBER(a->major, b->major);
  127. if (r)
  128. return r;
  129. return SPACESHIP_NUMBER(a->minorFrom, b->minorFrom);
  130. }
  131. static void LinuxProcessTable_initTtyDrivers(LinuxProcessTable* this) {
  132. TtyDriver* ttyDrivers;
  133. char buf[16384];
  134. ssize_t r = xReadfile(PROCTTYDRIVERSFILE, buf, sizeof(buf));
  135. if (r < 0)
  136. return;
  137. size_t numDrivers = 0;
  138. size_t allocd = 10;
  139. ttyDrivers = xMallocArray(allocd, sizeof(TtyDriver));
  140. char* at = buf;
  141. char* path = NULL;
  142. while (at && *at != '\0') {
  143. /*
  144. * Format:
  145. * [name] [node path] [major] [minor range] [type]
  146. * serial /dev/ttyS 4 64-95 serial
  147. */
  148. at = strchr(at, ' '); // skip first token
  149. if (!at)
  150. goto finish; // bail out on truncation
  151. while (*at == ' ') at++; // skip spaces
  152. const char* token = at; // mark beginning of path
  153. at = strchr(at, ' '); // find end of path
  154. if (!at)
  155. goto finish; // bail out on truncation
  156. *at = '\0'; at++; // clear and skip
  157. path = xStrdup(token); // save
  158. while (*at == ' ') at++; // skip spaces
  159. token = at; // mark beginning of major
  160. at = strchr(at, ' '); // find end of major
  161. if (!at)
  162. goto finish; // bail out on truncation
  163. *at = '\0'; at++; // clear and skip
  164. ttyDrivers[numDrivers].major = atoi(token); // save
  165. while (*at == ' ') at++; // skip spaces
  166. token = at; // mark beginning of minorFrom
  167. while (*at >= '0' && *at <= '9') at++; //find end of minorFrom
  168. if (*at == '-') { // if has range
  169. *at = '\0'; at++; // clear and skip
  170. ttyDrivers[numDrivers].minorFrom = atoi(token); // save
  171. token = at; // mark beginning of minorTo
  172. at = strchr(at, ' '); // find end of minorTo
  173. if (!at)
  174. goto finish; // bail out on truncation
  175. *at = '\0'; at++; // clear and skip
  176. ttyDrivers[numDrivers].minorTo = atoi(token); // save
  177. } else { // no range
  178. *at = '\0'; at++; // clear and skip
  179. ttyDrivers[numDrivers].minorFrom = atoi(token); // save
  180. ttyDrivers[numDrivers].minorTo = atoi(token); // save
  181. }
  182. at = strchr(at, '\n'); // go to end of line
  183. if (at)
  184. at++; // skip
  185. ttyDrivers[numDrivers].path = path;
  186. path = NULL;
  187. numDrivers++;
  188. if (numDrivers == allocd) {
  189. allocd += 10;
  190. ttyDrivers = xReallocArray(ttyDrivers, allocd, sizeof(TtyDriver));
  191. }
  192. }
  193. finish:
  194. free(path);
  195. ttyDrivers = xRealloc(ttyDrivers, sizeof(TtyDriver) * (numDrivers + 1));
  196. ttyDrivers[numDrivers].path = NULL;
  197. qsort(ttyDrivers, numDrivers, sizeof(TtyDriver), sortTtyDrivers);
  198. this->ttyDrivers = ttyDrivers;
  199. }
  200. ProcessTable* ProcessTable_new(Machine* host, Hashtable* pidMatchList) {
  201. LinuxProcessTable* this = xCalloc(1, sizeof(LinuxProcessTable));
  202. Object_setClass(this, Class(ProcessTable));
  203. ProcessTable* super = &this->super;
  204. ProcessTable_init(super, Class(LinuxProcess), host, pidMatchList);
  205. LinuxProcessTable_initTtyDrivers(this);
  206. // Test /proc/PID/smaps_rollup availability (faster to parse, Linux 4.14+)
  207. this->haveSmapsRollup = (access(PROCDIR "/self/smaps_rollup", R_OK) == 0);
  208. // Read PID namespace inode number
  209. {
  210. struct stat sb;
  211. int r = stat(PROCDIR "/self/ns/pid", &sb);
  212. if (r == 0) {
  213. rootPidNs = sb.st_ino;
  214. } else {
  215. rootPidNs = (ino_t)-1;
  216. }
  217. }
  218. return super;
  219. }
  220. void ProcessTable_delete(Object* cast) {
  221. LinuxProcessTable* this = (LinuxProcessTable*) cast;
  222. ProcessTable_done(&this->super);
  223. if (this->ttyDrivers) {
  224. for (int i = 0; this->ttyDrivers[i].path; i++) {
  225. free(this->ttyDrivers[i].path);
  226. }
  227. free(this->ttyDrivers);
  228. }
  229. #ifdef HAVE_DELAYACCT
  230. LibNl_destroyNetlinkSocket(this);
  231. #endif
  232. free(this);
  233. }
  234. static inline unsigned long long LinuxProcessTable_adjustTime(const LinuxMachine* lhost, unsigned long long t) {
  235. return t * 100 / lhost->jiffies;
  236. }
  237. /* Taken from: https://github.com/torvalds/linux/blob/64570fbc14f8d7cb3fe3995f20e26bc25ce4b2cc/fs/proc/array.c#L120 */
  238. static inline ProcessState LinuxProcessTable_getProcessState(char state) {
  239. switch (state) {
  240. case 'S': return SLEEPING;
  241. case 'X': return DEFUNCT;
  242. case 'Z': return ZOMBIE;
  243. case 't': return TRACED;
  244. case 'T': return STOPPED;
  245. case 'D': return UNINTERRUPTIBLE_WAIT;
  246. case 'R': return RUNNING;
  247. case 'P': return BLOCKED;
  248. case 'I': return IDLE;
  249. default: return UNKNOWN;
  250. }
  251. }
  252. /*
  253. * Read /proc/<pid>/stat (thread-specific data)
  254. */
  255. static bool LinuxProcessTable_readStatFile(LinuxProcess* lp, openat_arg_t procFd, const LinuxMachine* lhost, bool scanMainThread, char* command, size_t commLen) {
  256. Process* process = &lp->super;
  257. char buf[MAX_READ + 1];
  258. char path[22] = "stat";
  259. if (scanMainThread) {
  260. xSnprintf(path, sizeof(path), "task/%"PRIi32"/stat", (int32_t)Process_getPid(process));
  261. }
  262. ssize_t r = xReadfileat(procFd, path, buf, sizeof(buf));
  263. if (r < 0)
  264. return false;
  265. /* (1) pid - %d */
  266. assert(Process_getPid(process) == atoi(buf));
  267. char* location = strchr(buf, ' ');
  268. if (!location)
  269. return false;
  270. /* (2) comm - (%s) */
  271. location += 2;
  272. char* end = strrchr(location, ')');
  273. if (!end)
  274. return false;
  275. String_safeStrncpy(command, location, MINIMUM((size_t)(end - location + 1), commLen));
  276. location = end + 2;
  277. /* (3) state - %c */
  278. process->state = LinuxProcessTable_getProcessState(location[0]);
  279. location += 2;
  280. /* (4) ppid - %d */
  281. Process_setParent(process, fast_strtol_dec(&location, 0));
  282. location += 1;
  283. /* (5) pgrp - %d */
  284. process->pgrp = fast_strtol_dec(&location, 0);
  285. location += 1;
  286. /* (6) session - %d */
  287. process->session = fast_strtol_dec(&location, 0);
  288. location += 1;
  289. /* (7) tty_nr - %d */
  290. process->tty_nr = fast_strtoul_dec(&location, 0);
  291. location += 1;
  292. /* (8) tpgid - %d */
  293. process->tpgid = fast_strtol_dec(&location, 0);
  294. location += 1;
  295. /* (9) flags - %u */
  296. lp->flags = fast_strtoul_dec(&location, 0);
  297. location += 1;
  298. /* (10) minflt - %lu */
  299. process->minflt = fast_strtoull_dec(&location, 0);
  300. location += 1;
  301. /* (11) cminflt - %lu */
  302. lp->cminflt = fast_strtoull_dec(&location, 0);
  303. location += 1;
  304. /* (12) majflt - %lu */
  305. process->majflt = fast_strtoull_dec(&location, 0);
  306. location += 1;
  307. /* (13) cmajflt - %lu */
  308. lp->cmajflt = fast_strtoull_dec(&location, 0);
  309. location += 1;
  310. /* (14) utime - %lu */
  311. lp->utime = LinuxProcessTable_adjustTime(lhost, fast_strtoull_dec(&location, 0));
  312. location += 1;
  313. /* (15) stime - %lu */
  314. lp->stime = LinuxProcessTable_adjustTime(lhost, fast_strtoull_dec(&location, 0));
  315. location += 1;
  316. /* (16) cutime - %ld */
  317. lp->cutime = LinuxProcessTable_adjustTime(lhost, fast_strtoull_dec(&location, 0));
  318. location += 1;
  319. /* (17) cstime - %ld */
  320. lp->cstime = LinuxProcessTable_adjustTime(lhost, fast_strtoull_dec(&location, 0));
  321. location += 1;
  322. /* (18) priority - %ld */
  323. process->priority = fast_strtol_dec(&location, 0);
  324. location += 1;
  325. /* (19) nice - %ld */
  326. process->nice = fast_strtol_dec(&location, 0);
  327. location += 1;
  328. /* (20) num_threads - %ld */
  329. process->nlwp = fast_strtol_dec(&location, 0);
  330. location += 1;
  331. /* Skip (21) itrealvalue - %ld */
  332. location = strchr(location, ' ') + 1;
  333. /* (22) starttime - %llu */
  334. if (process->starttime_ctime == 0) {
  335. process->starttime_ctime = lhost->boottime + LinuxProcessTable_adjustTime(lhost, fast_strtoll_dec(&location, 0)) / 100;
  336. } else {
  337. location = strchr(location, ' ');
  338. }
  339. location += 1;
  340. /* Skip (23) - (38) */
  341. for (int i = 0; i < 16; i++) {
  342. location = strchr(location, ' ') + 1;
  343. }
  344. assert(location != NULL);
  345. /* (39) processor - %d */
  346. process->processor = fast_strtol_dec(&location, 0);
  347. /* Ignore further fields */
  348. process->time = lp->utime + lp->stime;
  349. return true;
  350. }
  351. /*
  352. * Read /proc/<pid>/status (thread-specific data)
  353. */
  354. static bool LinuxProcessTable_readStatusFile(Process* process, openat_arg_t procFd) {
  355. LinuxProcess* lp = (LinuxProcess*) process;
  356. unsigned long ctxt = 0;
  357. process->isRunningInContainer = TRI_OFF;
  358. #ifdef HAVE_VSERVER
  359. lp->vxid = 0;
  360. #endif
  361. FILE* statusfile = fopenat(procFd, "status", "r");
  362. if (!statusfile)
  363. return false;
  364. char buffer[PROC_LINE_LENGTH + 1] = {0};
  365. while (fgets(buffer, sizeof(buffer), statusfile)) {
  366. if (String_startsWith(buffer, "NSpid:")) {
  367. const char* ptr = buffer;
  368. int pid_ns_count = 0;
  369. while (*ptr && *ptr != '\n' && !isdigit((unsigned char)*ptr))
  370. ++ptr;
  371. while (*ptr && *ptr != '\n') {
  372. if (isdigit(*ptr))
  373. pid_ns_count++;
  374. while (isdigit((unsigned char)*ptr))
  375. ++ptr;
  376. while (*ptr && *ptr != '\n' && !isdigit((unsigned char)*ptr))
  377. ++ptr;
  378. }
  379. if (pid_ns_count > 1)
  380. process->isRunningInContainer = TRI_ON;
  381. } else if (String_startsWith(buffer, "voluntary_ctxt_switches:")) {
  382. unsigned long vctxt;
  383. int ok = sscanf(buffer, "voluntary_ctxt_switches:\t%lu", &vctxt);
  384. if (ok == 1) {
  385. ctxt += vctxt;
  386. }
  387. } else if (String_startsWith(buffer, "nonvoluntary_ctxt_switches:")) {
  388. unsigned long nvctxt;
  389. int ok = sscanf(buffer, "nonvoluntary_ctxt_switches:\t%lu", &nvctxt);
  390. if (ok == 1) {
  391. ctxt += nvctxt;
  392. }
  393. #ifdef HAVE_VSERVER
  394. } else if (String_startsWith(buffer, "VxID:")) {
  395. int vxid;
  396. int ok = sscanf(buffer, "VxID:\t%32d", &vxid);
  397. if (ok == 1) {
  398. lp->vxid = vxid;
  399. }
  400. #ifdef HAVE_ANCIENT_VSERVER
  401. } else if (String_startsWith(buffer, "s_context:")) {
  402. int vxid;
  403. int ok = sscanf(buffer, "s_context:\t%32d", &vxid);
  404. if (ok == 1) {
  405. lp->vxid = vxid;
  406. }
  407. #endif /* HAVE_ANCIENT_VSERVER */
  408. #endif /* HAVE_VSERVER */
  409. }
  410. }
  411. fclose(statusfile);
  412. lp->ctxt_diff = (ctxt > lp->ctxt_total) ? (ctxt - lp->ctxt_total) : 0;
  413. lp->ctxt_total = ctxt;
  414. return true;
  415. }
  416. /*
  417. * Gather user of task (process-shared data)
  418. */
  419. static bool LinuxProcessTable_updateUser(const Machine* host, Process* process, openat_arg_t procFd, const LinuxProcess* mainTask) {
  420. if (mainTask) {
  421. process->st_uid = mainTask->super.st_uid;
  422. process->user = mainTask->super.user;
  423. return true;
  424. }
  425. struct stat sb;
  426. #ifdef HAVE_OPENAT
  427. int statok = fstat(procFd, &sb);
  428. #else
  429. int statok = stat(procFd, &sb);
  430. #endif
  431. if (statok == -1)
  432. return false;
  433. if (process->st_uid != sb.st_uid) {
  434. process->st_uid = sb.st_uid;
  435. process->user = UsersTable_getRef(host->usersTable, sb.st_uid);
  436. }
  437. return true;
  438. }
  439. /*
  440. * Read /proc/<pid>/io (thread-specific data)
  441. */
  442. static void LinuxProcessTable_readIoFile(LinuxProcess* lp, openat_arg_t procFd, bool scanMainThread) {
  443. Process* process = &lp->super;
  444. const Machine* host = process->super.host;
  445. char path[20] = "io";
  446. char buffer[1024];
  447. if (scanMainThread) {
  448. xSnprintf(path, sizeof(path), "task/%"PRIi32"/io", (int32_t)Process_getPid(process));
  449. }
  450. ssize_t r = xReadfileat(procFd, path, buffer, sizeof(buffer));
  451. if (r < 0) {
  452. lp->io_rate_read_bps = NAN;
  453. lp->io_rate_write_bps = NAN;
  454. lp->io_rchar = ULLONG_MAX;
  455. lp->io_wchar = ULLONG_MAX;
  456. lp->io_syscr = ULLONG_MAX;
  457. lp->io_syscw = ULLONG_MAX;
  458. lp->io_read_bytes = ULLONG_MAX;
  459. lp->io_write_bytes = ULLONG_MAX;
  460. lp->io_cancelled_write_bytes = ULLONG_MAX;
  461. lp->io_last_scan_time_ms = host->realtimeMs;
  462. return;
  463. }
  464. unsigned long long last_read = lp->io_read_bytes;
  465. unsigned long long last_write = lp->io_write_bytes;
  466. unsigned long long time_delta = saturatingSub(host->realtimeMs, lp->io_last_scan_time_ms);
  467. // Note: Linux Kernel documentation states that /proc/<pid>/io may be racy
  468. // on 32-bit machines. (Documentation/filesystems/proc.rst)
  469. char* buf = buffer;
  470. const char* line;
  471. while ((line = strsep(&buf, "\n")) != NULL) {
  472. switch (line[0]) {
  473. case 'r':
  474. if (line[1] == 'c' && String_startsWith(line + 2, "har: ")) {
  475. lp->io_rchar = strtoull(line + 7, NULL, 10);
  476. } else if (String_startsWith(line + 1, "ead_bytes: ")) {
  477. lp->io_read_bytes = strtoull(line + 12, NULL, 10);
  478. lp->io_rate_read_bps = time_delta ? saturatingSub(lp->io_read_bytes, last_read) * /*ms to s*/1000. / time_delta : NAN;
  479. }
  480. break;
  481. case 'w':
  482. if (line[1] == 'c' && String_startsWith(line + 2, "har: ")) {
  483. lp->io_wchar = strtoull(line + 7, NULL, 10);
  484. } else if (String_startsWith(line + 1, "rite_bytes: ")) {
  485. lp->io_write_bytes = strtoull(line + 13, NULL, 10);
  486. lp->io_rate_write_bps = time_delta ? saturatingSub(lp->io_write_bytes, last_write) * /*ms to s*/1000. / time_delta : NAN;
  487. }
  488. break;
  489. case 's':
  490. if (line[4] == 'r' && String_startsWith(line + 1, "yscr: ")) {
  491. lp->io_syscr = strtoull(line + 7, NULL, 10);
  492. } else if (String_startsWith(line + 1, "yscw: ")) {
  493. lp->io_syscw = strtoull(line + 7, NULL, 10);
  494. }
  495. break;
  496. case 'c':
  497. if (String_startsWith(line + 1, "ancelled_write_bytes: ")) {
  498. lp->io_cancelled_write_bytes = strtoull(line + 23, NULL, 10);
  499. }
  500. }
  501. }
  502. lp->io_last_scan_time_ms = host->realtimeMs;
  503. }
  504. typedef struct LibraryData_ {
  505. uint64_t size;
  506. bool exec;
  507. } LibraryData;
  508. static void LinuxProcessTable_calcLibSize_helper(ATTR_UNUSED ht_key_t key, void* value, void* data) {
  509. if (!data)
  510. return;
  511. if (!value)
  512. return;
  513. const LibraryData* v = (const LibraryData*)value;
  514. uint64_t* d = (uint64_t*)data;
  515. if (!v->exec)
  516. return;
  517. *d += v->size;
  518. }
  519. /*
  520. * Read /proc/<pid>/maps (process-shared data)
  521. */
  522. static void LinuxProcessTable_readMaps(LinuxProcess* process, openat_arg_t procFd, const LinuxMachine* host, bool calcSize, bool checkDeletedLib) {
  523. Process* proc = (Process*)process;
  524. proc->usesDeletedLib = false;
  525. FILE* mapsfile = fopenat(procFd, "maps", "r");
  526. if (!mapsfile)
  527. return;
  528. Hashtable* ht = NULL;
  529. if (calcSize)
  530. ht = Hashtable_new(64, true);
  531. char buffer[1024];
  532. while (fgets(buffer, sizeof(buffer), mapsfile)) {
  533. uint64_t map_start;
  534. uint64_t map_end;
  535. bool map_execute;
  536. unsigned int map_devmaj;
  537. unsigned int map_devmin;
  538. uint64_t map_inode;
  539. // Short circuit test: Look for a slash
  540. if (!strchr(buffer, '/'))
  541. continue;
  542. // Parse format: "%Lx-%Lx %4s %x %2x:%2x %Ld"
  543. char* readptr = buffer;
  544. map_start = fast_strtoull_hex(&readptr, 16);
  545. if ('-' != *readptr++)
  546. continue;
  547. map_end = fast_strtoull_hex(&readptr, 16);
  548. if (' ' != *readptr++)
  549. continue;
  550. if (!readptr[0] || !readptr[1] || !readptr[2] || !readptr[3])
  551. continue;
  552. map_execute = (readptr[2] == 'x');
  553. readptr += 4;
  554. if (' ' != *readptr++)
  555. continue;
  556. while (*readptr > ' ')
  557. readptr++; // Skip parsing this hex value
  558. if (' ' != *readptr++)
  559. continue;
  560. map_devmaj = fast_strtoull_hex(&readptr, 4);
  561. if (':' != *readptr++)
  562. continue;
  563. map_devmin = fast_strtoull_hex(&readptr, 4);
  564. if (' ' != *readptr++)
  565. continue;
  566. //Minor shortcut: Once we know there's no file for this region, we skip
  567. if (!map_devmaj && !map_devmin)
  568. continue;
  569. map_inode = fast_strtoull_dec(&readptr, 0);
  570. if (!map_inode)
  571. continue;
  572. if (calcSize) {
  573. LibraryData* libdata = Hashtable_get(ht, map_inode);
  574. if (!libdata) {
  575. libdata = xCalloc(1, sizeof(LibraryData));
  576. Hashtable_put(ht, map_inode, libdata);
  577. }
  578. libdata->size += map_end - map_start;
  579. libdata->exec |= map_execute;
  580. }
  581. if (checkDeletedLib && map_execute && !proc->usesDeletedLib) {
  582. while (*readptr == ' ')
  583. readptr++;
  584. if (*readptr != '/')
  585. continue;
  586. if (String_startsWith(readptr, "/memfd:"))
  587. continue;
  588. /* Virtualbox maps /dev/zero for memory allocation. That results in
  589. * false positive, so ignore. */
  590. if (String_eq(readptr, "/dev/zero (deleted)\n"))
  591. continue;
  592. if (strstr(readptr, " (deleted)\n")) {
  593. proc->usesDeletedLib = true;
  594. if (!calcSize)
  595. break;
  596. }
  597. }
  598. }
  599. fclose(mapsfile);
  600. if (calcSize) {
  601. uint64_t total_size = 0;
  602. Hashtable_foreach(ht, LinuxProcessTable_calcLibSize_helper, &total_size);
  603. Hashtable_delete(ht);
  604. process->m_lrs = total_size / host->pageSize;
  605. }
  606. }
  607. /*
  608. * Read /proc/<pid>/statm (process-shared data)
  609. */
  610. static bool LinuxProcessTable_readStatmFile(LinuxProcess* process, openat_arg_t procFd, const LinuxMachine* host, const LinuxProcess* mainTask) {
  611. if (mainTask) {
  612. process->super.m_virt = mainTask->super.m_virt;
  613. process->super.m_resident = mainTask->super.m_resident;
  614. return true;
  615. }
  616. char statmdata[128] = {0};
  617. if (xReadfileat(procFd, "statm", statmdata, sizeof(statmdata)) < 1) {
  618. return false;
  619. }
  620. long int dummy, dummy2;
  621. int r = sscanf(statmdata, "%ld %ld %ld %ld %ld %ld %ld",
  622. &process->super.m_virt,
  623. &process->super.m_resident,
  624. &process->m_share,
  625. &process->m_trs,
  626. &dummy, /* unused since Linux 2.6; always 0 */
  627. &process->m_drs,
  628. &dummy2); /* unused since Linux 2.6; always 0 */
  629. if (r == 7) {
  630. process->super.m_virt *= host->pageSizeKB;
  631. process->super.m_resident *= host->pageSizeKB;
  632. process->m_priv = process->super.m_resident - (process->m_share * host->pageSizeKB);
  633. }
  634. return r == 7;
  635. }
  636. /*
  637. * Read /proc/<pid>/smaps (process-shared data)
  638. */
  639. static bool LinuxProcessTable_readSmapsFile(LinuxProcess* process, openat_arg_t procFd, bool haveSmapsRollup) {
  640. //http://elixir.free-electrons.com/linux/v4.10/source/fs/proc/task_mmu.c#L719
  641. //kernel will return data in chunks of size PAGE_SIZE or less.
  642. FILE* fp = fopenat(procFd, haveSmapsRollup ? "smaps_rollup" : "smaps", "r");
  643. if (!fp)
  644. return false;
  645. process->m_pss = 0;
  646. process->m_swap = 0;
  647. process->m_psswp = 0;
  648. char buffer[256];
  649. while (fgets(buffer, sizeof(buffer), fp)) {
  650. if (!strchr(buffer, '\n')) {
  651. // Partial line, skip to end of this line
  652. if (!skipEndOfLine(fp)) {
  653. fclose(fp);
  654. return false;
  655. }
  656. }
  657. if (String_startsWith(buffer, "Pss:")) {
  658. process->m_pss += strtol(buffer + 4, NULL, 10);
  659. } else if (String_startsWith(buffer, "Swap:")) {
  660. process->m_swap += strtol(buffer + 5, NULL, 10);
  661. } else if (String_startsWith(buffer, "SwapPss:")) {
  662. process->m_psswp += strtol(buffer + 8, NULL, 10);
  663. }
  664. }
  665. fclose(fp);
  666. return true;
  667. }
  668. #ifdef HAVE_OPENVZ
  669. static void LinuxProcessTable_readOpenVZData(LinuxProcess* process, openat_arg_t procFd) {
  670. if (access(PROCDIR "/vz", R_OK) != 0) {
  671. free(process->ctid);
  672. process->ctid = NULL;
  673. process->vpid = Process_getPid(&process->super);
  674. return;
  675. }
  676. FILE* file = fopenat(procFd, "status", "r");
  677. if (!file) {
  678. free(process->ctid);
  679. process->ctid = NULL;
  680. process->vpid = Process_getPid(&process->super);
  681. return;
  682. }
  683. bool foundEnvID = false;
  684. bool foundVPid = false;
  685. char linebuf[256];
  686. while (fgets(linebuf, sizeof(linebuf), file) != NULL) {
  687. if (strchr(linebuf, '\n') == NULL) {
  688. // Partial line, skip to end of this line
  689. if (!skipEndOfLine(file)) {
  690. break;
  691. }
  692. }
  693. char* name_value_sep = strchr(linebuf, ':');
  694. if (name_value_sep == NULL) {
  695. continue;
  696. }
  697. int field;
  698. if (0 == strncasecmp(linebuf, "envID", name_value_sep - linebuf)) {
  699. field = 1;
  700. } else if (0 == strncasecmp(linebuf, "VPid", name_value_sep - linebuf)) {
  701. field = 2;
  702. } else {
  703. continue;
  704. }
  705. do {
  706. name_value_sep++;
  707. } while (*name_value_sep != '\0' && *name_value_sep <= 32);
  708. char* value_end = name_value_sep;
  709. while (*value_end > 32) {
  710. value_end++;
  711. }
  712. if (name_value_sep == value_end) {
  713. continue;
  714. }
  715. *value_end = '\0';
  716. switch (field) {
  717. case 1:
  718. foundEnvID = true;
  719. if (!String_eq(name_value_sep, process->ctid ? process->ctid : ""))
  720. free_and_xStrdup(&process->ctid, name_value_sep);
  721. break;
  722. case 2:
  723. foundVPid = true;
  724. process->vpid = strtoul(name_value_sep, NULL, 0);
  725. break;
  726. default:
  727. //Sanity Check: Should never reach here, or the implementation is missing something!
  728. assert(false && "OpenVZ handling: Unimplemented case for field handling reached.");
  729. }
  730. }
  731. fclose(file);
  732. if (!foundEnvID) {
  733. free(process->ctid);
  734. process->ctid = NULL;
  735. }
  736. if (!foundVPid) {
  737. process->vpid = Process_getPid(&process->super);
  738. }
  739. }
  740. #endif /* HAVE_OPENVZ */
  741. /*
  742. * Read /proc/<pid>/cgroup (thread-specific data)
  743. */
  744. static void LinuxProcessTable_readCGroupFile(LinuxProcess* process, openat_arg_t procFd) {
  745. FILE* file = fopenat(procFd, "cgroup", "r");
  746. if (!file) {
  747. if (process->cgroup) {
  748. free(process->cgroup);
  749. process->cgroup = NULL;
  750. }
  751. if (process->cgroup_short) {
  752. free(process->cgroup_short);
  753. process->cgroup_short = NULL;
  754. }
  755. if (process->container_short) {
  756. free(process->container_short);
  757. process->container_short = NULL;
  758. }
  759. return;
  760. }
  761. char output[PROC_LINE_LENGTH + 1];
  762. output[0] = '\0';
  763. char* at = output;
  764. int left = PROC_LINE_LENGTH;
  765. while (!feof(file) && left > 0) {
  766. char buffer[PROC_LINE_LENGTH + 1];
  767. const char* ok = fgets(buffer, PROC_LINE_LENGTH, file);
  768. if (!ok)
  769. break;
  770. char* group = buffer;
  771. for (size_t i = 0; i < 2; i++) {
  772. group = String_strchrnul(group, ':');
  773. if (!*group)
  774. break;
  775. group++;
  776. }
  777. char* eol = String_strchrnul(group, '\n');
  778. *eol = '\0';
  779. if (at != output) {
  780. *at = ';';
  781. at++;
  782. left--;
  783. }
  784. int wrote = snprintf(at, left, "%s", group);
  785. left -= wrote;
  786. }
  787. fclose(file);
  788. bool changed = !process->cgroup || !String_eq(process->cgroup, output);
  789. Row_updateFieldWidth(CGROUP, strlen(output));
  790. free_and_xStrdup(&process->cgroup, output);
  791. if (!changed) {
  792. if (process->cgroup_short) {
  793. Row_updateFieldWidth(CCGROUP, strlen(process->cgroup_short));
  794. } else {
  795. //CCGROUP is alias to normal CGROUP if shortening fails
  796. Row_updateFieldWidth(CCGROUP, strlen(process->cgroup));
  797. }
  798. if (process->container_short) {
  799. Row_updateFieldWidth(CONTAINER, strlen(process->container_short));
  800. } else {
  801. Row_updateFieldWidth(CONTAINER, strlen("N/A"));
  802. }
  803. return;
  804. }
  805. char* cgroup_short = CGroup_filterName(process->cgroup);
  806. if (cgroup_short) {
  807. Row_updateFieldWidth(CCGROUP, strlen(cgroup_short));
  808. free_and_xStrdup(&process->cgroup_short, cgroup_short);
  809. free(cgroup_short);
  810. } else {
  811. //CCGROUP is alias to normal CGROUP if shortening fails
  812. Row_updateFieldWidth(CCGROUP, strlen(process->cgroup));
  813. free(process->cgroup_short);
  814. process->cgroup_short = NULL;
  815. }
  816. char* container_short = CGroup_filterContainer(process->cgroup);
  817. if (container_short) {
  818. Row_updateFieldWidth(CONTAINER, strlen(container_short));
  819. free_and_xStrdup(&process->container_short, container_short);
  820. free(container_short);
  821. } else {
  822. //CONTAINER is just "N/A" if shortening fails
  823. Row_updateFieldWidth(CONTAINER, strlen("N/A"));
  824. free(process->container_short);
  825. process->container_short = NULL;
  826. }
  827. }
  828. /*
  829. * Read /proc/<pid>/oom_score (process-shared data)
  830. */
  831. static void LinuxProcessTable_readOomData(LinuxProcess* process, openat_arg_t procFd, const LinuxProcess* mainTask) {
  832. if (mainTask) {
  833. process->oom = mainTask->oom;
  834. return;
  835. }
  836. char buffer[PROC_LINE_LENGTH + 1] = {0};
  837. ssize_t oomRead = xReadfileat(procFd, "oom_score", buffer, sizeof(buffer));
  838. if (oomRead < 1) {
  839. return;
  840. }
  841. char* oomPtr = buffer;
  842. uint64_t oom = fast_strtoull_dec(&oomPtr, oomRead);
  843. if (*oomPtr && *oomPtr != '\n' && *oomPtr != ' ') {
  844. return;
  845. }
  846. if (oom > UINT_MAX) {
  847. return;
  848. }
  849. process->oom = oom;
  850. }
  851. /*
  852. * Read /proc/<pid>/autogroup (process-shared data)
  853. */
  854. static void LinuxProcessTable_readAutogroup(LinuxProcess* process, openat_arg_t procFd, const LinuxProcess* mainTask) {
  855. if (mainTask) {
  856. process->autogroup_id = mainTask->autogroup_id;
  857. return;
  858. }
  859. process->autogroup_id = -1;
  860. char autogroup[64]; // space for two numeric values and fixed length strings
  861. ssize_t amtRead = xReadfileat(procFd, "autogroup", autogroup, sizeof(autogroup));
  862. if (amtRead < 0)
  863. return;
  864. long int identity;
  865. int nice;
  866. int ok = sscanf(autogroup, "/autogroup-%ld nice %d", &identity, &nice);
  867. if (ok == 2) {
  868. process->autogroup_id = identity;
  869. process->autogroup_nice = nice;
  870. }
  871. }
  872. /*
  873. * Read /proc/<pid>/attr/current (process-shared data)
  874. */
  875. static void LinuxProcessTable_readSecattrData(LinuxProcess* process, openat_arg_t procFd, const LinuxProcess* mainTask) {
  876. if (mainTask) {
  877. const char* mainSecAttr = mainTask->secattr;
  878. if (mainSecAttr) {
  879. free_and_xStrdup(&process->secattr, mainSecAttr);
  880. } else {
  881. free(process->secattr);
  882. process->secattr = NULL;
  883. }
  884. return;
  885. }
  886. char buffer[PROC_LINE_LENGTH + 1] = {0};
  887. ssize_t attrdata = xReadfileat(procFd, "attr/current", buffer, sizeof(buffer));
  888. if (attrdata < 1) {
  889. free(process->secattr);
  890. process->secattr = NULL;
  891. return;
  892. }
  893. char* newline = strchr(buffer, '\n');
  894. if (newline) {
  895. *newline = '\0';
  896. }
  897. Row_updateFieldWidth(SECATTR, strlen(buffer));
  898. free_and_xStrdup(&process->secattr, buffer);
  899. }
  900. /*
  901. * Read /proc/<pid>/cwd (process-shared data)
  902. */
  903. static void LinuxProcessTable_readCwd(LinuxProcess* process, openat_arg_t procFd, const LinuxProcess* mainTask) {
  904. if (mainTask) {
  905. const char* mainCwd = mainTask->super.procCwd;
  906. if (mainCwd) {
  907. free_and_xStrdup(&process->super.procCwd, mainCwd);
  908. } else {
  909. free(process->super.procCwd);
  910. process->super.procCwd = NULL;
  911. }
  912. return;
  913. }
  914. char pathBuffer[PATH_MAX + 1] = {0};
  915. #if defined(HAVE_READLINKAT) && defined(HAVE_OPENAT)
  916. ssize_t r = readlinkat(procFd, "cwd", pathBuffer, sizeof(pathBuffer) - 1);
  917. #else
  918. ssize_t r = Compat_readlink(procFd, "cwd", pathBuffer, sizeof(pathBuffer) - 1);
  919. #endif
  920. if (r < 0) {
  921. free(process->super.procCwd);
  922. process->super.procCwd = NULL;
  923. return;
  924. }
  925. pathBuffer[r] = '\0';
  926. free_and_xStrdup(&process->super.procCwd, pathBuffer);
  927. }
  928. /*
  929. * Read /proc/<pid>/exe (process-shared data)
  930. */
  931. static void LinuxProcessList_readExe(Process* process, openat_arg_t procFd, const LinuxProcess* mainTask) {
  932. if (mainTask) {
  933. Process_updateExe(process, mainTask->super.procExe);
  934. process->procExeDeleted = mainTask->super.procExeDeleted;
  935. return;
  936. }
  937. char filename[PATH_MAX + 1];
  938. #if defined(HAVE_READLINKAT) && defined(HAVE_OPENAT)
  939. ssize_t amtRead = readlinkat(procFd, "exe", filename, sizeof(filename) - 1);
  940. #else
  941. ssize_t amtRead = Compat_readlink(procFd, "exe", filename, sizeof(filename) - 1);
  942. #endif
  943. if (amtRead > 0) {
  944. filename[amtRead] = 0;
  945. if (!process->procExe ||
  946. (!process->procExeDeleted && !String_eq(filename, process->procExe)) ||
  947. process->procExeDeleted) {
  948. const char* deletedMarker = " (deleted)";
  949. const size_t markerLen = strlen(deletedMarker);
  950. const size_t filenameLen = strlen(filename);
  951. if (filenameLen > markerLen) {
  952. bool oldExeDeleted = process->procExeDeleted;
  953. process->procExeDeleted = String_eq(filename + filenameLen - markerLen, deletedMarker);
  954. if (process->procExeDeleted)
  955. filename[filenameLen - markerLen] = '\0';
  956. if (oldExeDeleted != process->procExeDeleted)
  957. process->mergedCommand.lastUpdate = 0;
  958. }
  959. Process_updateExe(process, filename);
  960. }
  961. } else if (process->procExe) {
  962. Process_updateExe(process, NULL);
  963. process->procExeDeleted = false;
  964. }
  965. }
  966. /*
  967. * Read /proc/<pid>/cmdline (process-shared data)
  968. */
  969. static bool LinuxProcessTable_readCmdlineFile(Process* process, openat_arg_t procFd, const LinuxProcess* mainTask) {
  970. LinuxProcessList_readExe(process, procFd, mainTask);
  971. char command[4096 + 1]; // max cmdline length on Linux
  972. ssize_t amtRead = xReadfileat(procFd, "cmdline", command, sizeof(command));
  973. if (amtRead <= 0)
  974. return false;
  975. int tokenEnd = -1;
  976. int tokenStart = -1;
  977. int lastChar = 0;
  978. bool argSepNUL = false;
  979. bool argSepSpace = false;
  980. for (int i = 0; i < amtRead; i++) {
  981. // If this is true, there's a NUL byte in the middle of command
  982. if (tokenEnd >= 0) {
  983. argSepNUL = true;
  984. }
  985. const char argChar = command[i];
  986. /* newline used as delimiter - when forming the mergedCommand, newline is
  987. * converted to space by Process_makeCommandStr */
  988. if (argChar == '\n') {
  989. /* Set to some other non-printable character */
  990. command[i] = '\r';
  991. continue;
  992. }
  993. if (argChar == '\0') {
  994. command[i] = '\n';
  995. // Set tokenEnd to the NUL byte
  996. if (tokenEnd < 0) {
  997. tokenEnd = i;
  998. }
  999. continue;
  1000. }
  1001. /* Record some information for the argument parsing heuristic below. */
  1002. if (argChar <= ' ') {
  1003. argSepSpace = true;
  1004. }
  1005. /* Detect the last / before the end of the token as
  1006. * the start of the basename in cmdline, see Process_writeCommand */
  1007. if (argChar == '/' && tokenEnd < 0) {
  1008. tokenStart = i + 1;
  1009. }
  1010. lastChar = i;
  1011. }
  1012. command[lastChar + 1] = '\0';
  1013. if (!argSepNUL && argSepSpace) {
  1014. /* Argument parsing heuristic.
  1015. *
  1016. * This heuristic is used for processes that rewrite their command line.
  1017. * Normally the command line is split by using NUL bytes between each argument.
  1018. * But some programs like chrome flatten this using spaces.
  1019. *
  1020. * This heuristic tries its best to undo this loss of information.
  1021. * To achieve this, we treat every character <= 32 as argument separators
  1022. * (i.e. all of ASCII control sequences and space).
  1023. * We then search for the basename of the cmdline in the first argument we found that way.
  1024. * As path names may contain we try to cross-validate if the path we got that way exists.
  1025. */
  1026. tokenStart = -1;
  1027. tokenEnd = -1;
  1028. size_t exeLen = process->procExe ? strlen(process->procExe) : 0;
  1029. if (process->procExe && String_startsWith(command, process->procExe) &&
  1030. exeLen < (size_t)lastChar && command[exeLen] <= ' ') {
  1031. tokenStart = process->procExeBasenameOffset;
  1032. tokenEnd = exeLen;
  1033. }
  1034. // From initial scan we know there's at least one space.
  1035. // Check if that's part of a filename for an existing file.
  1036. else if (Compat_faccessat(AT_FDCWD, command, F_OK, AT_SYMLINK_NOFOLLOW) != 0) {
  1037. // If we reach here the path does not exist.
  1038. // Thus begin searching for the part of it that actually does.
  1039. int tokenArg0Start = -1;
  1040. for (int i = 0; i <= lastChar; i++) {
  1041. const char cmdChar = command[i];
  1042. /* Any ASCII control or space used as delimiter */
  1043. if (cmdChar <= ' ') {
  1044. if (tokenEnd >= 0) {
  1045. // Split on every further separator, regardless of path correctness
  1046. command[i] = '\n';
  1047. continue;
  1048. }
  1049. // Found our first argument
  1050. command[i] = '\0';
  1051. bool found = Compat_faccessat(AT_FDCWD, command, F_OK, AT_SYMLINK_NOFOLLOW) == 0;
  1052. // Restore if this wasn't it
  1053. command[i] = found ? '\n' : cmdChar;
  1054. if (found)
  1055. tokenEnd = i;
  1056. if (tokenArg0Start < 0)
  1057. tokenArg0Start = tokenStart < 0 ? 0 : tokenStart;
  1058. continue;
  1059. }
  1060. if (tokenEnd >= 0) {
  1061. continue;
  1062. }
  1063. if (cmdChar == '/') {
  1064. // Normal path separator
  1065. tokenStart = i + 1;
  1066. } else if (cmdChar == '\\' && (tokenStart < 1 || command[tokenStart - 1] == '\\')) {
  1067. // Windows Path separator (WINE)
  1068. tokenStart = i + 1;
  1069. } else if (cmdChar == ':' && (command[i + 1] != '/' && command[i + 1] != '\\')) {
  1070. // Colon not part of a Windows Path
  1071. tokenEnd = i;
  1072. } else if (tokenStart < 0) {
  1073. // Relative path
  1074. tokenStart = i;
  1075. }
  1076. }
  1077. if (tokenEnd < 0) {
  1078. tokenStart = tokenArg0Start;
  1079. // No token delimiter found, forcibly split
  1080. for (int i = 0; i <= lastChar; i++) {
  1081. if (command[i] <= ' ') {
  1082. command[i] = '\n';
  1083. if (tokenEnd < 0) {
  1084. tokenEnd = i;
  1085. }
  1086. }
  1087. }
  1088. }
  1089. }
  1090. /* Some command lines are hard to parse, like
  1091. * file.so [kdeinit5] file local:/run/user/1000/klauncherdqbouY.1.slave-socket local:/run/user/1000/kded5TwsDAx.1.slave-socket
  1092. * Reset if start is behind end.
  1093. */
  1094. if (tokenStart >= tokenEnd) {
  1095. tokenStart = -1;
  1096. tokenEnd = -1;
  1097. }
  1098. }
  1099. if (tokenStart < 0) {
  1100. tokenStart = 0;
  1101. }
  1102. if (tokenEnd < 0) {
  1103. tokenEnd = lastChar + 1;
  1104. }
  1105. Process_updateCmdline(process, command, tokenStart, tokenEnd);
  1106. return true;
  1107. }
  1108. /*
  1109. * Read /proc/<pid>/comm (thread-specific data)
  1110. */
  1111. static void LinuxProcessList_readComm(Process* process, openat_arg_t procFd) {
  1112. char command[4096 + 1]; // max cmdline length on Linux
  1113. ssize_t amtRead = xReadfileat(procFd, "comm", command, sizeof(command));
  1114. if (amtRead > 0) {
  1115. command[amtRead - 1] = '\0';
  1116. Process_updateComm(process, command);
  1117. } else {
  1118. Process_updateComm(process, NULL);
  1119. }
  1120. }
  1121. static char* LinuxProcessTable_updateTtyDevice(TtyDriver* ttyDrivers, unsigned long int tty_nr) {
  1122. unsigned int maj = major(tty_nr);
  1123. unsigned int min = minor(tty_nr);
  1124. int i = -1;
  1125. for (;;) {
  1126. i++;
  1127. if ((!ttyDrivers[i].path) || maj < ttyDrivers[i].major) {
  1128. break;
  1129. }
  1130. if (maj > ttyDrivers[i].major) {
  1131. continue;
  1132. }
  1133. if (min < ttyDrivers[i].minorFrom) {
  1134. break;
  1135. }
  1136. if (min > ttyDrivers[i].minorTo) {
  1137. continue;
  1138. }
  1139. unsigned int idx = min - ttyDrivers[i].minorFrom;
  1140. struct stat sb;
  1141. char* fullPath;
  1142. for (;;) {
  1143. xAsprintf(&fullPath, "%s/%d", ttyDrivers[i].path, idx);
  1144. int err = stat(fullPath, &sb);
  1145. if (err == 0 && major(sb.st_rdev) == maj && minor(sb.st_rdev) == min) {
  1146. return fullPath;
  1147. }
  1148. free(fullPath);
  1149. xAsprintf(&fullPath, "%s%d", ttyDrivers[i].path, idx);
  1150. err = stat(fullPath, &sb);
  1151. if (err == 0 && major(sb.st_rdev) == maj && minor(sb.st_rdev) == min) {
  1152. return fullPath;
  1153. }
  1154. free(fullPath);
  1155. if (idx == min) {
  1156. break;
  1157. }
  1158. idx = min;
  1159. }
  1160. int err = stat(ttyDrivers[i].path, &sb);
  1161. if (err == 0 && tty_nr == sb.st_rdev) {
  1162. return xStrdup(ttyDrivers[i].path);
  1163. }
  1164. }
  1165. char* out;
  1166. xAsprintf(&out, "/dev/%u:%u", maj, min);
  1167. return out;
  1168. }
  1169. static bool isOlderThan(const Process* proc, unsigned int seconds) {
  1170. const Machine* host = proc->super.host;
  1171. assert(host->realtimeMs > 0);
  1172. /* Starttime might not yet be parsed */
  1173. if (proc->starttime_ctime <= 0)
  1174. return false;
  1175. uint64_t realtime = host->realtimeMs / 1000;
  1176. if (realtime < (uint64_t)proc->starttime_ctime)
  1177. return false;
  1178. return realtime - proc->starttime_ctime > seconds;
  1179. }
  1180. static bool LinuxProcessTable_recurseProcTree(LinuxProcessTable* this, openat_arg_t parentFd, const LinuxMachine* lhost, const char* dirname, const LinuxProcess* mainTask) {
  1181. ProcessTable* pt = (ProcessTable*) this;
  1182. const Machine* host = &lhost->super;
  1183. const Settings* settings = host->settings;
  1184. const ScreenSettings* ss = settings->ss;
  1185. const struct dirent* entry;
  1186. /* set runningTasks from /proc/stat (from Machine_scanCPUTime) */
  1187. pt->runningTasks = lhost->runningTasks;
  1188. #ifdef HAVE_OPENAT
  1189. int dirFd = openat(parentFd, dirname, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
  1190. if (dirFd < 0)
  1191. return false;
  1192. DIR* dir = fdopendir(dirFd);
  1193. #else
  1194. char dirFd[4096];
  1195. xSnprintf(dirFd, sizeof(dirFd), "%s/%s", parentFd, dirname);
  1196. DIR* dir = opendir(dirFd);
  1197. #endif
  1198. if (!dir) {
  1199. Compat_openatArgClose(dirFd);
  1200. return false;
  1201. }
  1202. const bool hideKernelThreads = settings->hideKernelThreads;
  1203. const bool hideUserlandThreads = settings->hideUserlandThreads;
  1204. const bool hideRunningInContainer = settings->hideRunningInContainer;
  1205. while ((entry = readdir(dir)) != NULL) {
  1206. const char* name = entry->d_name;
  1207. // Ignore all non-directories
  1208. if (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN) {
  1209. continue;
  1210. }
  1211. // The RedHat kernel hides threads with a dot.
  1212. // I believe this is non-standard.
  1213. if (name[0] == '.') {
  1214. name++;
  1215. }
  1216. // Just skip all non-number directories.
  1217. if (name[0] < '0' || name[0] > '9') {
  1218. continue;
  1219. }
  1220. // filename is a number: process directory
  1221. int pid;
  1222. {
  1223. char* endptr;
  1224. unsigned long parsedPid = strtoul(name, &endptr, 10);
  1225. if (parsedPid == 0 || parsedPid == ULONG_MAX || *endptr != '\0')
  1226. continue;
  1227. pid = parsedPid;
  1228. }
  1229. // Skip task directory of main thread
  1230. if (mainTask && pid == Process_getPid(&mainTask->super))
  1231. continue;
  1232. #ifdef HAVE_OPENAT
  1233. int procFd = openat(dirFd, entry->d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
  1234. if (procFd < 0)
  1235. continue;
  1236. #else
  1237. char procFd[4096];
  1238. xSnprintf(procFd, sizeof(procFd), "%s/%s", dirFd, entry->d_name);
  1239. #endif
  1240. bool preExisting;
  1241. Process* proc = ProcessTable_getProcess(pt, pid, &preExisting, LinuxProcess_new);
  1242. LinuxProcess* lp = (LinuxProcess*) proc;
  1243. Process_setThreadGroup(proc, mainTask ? Process_getPid(&mainTask->super) : pid);
  1244. proc->isUserlandThread = Process_getPid(proc) != Process_getThreadGroup(proc);
  1245. assert(proc->isUserlandThread == (mainTask != NULL));
  1246. LinuxProcessTable_recurseProcTree(this, procFd, lhost, "task", lp);
  1247. /*
  1248. * These conditions will not trigger on first occurrence, cause we need to
  1249. * add the process to the ProcessTable and do all one time scans
  1250. * (e.g. parsing the cmdline to detect a kernel thread)
  1251. * But it will short-circuit subsequent scans.
  1252. */
  1253. if (preExisting && hideKernelThreads && Process_isKernelThread(proc)) {
  1254. proc->super.updated = true;
  1255. proc->super.show = false;
  1256. pt->kernelThreads++;
  1257. pt->totalTasks++;
  1258. Compat_openatArgClose(procFd);
  1259. continue;
  1260. }
  1261. if (preExisting && hideUserlandThreads && Process_isUserlandThread(proc)) {
  1262. proc->super.updated = true;
  1263. proc->super.show = false;
  1264. pt->userlandThreads++;
  1265. pt->totalTasks++;
  1266. Compat_openatArgClose(procFd);
  1267. continue;
  1268. }
  1269. if (preExisting && hideRunningInContainer && proc->isRunningInContainer == TRI_ON) {
  1270. proc->super.updated = true;
  1271. proc->super.show = false;
  1272. Compat_openatArgClose(procFd);
  1273. continue;
  1274. }
  1275. const bool scanMainThread = !hideUserlandThreads && !Process_isKernelThread(proc) && !mainTask;
  1276. if (!LinuxProcessTable_readStatmFile(lp, procFd, lhost, mainTask))
  1277. goto errorReadingProcess;
  1278. {
  1279. bool prev = proc->usesDeletedLib;
  1280. if (!proc->isKernelThread && !proc->isUserlandThread &&
  1281. ((ss->flags & PROCESS_FLAG_LINUX_LRS_FIX) || (settings->highlightDeletedExe && !proc->procExeDeleted && isOlderThan(proc, 10)))) {
  1282. // Check if we really should recalculate the M_LRS value for this process
  1283. uint64_t passedTimeInMs = host->realtimeMs - lp->last_mlrs_calctime;
  1284. uint64_t recheck = ((uint64_t)rand()) % 2048;
  1285. if (passedTimeInMs > recheck) {
  1286. lp->last_mlrs_calctime = host->realtimeMs;
  1287. LinuxProcessTable_readMaps(lp, procFd, lhost, ss->flags & PROCESS_FLAG_LINUX_LRS_FIX, settings->highlightDeletedExe);
  1288. }
  1289. } else {
  1290. /* Copy from process structure in threads and reset if setting got disabled */
  1291. proc->usesDeletedLib = (proc->isUserlandThread && mainTask) ? mainTask->super.usesDeletedLib : false;
  1292. lp->m_lrs = (proc->isUserlandThread && mainTask) ? mainTask->m_lrs : 0;
  1293. }
  1294. if (prev != proc->usesDeletedLib)
  1295. proc->mergedCommand.lastUpdate = 0;
  1296. }
  1297. char statCommand[MAX_NAME + 1];
  1298. unsigned long long int lasttimes = (lp->utime + lp->stime);
  1299. unsigned long int last_tty_nr = proc->tty_nr;
  1300. if (!LinuxProcessTable_readStatFile(lp, procFd, lhost, scanMainThread, statCommand, sizeof(statCommand)))
  1301. goto errorReadingProcess;
  1302. if (lp->flags & PF_KTHREAD) {
  1303. proc->isKernelThread = true;
  1304. }
  1305. if (last_tty_nr != proc->tty_nr && this->ttyDrivers) {
  1306. free(proc->tty_name);
  1307. proc->tty_name = LinuxProcessTable_updateTtyDevice(this->ttyDrivers, proc->tty_nr);
  1308. }
  1309. proc->percent_cpu = NAN;
  1310. /* lhost->period might be 0 after system sleep */
  1311. if (lhost->period > 0.0) {
  1312. float percent_cpu = saturatingSub(lp->utime + lp->stime, lasttimes) / lhost->period * 100.0;
  1313. proc->percent_cpu = MINIMUM(percent_cpu, host->activeCPUs * 100.0F);
  1314. }
  1315. proc->percent_mem = proc->m_resident / (double)(host->totalMem) * 100.0;
  1316. Process_updateCPUFieldWidths(proc->percent_cpu);
  1317. if (!LinuxProcessTable_updateUser(host, proc, procFd, mainTask))
  1318. goto errorReadingProcess;
  1319. /* Check if the process is inside a different PID namespace. */
  1320. if (proc->isRunningInContainer == TRI_INITIAL && rootPidNs != (ino_t)-1) {
  1321. struct stat sb;
  1322. #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT)
  1323. int res = fstatat(procFd, "ns/pid", &sb, 0);
  1324. #else
  1325. char path[PATH_MAX];
  1326. xSnprintf(path, sizeof(path), "%s/ns/pid", procFd);
  1327. int res = stat(path, &sb);
  1328. #endif
  1329. if (res == 0) {
  1330. proc->isRunningInContainer = (sb.st_ino != rootPidNs) ? TRI_ON : TRI_OFF;
  1331. }
  1332. }
  1333. if (ss->flags & PROCESS_FLAG_LINUX_CTXT
  1334. || ((hideRunningInContainer || ss->flags & PROCESS_FLAG_LINUX_CONTAINER) && proc->isRunningInContainer == TRI_INITIAL)
  1335. #ifdef HAVE_VSERVER
  1336. || ss->flags & PROCESS_FLAG_LINUX_VSERVER
  1337. #endif
  1338. ) {
  1339. proc->isRunningInContainer = TRI_OFF;
  1340. if (!LinuxProcessTable_readStatusFile(proc, procFd))
  1341. goto errorReadingProcess;
  1342. }
  1343. if (!preExisting) {
  1344. #ifdef HAVE_OPENVZ
  1345. if (ss->flags & PROCESS_FLAG_LINUX_OPENVZ) {
  1346. LinuxProcessTable_readOpenVZData(lp, procFd);
  1347. }
  1348. #endif
  1349. if (proc->isKernelThread) {
  1350. Process_updateCmdline(proc, NULL, 0, 0);
  1351. } else {
  1352. if (!LinuxProcessTable_readCmdlineFile(proc, procFd, mainTask)) {
  1353. Process_updateCmdline(proc, statCommand, 0, strlen(statCommand));
  1354. }
  1355. LinuxProcessList_readComm(proc, procFd);
  1356. }
  1357. Process_fillStarttimeBuffer(proc);
  1358. ProcessTable_add(pt, proc);
  1359. } else {
  1360. if (settings->updateProcessNames && proc->state != ZOMBIE) {
  1361. if (proc->isKernelThread) {
  1362. Process_updateCmdline(proc, NULL, 0, 0);
  1363. } else {
  1364. if (!LinuxProcessTable_readCmdlineFile(proc, procFd, mainTask)) {
  1365. Process_updateCmdline(proc, statCommand, 0, strlen(statCommand));
  1366. }
  1367. LinuxProcessList_readComm(proc, procFd);
  1368. }
  1369. }
  1370. }
  1371. /*
  1372. * Section gathering non-critical information that is independent from
  1373. * each other.
  1374. */
  1375. /* Gather permitted capabilities (thread-specific data) for non-root process. */
  1376. if (proc->st_uid != 0 && proc->elevated_priv != TRI_OFF) {
  1377. struct __user_cap_header_struct header = { .version = _LINUX_CAPABILITY_VERSION_3, .pid = Process_getPid(proc) };
  1378. struct __user_cap_data_struct data;
  1379. long res = syscall(SYS_capget, &header, &data);
  1380. if (res == 0) {
  1381. proc->elevated_priv = (data.permitted != 0) ? TRI_ON : TRI_OFF;
  1382. } else {
  1383. proc->elevated_priv = TRI_OFF;
  1384. }
  1385. }
  1386. if (ss->flags & PROCESS_FLAG_LINUX_CGROUP)
  1387. LinuxProcessTable_readCGroupFile(lp, procFd);
  1388. if ((ss->flags & PROCESS_FLAG_LINUX_SMAPS) && !Process_isKernelThread(proc)) {
  1389. if (!mainTask) {
  1390. // Read smaps file of each process only every second pass to improve performance
  1391. static int smaps_flag = 0;
  1392. if ((pid & 1) == smaps_flag) {
  1393. LinuxProcessTable_readSmapsFile(lp, procFd, this->haveSmapsRollup);
  1394. }
  1395. if (pid == 1) {
  1396. smaps_flag = !smaps_flag;
  1397. }
  1398. } else {
  1399. lp->m_pss = mainTask->m_pss;
  1400. lp->m_swap = mainTask->m_swap;
  1401. lp->m_psswp = mainTask->m_psswp;
  1402. }
  1403. }
  1404. if (ss->flags & PROCESS_FLAG_IO) {
  1405. LinuxProcessTable_readIoFile(lp, procFd, scanMainThread);
  1406. }
  1407. #ifdef HAVE_DELAYACCT
  1408. if (ss->flags & PROCESS_FLAG_LINUX_DELAYACCT) {
  1409. LibNl_readDelayAcctData(this, lp);
  1410. }
  1411. #endif
  1412. if (ss->flags & PROCESS_FLAG_LINUX_OOM) {
  1413. LinuxProcessTable_readOomData(lp, procFd, mainTask);
  1414. }
  1415. if (ss->flags & PROCESS_FLAG_LINUX_IOPRIO) {
  1416. LinuxProcess_updateIOPriority(proc);
  1417. }
  1418. if (ss->flags & PROCESS_FLAG_LINUX_SECATTR) {
  1419. LinuxProcessTable_readSecattrData(lp, procFd, mainTask);
  1420. }
  1421. if (ss->flags & PROCESS_FLAG_CWD) {
  1422. LinuxProcessTable_readCwd(lp, procFd, mainTask);
  1423. }
  1424. if ((ss->flags & PROCESS_FLAG_LINUX_AUTOGROUP) && this->haveAutogroup) {
  1425. LinuxProcessTable_readAutogroup(lp, procFd, mainTask);
  1426. }
  1427. #ifdef SCHEDULER_SUPPORT
  1428. if (ss->flags & PROCESS_FLAG_SCHEDPOL) {
  1429. Scheduling_readProcessPolicy(proc);
  1430. }
  1431. #endif
  1432. if (ss->flags & PROCESS_FLAG_LINUX_GPU || GPUMeter_active()) {
  1433. if (mainTask) {
  1434. lp->gpu_time = mainTask->gpu_time;
  1435. } else {
  1436. GPU_readProcessData(this, lp, procFd);
  1437. }
  1438. }
  1439. /*
  1440. * Final section after all data has been gathered
  1441. */
  1442. if (!proc->cmdline && statCommand[0] &&
  1443. (proc->state == ZOMBIE || Process_isKernelThread(proc) || settings->showThreadNames)) {
  1444. Process_updateCmdline(proc, statCommand, 0, strlen(statCommand));
  1445. }
  1446. proc->super.updated = true;
  1447. Compat_openatArgClose(procFd);
  1448. if (hideRunningInContainer && proc->isRunningInContainer == TRI_ON) {
  1449. proc->super.show = false;
  1450. continue;
  1451. }
  1452. if (Process_isKernelThread(proc)) {
  1453. pt->kernelThreads++;
  1454. } else if (Process_isUserlandThread(proc)) {
  1455. pt->userlandThreads++;
  1456. }
  1457. /* Set at the end when we know if a new entry is a thread */
  1458. proc->super.show = ! ((hideKernelThreads && Process_isKernelThread(proc)) || (hideUserlandThreads && Process_isUserlandThread(proc)));
  1459. pt->totalTasks++;
  1460. /* runningTasks is set in Machine_scanCPUTime() from /proc/stat */
  1461. continue;
  1462. // Exception handler.
  1463. errorReadingProcess:
  1464. {
  1465. #ifdef HAVE_OPENAT
  1466. if (procFd >= 0)
  1467. close(procFd);
  1468. #endif
  1469. if (preExisting) {
  1470. /*
  1471. * The only real reason for coming here (apart from Linux violating the /proc API)
  1472. * would be the process going away with its /proc files disappearing (!HAVE_OPENAT).
  1473. * However, we want to keep in the process list for now for the "highlight dying" mode.
  1474. */
  1475. } else {
  1476. /* A really short-lived process that we don't have full info about */
  1477. assert(ProcessTable_findProcess(pt, Process_getPid(proc)) == NULL);
  1478. Process_delete((Object*)proc);
  1479. }
  1480. }
  1481. }
  1482. closedir(dir);
  1483. return true;
  1484. }
  1485. void ProcessTable_goThroughEntries(ProcessTable* super) {
  1486. LinuxProcessTable* this = (LinuxProcessTable*) super;
  1487. Machine* host = super->super.host;
  1488. const Settings* settings = host->settings;
  1489. LinuxMachine* lhost = (LinuxMachine*) host;
  1490. if (settings->ss->flags & PROCESS_FLAG_LINUX_AUTOGROUP) {
  1491. // Refer to sched(7) 'autogroup feature' section
  1492. // The kernel feature can be enabled/disabled through procfs at
  1493. // any time, so check for it at the start of each sample - only
  1494. // read from per-process procfs files if it's globally enabled.
  1495. this->haveAutogroup = LinuxProcess_isAutogroupEnabled();
  1496. } else {
  1497. this->haveAutogroup = false;
  1498. }
  1499. /* Shift GPU values */
  1500. {
  1501. lhost->prevGpuTime = lhost->curGpuTime;
  1502. lhost->curGpuTime = 0;
  1503. for (GPUEngineData* engine = lhost->gpuEngineData; engine; engine = engine->next) {
  1504. engine->prevTime = engine->curTime;
  1505. engine->curTime = 0;
  1506. }
  1507. }
  1508. /* PROCDIR is an absolute path */
  1509. assert(PROCDIR[0] == '/');
  1510. #ifdef HAVE_OPENAT
  1511. openat_arg_t rootFd = AT_FDCWD;
  1512. #else
  1513. openat_arg_t rootFd = "";
  1514. #endif
  1515. LinuxProcessTable_recurseProcTree(this, rootFd, lhost, PROCDIR, NULL);
  1516. }