ProcessModel.cpp 21 KB

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