ProcessModel.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "ProcessModel.h"
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonValue.h>
  10. #include <AK/NonnullRefPtr.h>
  11. #include <AK/NumberFormat.h>
  12. #include <LibCore/DeprecatedFile.h>
  13. #include <LibCore/ProcessStatisticsReader.h>
  14. #include <LibGUI/FileIconProvider.h>
  15. #include <LibGUI/Icon.h>
  16. #include <LibGUI/ModelIndex.h>
  17. #include <LibGUI/ModelRole.h>
  18. #include <unistd.h>
  19. static ProcessModel* s_the;
  20. ProcessModel& ProcessModel::the()
  21. {
  22. VERIFY(s_the);
  23. return *s_the;
  24. }
  25. ProcessModel::ProcessModel()
  26. {
  27. VERIFY(!s_the);
  28. s_the = this;
  29. auto file = Core::DeprecatedFile::construct("/sys/kernel/cpuinfo");
  30. if (file->open(Core::OpenMode::ReadOnly)) {
  31. auto buffer = file->read_all();
  32. auto json = JsonValue::from_string({ buffer });
  33. auto cpuinfo_array = json.value().as_array();
  34. cpuinfo_array.for_each([&](auto& value) {
  35. auto& cpu_object = value.as_object();
  36. auto cpu_id = cpu_object.get_u32("processor"sv).value();
  37. m_cpus.append(make<CpuInfo>(cpu_id));
  38. });
  39. }
  40. if (m_cpus.is_empty())
  41. m_cpus.append(make<CpuInfo>(0));
  42. m_kernel_process_icon = GUI::Icon::default_icon("gear"sv);
  43. }
  44. int ProcessModel::row_count(GUI::ModelIndex const& index) const
  45. {
  46. if (!index.is_valid())
  47. return m_processes.size();
  48. // Anything in the second level (threads of processes) doesn't have children.
  49. // This way, we don't get infinitely recursing main threads without having to handle that special case elsewhere.
  50. if (index.parent().is_valid())
  51. return 0;
  52. auto const& thread = *static_cast<Thread const*>(index.internal_data());
  53. // Only the main thread has the other threads as its children.
  54. // Also, if there's not more than one thread, we won't draw that.
  55. if (thread.is_main_thread() && thread.current_state.process.threads.size() > 1)
  56. return thread.current_state.process.threads.size() - 1;
  57. return 0;
  58. }
  59. int ProcessModel::column_count(GUI::ModelIndex const&) const
  60. {
  61. return Column::__Count;
  62. }
  63. DeprecatedString ProcessModel::column_name(int column) const
  64. {
  65. switch (column) {
  66. case Column::Icon:
  67. return "";
  68. case Column::PID:
  69. return "PID";
  70. case Column::TID:
  71. return "TID";
  72. case Column::PPID:
  73. return "PPID";
  74. case Column::PGID:
  75. return "PGID";
  76. case Column::SID:
  77. return "SID";
  78. case Column::State:
  79. return "State";
  80. case Column::User:
  81. return "User";
  82. case Column::Priority:
  83. return "Pr";
  84. case Column::Virtual:
  85. return "Virtual";
  86. case Column::Physical:
  87. return "Physical";
  88. case Column::DirtyPrivate:
  89. return "Private";
  90. case Column::CleanInode:
  91. return "CleanI";
  92. case Column::PurgeableVolatile:
  93. return "Purg:V";
  94. case Column::PurgeableNonvolatile:
  95. return "Purg:N";
  96. case Column::CPU:
  97. return "CPU";
  98. case Column::Processor:
  99. return "Processor";
  100. case Column::Name:
  101. return "Name";
  102. case Column::Syscalls:
  103. return "Syscalls";
  104. case Column::InodeFaults:
  105. return "F:Inode";
  106. case Column::ZeroFaults:
  107. return "F:Zero";
  108. case Column::CowFaults:
  109. return "F:CoW";
  110. case Column::IPv4SocketReadBytes:
  111. return "IPv4 In";
  112. case Column::IPv4SocketWriteBytes:
  113. return "IPv4 Out";
  114. case Column::UnixSocketReadBytes:
  115. return "Unix In";
  116. case Column::UnixSocketWriteBytes:
  117. return "Unix Out";
  118. case Column::FileReadBytes:
  119. return "File In";
  120. case Column::FileWriteBytes:
  121. return "File Out";
  122. case Column::Pledge:
  123. return "Pledge";
  124. case Column::Veil:
  125. return "Veil";
  126. case Column::Command:
  127. return "Command";
  128. default:
  129. VERIFY_NOT_REACHED();
  130. }
  131. }
  132. GUI::Variant ProcessModel::data(GUI::ModelIndex const& index, GUI::ModelRole role) const
  133. {
  134. VERIFY(is_within_range(index));
  135. if (role == GUI::ModelRole::TextAlignment) {
  136. switch (index.column()) {
  137. case Column::Icon:
  138. case Column::Name:
  139. case Column::State:
  140. case Column::User:
  141. case Column::Pledge:
  142. case Column::Veil:
  143. case Column::Command:
  144. return Gfx::TextAlignment::CenterLeft;
  145. case Column::PID:
  146. case Column::TID:
  147. case Column::PPID:
  148. case Column::PGID:
  149. case Column::SID:
  150. case Column::Priority:
  151. case Column::Virtual:
  152. case Column::Physical:
  153. case Column::DirtyPrivate:
  154. case Column::CleanInode:
  155. case Column::PurgeableVolatile:
  156. case Column::PurgeableNonvolatile:
  157. case Column::CPU:
  158. case Column::Processor:
  159. case Column::Syscalls:
  160. case Column::InodeFaults:
  161. case Column::ZeroFaults:
  162. case Column::CowFaults:
  163. case Column::FileReadBytes:
  164. case Column::FileWriteBytes:
  165. case Column::UnixSocketReadBytes:
  166. case Column::UnixSocketWriteBytes:
  167. case Column::IPv4SocketReadBytes:
  168. case Column::IPv4SocketWriteBytes:
  169. return Gfx::TextAlignment::CenterRight;
  170. default:
  171. VERIFY_NOT_REACHED();
  172. }
  173. }
  174. auto const& thread = *static_cast<Thread const*>(index.internal_data());
  175. if (role == GUI::ModelRole::Sort) {
  176. switch (index.column()) {
  177. case Column::Icon:
  178. return 0;
  179. case Column::PID:
  180. return thread.current_state.pid;
  181. case Column::TID:
  182. return thread.current_state.tid;
  183. case Column::PPID:
  184. return thread.current_state.ppid;
  185. case Column::PGID:
  186. return thread.current_state.pgid;
  187. case Column::SID:
  188. return thread.current_state.sid;
  189. case Column::State:
  190. return thread.current_state.state;
  191. case Column::User:
  192. return thread.current_state.user;
  193. case Column::Priority:
  194. return thread.current_state.priority;
  195. case Column::Virtual:
  196. return (int)thread.current_state.amount_virtual;
  197. case Column::Physical:
  198. return (int)thread.current_state.amount_resident;
  199. case Column::DirtyPrivate:
  200. return (int)thread.current_state.amount_dirty_private;
  201. case Column::CleanInode:
  202. return (int)thread.current_state.amount_clean_inode;
  203. case Column::PurgeableVolatile:
  204. return (int)thread.current_state.amount_purgeable_volatile;
  205. case Column::PurgeableNonvolatile:
  206. return (int)thread.current_state.amount_purgeable_nonvolatile;
  207. case Column::CPU:
  208. return thread.current_state.cpu_percent;
  209. case Column::Processor:
  210. return thread.current_state.cpu;
  211. case Column::Name:
  212. return thread.current_state.name;
  213. case Column::Command:
  214. return thread.current_state.command;
  215. case Column::Syscalls:
  216. return thread.current_state.syscall_count;
  217. case Column::InodeFaults:
  218. return thread.current_state.inode_faults;
  219. case Column::ZeroFaults:
  220. return thread.current_state.zero_faults;
  221. case Column::CowFaults:
  222. return thread.current_state.cow_faults;
  223. case Column::IPv4SocketReadBytes:
  224. return thread.current_state.ipv4_socket_read_bytes;
  225. case Column::IPv4SocketWriteBytes:
  226. return thread.current_state.ipv4_socket_write_bytes;
  227. case Column::UnixSocketReadBytes:
  228. return thread.current_state.unix_socket_read_bytes;
  229. case Column::UnixSocketWriteBytes:
  230. return thread.current_state.unix_socket_write_bytes;
  231. case Column::FileReadBytes:
  232. return thread.current_state.file_read_bytes;
  233. case Column::FileWriteBytes:
  234. return thread.current_state.file_write_bytes;
  235. case Column::Pledge:
  236. return thread.current_state.pledge;
  237. case Column::Veil:
  238. return thread.current_state.veil;
  239. }
  240. VERIFY_NOT_REACHED();
  241. }
  242. if (role == GUI::ModelRole::Display) {
  243. switch (index.column()) {
  244. case Column::Icon:
  245. return icon_for(thread);
  246. case Column::PID:
  247. return thread.current_state.pid;
  248. case Column::TID:
  249. return thread.current_state.tid;
  250. case Column::PPID:
  251. return thread.current_state.ppid;
  252. case Column::PGID:
  253. return thread.current_state.pgid;
  254. case Column::SID:
  255. return thread.current_state.sid;
  256. case Column::State:
  257. return thread.current_state.state;
  258. case Column::User:
  259. return thread.current_state.user;
  260. case Column::Priority:
  261. return thread.current_state.priority;
  262. case Column::Virtual:
  263. return human_readable_size(thread.current_state.amount_virtual);
  264. case Column::Physical:
  265. return human_readable_size(thread.current_state.amount_resident);
  266. case Column::DirtyPrivate:
  267. return human_readable_size(thread.current_state.amount_dirty_private);
  268. case Column::CleanInode:
  269. return human_readable_size(thread.current_state.amount_clean_inode);
  270. case Column::PurgeableVolatile:
  271. return human_readable_size(thread.current_state.amount_purgeable_volatile);
  272. case Column::PurgeableNonvolatile:
  273. return human_readable_size(thread.current_state.amount_purgeable_nonvolatile);
  274. case Column::CPU:
  275. return DeprecatedString::formatted("{:.2}", thread.current_state.cpu_percent);
  276. case Column::Processor:
  277. return thread.current_state.cpu;
  278. case Column::Name:
  279. if (thread.current_state.kernel)
  280. return DeprecatedString::formatted("{} (*)", thread.current_state.name);
  281. return thread.current_state.name;
  282. case Column::Command:
  283. return thread.current_state.command;
  284. case Column::Syscalls:
  285. return thread.current_state.syscall_count;
  286. case Column::InodeFaults:
  287. return thread.current_state.inode_faults;
  288. case Column::ZeroFaults:
  289. return thread.current_state.zero_faults;
  290. case Column::CowFaults:
  291. return thread.current_state.cow_faults;
  292. case Column::IPv4SocketReadBytes:
  293. return thread.current_state.ipv4_socket_read_bytes;
  294. case Column::IPv4SocketWriteBytes:
  295. return thread.current_state.ipv4_socket_write_bytes;
  296. case Column::UnixSocketReadBytes:
  297. return thread.current_state.unix_socket_read_bytes;
  298. case Column::UnixSocketWriteBytes:
  299. return thread.current_state.unix_socket_write_bytes;
  300. case Column::FileReadBytes:
  301. return thread.current_state.file_read_bytes;
  302. case Column::FileWriteBytes:
  303. return thread.current_state.file_write_bytes;
  304. case Column::Pledge:
  305. return thread.current_state.pledge;
  306. case Column::Veil:
  307. return thread.current_state.veil;
  308. }
  309. }
  310. if (role == GUI::ModelRole::Icon)
  311. return icon_for(thread);
  312. if (role == GUI::ModelRole::IconOpacity) {
  313. if (thread.current_state.uid != getuid())
  314. return 0.5f;
  315. return {};
  316. }
  317. return {};
  318. }
  319. GUI::Icon ProcessModel::icon_for(Thread const& thread) const
  320. {
  321. if (thread.current_state.kernel)
  322. return m_kernel_process_icon;
  323. return GUI::FileIconProvider::icon_for_executable(thread.current_state.executable);
  324. }
  325. GUI::ModelIndex ProcessModel::index(int row, int column, GUI::ModelIndex const& parent) const
  326. {
  327. if (row < 0 || column < 0)
  328. return {};
  329. // Process index; we display the main thread here.
  330. if (!parent.is_valid()) {
  331. if (row >= static_cast<int>(m_processes.size()))
  332. return {};
  333. auto corresponding_thread = m_processes[row]->main_thread();
  334. if (!corresponding_thread.has_value())
  335. return {};
  336. return create_index(row, column, corresponding_thread.release_value().ptr());
  337. }
  338. // Thread under process.
  339. auto const& parent_thread = *static_cast<Thread const*>(parent.internal_data());
  340. auto const& process = parent_thread.current_state.process;
  341. // dbgln("Getting thread model index in process {} for col {} row {}", process.pid, column, row);
  342. if (row >= static_cast<int>(process.threads.size()))
  343. return {};
  344. return create_index(row, column, &process.non_main_thread(row));
  345. }
  346. int ProcessModel::thread_model_row(Thread const& thread) const
  347. {
  348. auto const& process = thread.current_state.process;
  349. // A process's main thread uses the global process index.
  350. if (process.pid == thread.current_state.pid) {
  351. auto it = m_processes.find_if([&](auto& entry) {
  352. return entry.ptr() == &process;
  353. });
  354. if (it == m_processes.end())
  355. return 0;
  356. return it.index();
  357. }
  358. return process.threads.find_first_index(thread).value_or(0);
  359. }
  360. GUI::ModelIndex ProcessModel::parent_index(GUI::ModelIndex const& index) const
  361. {
  362. if (!index.is_valid())
  363. return {};
  364. auto const& thread = *static_cast<Thread*>(index.internal_data());
  365. // There's no parent for the main thread.
  366. if (thread.current_state.pid == thread.current_state.tid)
  367. return {};
  368. // FIXME: We can't use first_matching here (not even a const version) because Optional cannot contain references.
  369. auto const& parent = thread.current_state.process;
  370. if (!parent.main_thread().has_value())
  371. return {};
  372. auto process_index = [&]() -> size_t {
  373. auto it = m_processes.find_if([&](auto& entry) {
  374. return entry.ptr() == &parent;
  375. });
  376. if (it == m_processes.end())
  377. return 0;
  378. return it.index();
  379. }();
  380. return create_index(process_index, index.column(), parent.main_thread().value().ptr());
  381. }
  382. Vector<GUI::ModelIndex> ProcessModel::matches(StringView searching, unsigned flags, GUI::ModelIndex const&)
  383. {
  384. Vector<GUI::ModelIndex> found_indices;
  385. for (auto const& thread : m_threads) {
  386. if (string_matches(thread.value->current_state.name, searching, flags)) {
  387. auto tid_row = thread_model_row(thread.value);
  388. found_indices.append(create_index(tid_row, Column::Name, reinterpret_cast<void const*>(thread.value.ptr())));
  389. if (flags & FirstMatchOnly)
  390. break;
  391. }
  392. }
  393. return found_indices;
  394. }
  395. static ErrorOr<DeprecatedString> try_read_command_line(pid_t pid)
  396. {
  397. auto file = TRY(Core::File::open(DeprecatedString::formatted("/proc/{}/cmdline", pid), Core::File::OpenMode::Read));
  398. auto data = TRY(file->read_until_eof());
  399. auto json = TRY(JsonValue::from_string(StringView { data.bytes() }));
  400. auto array = json.as_array().values();
  401. return DeprecatedString::join(" "sv, array);
  402. }
  403. static DeprecatedString read_command_line(pid_t pid)
  404. {
  405. auto string_or_error = try_read_command_line(pid);
  406. if (string_or_error.is_error()) {
  407. return "";
  408. }
  409. return string_or_error.release_value();
  410. }
  411. void ProcessModel::update()
  412. {
  413. auto previous_tid_count = m_threads.size();
  414. auto all_processes = Core::ProcessStatisticsReader::get_all(m_proc_all);
  415. HashTable<int> live_tids;
  416. u64 total_time_scheduled_diff = 0;
  417. if (!all_processes.is_error()) {
  418. if (m_has_total_scheduled_time)
  419. total_time_scheduled_diff = all_processes.value().total_time_scheduled - m_total_time_scheduled;
  420. m_total_time_scheduled = all_processes.value().total_time_scheduled;
  421. m_total_time_scheduled_kernel = all_processes.value().total_time_scheduled_kernel;
  422. m_has_total_scheduled_time = true;
  423. for (size_t i = 0; i < all_processes.value().processes.size(); ++i) {
  424. auto const& process = all_processes.value().processes[i];
  425. NonnullOwnPtr<Process>* process_state = nullptr;
  426. for (size_t i = 0; i < m_processes.size(); ++i) {
  427. auto* other_process = &m_processes[i];
  428. if ((*other_process)->pid == process.pid) {
  429. process_state = other_process;
  430. break;
  431. }
  432. }
  433. if (!process_state) {
  434. m_processes.append(make<Process>());
  435. process_state = &m_processes.last();
  436. }
  437. (*process_state)->pid = process.pid;
  438. for (auto& thread : process.threads) {
  439. ThreadState state(**process_state);
  440. state.tid = thread.tid;
  441. state.pid = process.pid;
  442. state.ppid = process.ppid;
  443. state.pgid = process.pgid;
  444. state.sid = process.sid;
  445. state.time_user = thread.time_user;
  446. state.time_kernel = thread.time_kernel;
  447. state.kernel = process.kernel;
  448. state.executable = process.executable;
  449. state.name = thread.name;
  450. state.command = read_command_line(process.pid);
  451. state.uid = process.uid;
  452. state.state = thread.state;
  453. state.user = process.username;
  454. state.pledge = process.pledge;
  455. state.veil = process.veil;
  456. state.cpu = thread.cpu;
  457. state.priority = thread.priority;
  458. state.amount_virtual = process.amount_virtual;
  459. state.amount_resident = process.amount_resident;
  460. state.amount_dirty_private = process.amount_dirty_private;
  461. state.amount_clean_inode = process.amount_clean_inode;
  462. state.amount_purgeable_volatile = process.amount_purgeable_volatile;
  463. state.amount_purgeable_nonvolatile = process.amount_purgeable_nonvolatile;
  464. state.syscall_count = thread.syscall_count;
  465. state.inode_faults = thread.inode_faults;
  466. state.zero_faults = thread.zero_faults;
  467. state.cow_faults = thread.cow_faults;
  468. state.unix_socket_read_bytes = thread.unix_socket_read_bytes;
  469. state.unix_socket_write_bytes = thread.unix_socket_write_bytes;
  470. state.ipv4_socket_read_bytes = thread.ipv4_socket_read_bytes;
  471. state.ipv4_socket_write_bytes = thread.ipv4_socket_write_bytes;
  472. state.file_read_bytes = thread.file_read_bytes;
  473. state.file_write_bytes = thread.file_write_bytes;
  474. state.cpu_percent = 0;
  475. auto thread_data = m_threads.ensure(thread.tid, [&] { return make_ref_counted<Thread>(**process_state); });
  476. thread_data->previous_state = move(thread_data->current_state);
  477. thread_data->current_state = move(state);
  478. if (auto maybe_thread_index = (*process_state)->threads.find_first_index(thread_data); maybe_thread_index.has_value()) {
  479. (*process_state)->threads[maybe_thread_index.value()] = thread_data;
  480. } else {
  481. (*process_state)->threads.append(thread_data);
  482. }
  483. live_tids.set(thread.tid);
  484. }
  485. }
  486. }
  487. for (auto& c : m_cpus) {
  488. c->total_cpu_percent = 0.0;
  489. c->total_cpu_percent_kernel = 0.0;
  490. }
  491. Vector<int, 16> tids_to_remove;
  492. for (auto& it : m_threads) {
  493. if (!live_tids.contains(it.key)) {
  494. tids_to_remove.append(it.key);
  495. continue;
  496. }
  497. auto& thread = *it.value;
  498. u64 time_scheduled_diff = (thread.current_state.time_user + thread.current_state.time_kernel)
  499. - (thread.previous_state.time_user + thread.previous_state.time_kernel);
  500. u64 time_scheduled_diff_kernel = thread.current_state.time_kernel - thread.previous_state.time_kernel;
  501. thread.current_state.cpu_percent = total_time_scheduled_diff > 0 ? (float)((time_scheduled_diff * 1000) / total_time_scheduled_diff) / 10.0f : 0;
  502. thread.current_state.cpu_percent_kernel = total_time_scheduled_diff > 0 ? (float)((time_scheduled_diff_kernel * 1000) / total_time_scheduled_diff) / 10.0f : 0;
  503. if (it.value->current_state.pid != 0) {
  504. auto& cpu_info = m_cpus[thread.current_state.cpu];
  505. cpu_info->total_cpu_percent += thread.current_state.cpu_percent;
  506. cpu_info->total_cpu_percent_kernel += thread.current_state.cpu_percent_kernel;
  507. }
  508. }
  509. // FIXME: Also remove dead threads from processes
  510. for (auto tid : tids_to_remove) {
  511. m_threads.remove(tid);
  512. for (size_t i = 0; i < m_processes.size(); ++i) {
  513. auto& process = m_processes[i];
  514. process->threads.remove_all_matching([&](auto const& thread) { return thread->current_state.tid == tid; });
  515. if (process->threads.size() == 0) {
  516. m_processes.remove(i);
  517. --i;
  518. }
  519. }
  520. }
  521. if (on_cpu_info_change)
  522. on_cpu_info_change(m_cpus);
  523. if (on_state_update)
  524. on_state_update(!all_processes.is_error() ? all_processes.value().processes.size() : 0, m_threads.size());
  525. // FIXME: This is a rather hackish way of invalidating indices.
  526. // It would be good if GUI::Model had a way to orchestrate removal/insertion while preserving indices.
  527. did_update(previous_tid_count == m_threads.size() ? GUI::Model::UpdateFlag::DontInvalidateIndices : GUI::Model::UpdateFlag::InvalidateAllIndices);
  528. }
  529. bool ProcessModel::is_default_column(int index) const
  530. {
  531. switch (index) {
  532. case Column::PID:
  533. case Column::TID:
  534. case Column::Name:
  535. case Column::CPU:
  536. case Column::User:
  537. case Column::Virtual:
  538. case Column::DirtyPrivate:
  539. return true;
  540. default:
  541. return false;
  542. }
  543. }