ProcFS.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. #include "ProcFS.h"
  2. #include "Console.h"
  3. #include "KSyms.h"
  4. #include "Process.h"
  5. #include "Scheduler.h"
  6. #include "StdLib.h"
  7. #include <AK/JsonArraySerializer.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonObjectSerializer.h>
  10. #include <AK/JsonValue.h>
  11. #include <Kernel/Arch/i386/CPU.h>
  12. #include <Kernel/FileSystem/Custody.h>
  13. #include <Kernel/FileSystem/DiskBackedFileSystem.h>
  14. #include <Kernel/FileSystem/FileDescription.h>
  15. #include <Kernel/FileSystem/VirtualFileSystem.h>
  16. #include <Kernel/Heap/kmalloc.h>
  17. #include <Kernel/KBufferBuilder.h>
  18. #include <Kernel/KParams.h>
  19. #include <Kernel/Module.h>
  20. #include <Kernel/Net/LocalSocket.h>
  21. #include <Kernel/Net/NetworkAdapter.h>
  22. #include <Kernel/Net/Routing.h>
  23. #include <Kernel/Net/TCPSocket.h>
  24. #include <Kernel/Net/UDPSocket.h>
  25. #include <Kernel/PCI.h>
  26. #include <Kernel/Profiling.h>
  27. #include <Kernel/VM/MemoryManager.h>
  28. #include <Kernel/VM/PurgeableVMObject.h>
  29. #include <LibC/errno_numbers.h>
  30. enum ProcParentDirectory {
  31. PDI_AbstractRoot = 0,
  32. PDI_Root,
  33. PDI_Root_sys,
  34. PDI_Root_net,
  35. PDI_PID,
  36. PDI_PID_fd,
  37. };
  38. enum ProcFileType {
  39. FI_Invalid = 0,
  40. FI_Root = 1, // directory
  41. __FI_Root_Start,
  42. FI_Root_mm,
  43. FI_Root_mounts,
  44. FI_Root_df,
  45. FI_Root_all,
  46. FI_Root_memstat,
  47. FI_Root_cpuinfo,
  48. FI_Root_inodes,
  49. FI_Root_dmesg,
  50. FI_Root_pci,
  51. FI_Root_devices,
  52. FI_Root_uptime,
  53. FI_Root_cmdline,
  54. FI_Root_modules,
  55. FI_Root_profile,
  56. FI_Root_self, // symlink
  57. FI_Root_sys, // directory
  58. FI_Root_net, // directory
  59. __FI_Root_End,
  60. FI_Root_sys_variable,
  61. FI_Root_net_adapters,
  62. FI_Root_net_arp,
  63. FI_Root_net_tcp,
  64. FI_Root_net_udp,
  65. FI_Root_net_local,
  66. FI_PID,
  67. __FI_PID_Start,
  68. FI_PID_vm,
  69. FI_PID_vmobjects,
  70. FI_PID_stack,
  71. FI_PID_regs,
  72. FI_PID_fds,
  73. FI_PID_exe, // symlink
  74. FI_PID_cwd, // symlink
  75. FI_PID_fd, // directory
  76. __FI_PID_End,
  77. FI_MaxStaticFileIndex,
  78. };
  79. static inline pid_t to_pid(const InodeIdentifier& identifier)
  80. {
  81. #ifdef PROCFS_DEBUG
  82. dbgprintf("to_pid, index=%08x -> %u\n", identifier.index(), identifier.index() >> 16);
  83. #endif
  84. return identifier.index() >> 16u;
  85. }
  86. static inline ProcParentDirectory to_proc_parent_directory(const InodeIdentifier& identifier)
  87. {
  88. return (ProcParentDirectory)((identifier.index() >> 12) & 0xf);
  89. }
  90. static inline ProcFileType to_proc_file_type(const InodeIdentifier& identifier)
  91. {
  92. return (ProcFileType)(identifier.index() & 0xff);
  93. }
  94. static inline int to_fd(const InodeIdentifier& identifier)
  95. {
  96. ASSERT(to_proc_parent_directory(identifier) == PDI_PID_fd);
  97. return (identifier.index() & 0xff) - FI_MaxStaticFileIndex;
  98. }
  99. static inline int to_sys_index(const InodeIdentifier& identifier)
  100. {
  101. ASSERT(to_proc_parent_directory(identifier) == PDI_Root_sys);
  102. ASSERT(to_proc_file_type(identifier) == FI_Root_sys_variable);
  103. return identifier.index() >> 16u;
  104. }
  105. static inline InodeIdentifier to_identifier(unsigned fsid, ProcParentDirectory parent, pid_t pid, ProcFileType proc_file_type)
  106. {
  107. return { fsid, ((unsigned)parent << 12u) | ((unsigned)pid << 16u) | (unsigned)proc_file_type };
  108. }
  109. static inline InodeIdentifier to_identifier_with_fd(unsigned fsid, pid_t pid, int fd)
  110. {
  111. return { fsid, (PDI_PID_fd << 12u) | ((unsigned)pid << 16u) | (FI_MaxStaticFileIndex + fd) };
  112. }
  113. static inline InodeIdentifier sys_var_to_identifier(unsigned fsid, unsigned index)
  114. {
  115. ASSERT(index < 256);
  116. return { fsid, (PDI_Root_sys << 12u) | (index << 16u) | FI_Root_sys_variable };
  117. }
  118. static inline InodeIdentifier to_parent_id(const InodeIdentifier& identifier)
  119. {
  120. switch (to_proc_parent_directory(identifier)) {
  121. case PDI_AbstractRoot:
  122. case PDI_Root:
  123. return { identifier.fsid(), FI_Root };
  124. case PDI_Root_sys:
  125. return { identifier.fsid(), FI_Root_sys };
  126. case PDI_Root_net:
  127. return { identifier.fsid(), FI_Root_net };
  128. case PDI_PID:
  129. return to_identifier(identifier.fsid(), PDI_Root, to_pid(identifier), FI_PID);
  130. case PDI_PID_fd:
  131. return to_identifier(identifier.fsid(), PDI_PID, to_pid(identifier), FI_PID_fd);
  132. }
  133. ASSERT_NOT_REACHED();
  134. }
  135. #if 0
  136. static inline u8 to_unused_metadata(const InodeIdentifier& identifier)
  137. {
  138. return (identifier.index() >> 8) & 0xf;
  139. }
  140. #endif
  141. static inline bool is_process_related_file(const InodeIdentifier& identifier)
  142. {
  143. if (to_proc_file_type(identifier) == FI_PID)
  144. return true;
  145. auto proc_parent_directory = to_proc_parent_directory(identifier);
  146. switch (proc_parent_directory) {
  147. case PDI_PID:
  148. case PDI_PID_fd:
  149. return true;
  150. default:
  151. return false;
  152. }
  153. }
  154. static inline bool is_directory(const InodeIdentifier& identifier)
  155. {
  156. auto proc_file_type = to_proc_file_type(identifier);
  157. switch (proc_file_type) {
  158. case FI_Root:
  159. case FI_Root_sys:
  160. case FI_Root_net:
  161. case FI_PID:
  162. case FI_PID_fd:
  163. return true;
  164. default:
  165. return false;
  166. }
  167. }
  168. static inline bool is_persistent_inode(const InodeIdentifier& identifier)
  169. {
  170. return to_proc_parent_directory(identifier) == PDI_Root_sys;
  171. }
  172. NonnullRefPtr<ProcFS> ProcFS::create()
  173. {
  174. return adopt(*new ProcFS);
  175. }
  176. ProcFS::~ProcFS()
  177. {
  178. }
  179. Optional<KBuffer> procfs$pid_fds(InodeIdentifier identifier)
  180. {
  181. KBufferBuilder builder;
  182. JsonArraySerializer array { builder };
  183. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  184. if (!handle) {
  185. array.finish();
  186. return builder.build();
  187. }
  188. auto& process = handle->process();
  189. if (process.number_of_open_file_descriptors() == 0) {
  190. array.finish();
  191. return builder.build();
  192. }
  193. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  194. auto* description = process.file_description(i);
  195. if (!description)
  196. continue;
  197. bool cloexec = process.fd_flags(i) & FD_CLOEXEC;
  198. auto description_object = array.add_object();
  199. description_object.add("fd", i);
  200. description_object.add("absolute_path", description->absolute_path());
  201. description_object.add("seekable", description->file().is_seekable());
  202. description_object.add("class", description->file().class_name());
  203. description_object.add("offset", description->offset());
  204. description_object.add("cloexec", cloexec);
  205. description_object.add("blocking", description->is_blocking());
  206. description_object.add("can_read", description->can_read());
  207. description_object.add("can_write", description->can_write());
  208. }
  209. array.finish();
  210. return builder.build();
  211. }
  212. Optional<KBuffer> procfs$pid_fd_entry(InodeIdentifier identifier)
  213. {
  214. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  215. if (!handle)
  216. return {};
  217. auto& process = handle->process();
  218. int fd = to_fd(identifier);
  219. auto* description = process.file_description(fd);
  220. if (!description)
  221. return {};
  222. return description->absolute_path().to_byte_buffer();
  223. }
  224. Optional<KBuffer> procfs$pid_vm(InodeIdentifier identifier)
  225. {
  226. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  227. if (!handle)
  228. return {};
  229. auto& process = handle->process();
  230. KBufferBuilder builder;
  231. JsonArraySerializer array { builder };
  232. for (auto& region : process.regions()) {
  233. auto region_object = array.add_object();
  234. region_object.add("readable", region.is_readable());
  235. region_object.add("writable", region.is_writable());
  236. region_object.add("executable", region.is_executable());
  237. region_object.add("stack", region.is_stack());
  238. region_object.add("shared", region.is_shared());
  239. region_object.add("user_accessible", region.is_user_accessible());
  240. region_object.add("purgeable", region.vmobject().is_purgeable());
  241. if (region.vmobject().is_purgeable()) {
  242. region_object.add("volatile", static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile());
  243. }
  244. region_object.add("purgeable", region.vmobject().is_purgeable());
  245. region_object.add("address", region.vaddr().get());
  246. region_object.add("size", (u32)region.size());
  247. region_object.add("amount_resident", (u32)region.amount_resident());
  248. region_object.add("cow_pages", region.cow_pages());
  249. region_object.add("name", region.name());
  250. }
  251. array.finish();
  252. return builder.build();
  253. }
  254. Optional<KBuffer> procfs$pci(InodeIdentifier)
  255. {
  256. KBufferBuilder builder;
  257. JsonArraySerializer array { builder };
  258. PCI::enumerate_all([&array](PCI::Address address, PCI::ID id) {
  259. auto obj = array.add_object();
  260. obj.add("bus", address.bus());
  261. obj.add("slot", address.slot());
  262. obj.add("function", address.function());
  263. obj.add("vendor_id", id.vendor_id);
  264. obj.add("device_id", id.device_id);
  265. obj.add("revision_id", PCI::get_revision_id(address));
  266. obj.add("subclass", PCI::get_subclass(address));
  267. obj.add("class", PCI::get_class(address));
  268. obj.add("subsystem_id", PCI::get_subsystem_id(address));
  269. obj.add("subsystem_vendor_id", PCI::get_subsystem_vendor_id(address));
  270. });
  271. array.finish();
  272. return builder.build();
  273. }
  274. Optional<KBuffer> procfs$devices(InodeIdentifier)
  275. {
  276. KBufferBuilder builder;
  277. JsonArraySerializer array { builder };
  278. Device::for_each([&array](auto& device) {
  279. auto obj = array.add_object();
  280. obj.add("major", device.major());
  281. obj.add("minor", device.minor());
  282. obj.add("class_name", device.class_name());
  283. if (device.is_block_device())
  284. obj.add("type", "block");
  285. else if (device.is_character_device())
  286. obj.add("type", "character");
  287. else
  288. ASSERT_NOT_REACHED();
  289. });
  290. array.finish();
  291. return builder.build();
  292. }
  293. Optional<KBuffer> procfs$uptime(InodeIdentifier)
  294. {
  295. KBufferBuilder builder;
  296. builder.appendf("%u\n", (u32)(g_uptime / 1000));
  297. return builder.build();
  298. }
  299. Optional<KBuffer> procfs$cmdline(InodeIdentifier)
  300. {
  301. KBufferBuilder builder;
  302. builder.appendf("%s\n", KParams::the().cmdline().characters());
  303. return builder.build();
  304. }
  305. Optional<KBuffer> procfs$modules(InodeIdentifier)
  306. {
  307. extern HashMap<String, OwnPtr<Module>>* g_modules;
  308. KBufferBuilder builder;
  309. JsonArraySerializer array { builder };
  310. for (auto& it : *g_modules) {
  311. auto obj = array.add_object();
  312. obj.add("name", it.value->name);
  313. obj.add("module_init", (u32)it.value->module_init);
  314. obj.add("module_fini", (u32)it.value->module_fini);
  315. u32 size = 0;
  316. for (auto& section : it.value->sections) {
  317. size += section.capacity();
  318. }
  319. obj.add("size", size);
  320. }
  321. array.finish();
  322. return builder.build();
  323. }
  324. Optional<KBuffer> procfs$profile(InodeIdentifier)
  325. {
  326. InterruptDisabler disabler;
  327. KBufferBuilder builder;
  328. JsonArraySerializer array(builder);
  329. Profiling::for_each_sample([&](auto& sample) {
  330. auto object = array.add_object();
  331. object.add("pid", sample.pid);
  332. object.add("tid", sample.tid);
  333. object.add("timestamp", sample.timestamp);
  334. auto frames_array = object.add_array("frames");
  335. for (size_t i = 0; i < Profiling::max_stack_frame_count; ++i) {
  336. if (sample.frames[i] == 0)
  337. break;
  338. auto frame_object = frames_array.add_object();
  339. frame_object.add("address", JsonValue((u32)sample.frames[i]));
  340. frame_object.add("symbol", sample.symbolicated_frames[i]);
  341. frame_object.add("offset", JsonValue((u32)sample.offsets[i]));
  342. frame_object.finish();
  343. }
  344. frames_array.finish();
  345. });
  346. array.finish();
  347. return builder.build();
  348. }
  349. Optional<KBuffer> procfs$net_adapters(InodeIdentifier)
  350. {
  351. KBufferBuilder builder;
  352. JsonArraySerializer array { builder };
  353. NetworkAdapter::for_each([&array](auto& adapter) {
  354. auto obj = array.add_object();
  355. obj.add("name", adapter.name());
  356. obj.add("class_name", adapter.class_name());
  357. obj.add("mac_address", adapter.mac_address().to_string());
  358. if (!adapter.ipv4_address().is_zero()) {
  359. obj.add("ipv4_address", adapter.ipv4_address().to_string());
  360. obj.add("ipv4_netmask", adapter.ipv4_netmask().to_string());
  361. }
  362. if (!adapter.ipv4_gateway().is_zero())
  363. obj.add("ipv4_gateway", adapter.ipv4_gateway().to_string());
  364. obj.add("packets_in", adapter.packets_in());
  365. obj.add("bytes_in", adapter.bytes_in());
  366. obj.add("packets_out", adapter.packets_out());
  367. obj.add("bytes_out", adapter.bytes_out());
  368. obj.add("link_up", adapter.link_up());
  369. obj.add("mtu", adapter.mtu());
  370. });
  371. array.finish();
  372. return builder.build();
  373. }
  374. Optional<KBuffer> procfs$net_arp(InodeIdentifier)
  375. {
  376. KBufferBuilder builder;
  377. JsonArraySerializer array { builder };
  378. LOCKER(arp_table().lock());
  379. for (auto& it : arp_table().resource()) {
  380. auto obj = array.add_object();
  381. obj.add("mac_address", it.value.to_string());
  382. obj.add("ip_address", it.key.to_string());
  383. }
  384. array.finish();
  385. return builder.build();
  386. }
  387. Optional<KBuffer> procfs$net_tcp(InodeIdentifier)
  388. {
  389. KBufferBuilder builder;
  390. JsonArraySerializer array { builder };
  391. TCPSocket::for_each([&array](auto& socket) {
  392. auto obj = array.add_object();
  393. obj.add("local_address", socket.local_address().to_string());
  394. obj.add("local_port", socket.local_port());
  395. obj.add("peer_address", socket.peer_address().to_string());
  396. obj.add("peer_port", socket.peer_port());
  397. obj.add("state", TCPSocket::to_string(socket.state()));
  398. obj.add("ack_number", socket.ack_number());
  399. obj.add("sequence_number", socket.sequence_number());
  400. obj.add("packets_in", socket.packets_in());
  401. obj.add("bytes_in", socket.bytes_in());
  402. obj.add("packets_out", socket.packets_out());
  403. obj.add("bytes_out", socket.bytes_out());
  404. });
  405. array.finish();
  406. return builder.build();
  407. }
  408. Optional<KBuffer> procfs$net_udp(InodeIdentifier)
  409. {
  410. KBufferBuilder builder;
  411. JsonArraySerializer array { builder };
  412. UDPSocket::for_each([&array](auto& socket) {
  413. auto obj = array.add_object();
  414. obj.add("local_address", socket.local_address().to_string());
  415. obj.add("local_port", socket.local_port());
  416. obj.add("peer_address", socket.peer_address().to_string());
  417. obj.add("peer_port", socket.peer_port());
  418. });
  419. array.finish();
  420. return builder.build();
  421. }
  422. Optional<KBuffer> procfs$net_local(InodeIdentifier)
  423. {
  424. KBufferBuilder builder;
  425. JsonArraySerializer array { builder };
  426. LocalSocket::for_each([&array](auto& socket) {
  427. auto obj = array.add_object();
  428. obj.add("path", String(socket.socket_path()));
  429. obj.add("origin_pid", socket.origin_pid());
  430. obj.add("origin_uid", socket.origin_uid());
  431. obj.add("origin_gid", socket.origin_gid());
  432. obj.add("acceptor_pid", socket.acceptor_pid());
  433. obj.add("acceptor_uid", socket.acceptor_uid());
  434. obj.add("acceptor_gid", socket.acceptor_gid());
  435. });
  436. array.finish();
  437. return builder.build();
  438. }
  439. Optional<KBuffer> procfs$pid_vmobjects(InodeIdentifier identifier)
  440. {
  441. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  442. if (!handle)
  443. return {};
  444. auto& process = handle->process();
  445. KBufferBuilder builder;
  446. builder.appendf("BEGIN END SIZE NAME\n");
  447. for (auto& region : process.regions()) {
  448. builder.appendf("%x -- %x %x %s\n",
  449. region.vaddr().get(),
  450. region.vaddr().offset(region.size() - 1).get(),
  451. region.size(),
  452. region.name().characters());
  453. builder.appendf("VMO: %s @ %x(%u)\n",
  454. region.vmobject().is_anonymous() ? "anonymous" : "file-backed",
  455. &region.vmobject(),
  456. region.vmobject().ref_count());
  457. for (size_t i = 0; i < region.vmobject().page_count(); ++i) {
  458. auto& physical_page = region.vmobject().physical_pages()[i];
  459. builder.appendf("P%x%s(%u) ",
  460. physical_page ? physical_page->paddr().get() : 0,
  461. region.should_cow(i) ? "!" : "",
  462. physical_page ? physical_page->ref_count() : 0);
  463. }
  464. builder.appendf("\n");
  465. }
  466. return builder.build();
  467. }
  468. Optional<KBuffer> procfs$pid_stack(InodeIdentifier identifier)
  469. {
  470. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  471. if (!handle)
  472. return {};
  473. auto& process = handle->process();
  474. return process.backtrace(*handle);
  475. }
  476. Optional<KBuffer> procfs$pid_regs(InodeIdentifier identifier)
  477. {
  478. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  479. if (!handle)
  480. return {};
  481. auto& process = handle->process();
  482. KBufferBuilder builder;
  483. process.for_each_thread([&](Thread& thread) {
  484. builder.appendf("Thread %d:\n", thread.tid());
  485. auto& tss = thread.tss();
  486. builder.appendf("eax: %x\n", tss.eax);
  487. builder.appendf("ebx: %x\n", tss.ebx);
  488. builder.appendf("ecx: %x\n", tss.ecx);
  489. builder.appendf("edx: %x\n", tss.edx);
  490. builder.appendf("esi: %x\n", tss.esi);
  491. builder.appendf("edi: %x\n", tss.edi);
  492. builder.appendf("ebp: %x\n", tss.ebp);
  493. builder.appendf("cr3: %x\n", tss.cr3);
  494. builder.appendf("flg: %x\n", tss.eflags);
  495. builder.appendf("sp: %w:%x\n", tss.ss, tss.esp);
  496. builder.appendf("pc: %w:%x\n", tss.cs, tss.eip);
  497. return IterationDecision::Continue;
  498. });
  499. return builder.build();
  500. }
  501. Optional<KBuffer> procfs$pid_exe(InodeIdentifier identifier)
  502. {
  503. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  504. if (!handle)
  505. return {};
  506. auto& process = handle->process();
  507. auto* custody = process.executable();
  508. ASSERT(custody);
  509. return custody->absolute_path().to_byte_buffer();
  510. }
  511. Optional<KBuffer> procfs$pid_cwd(InodeIdentifier identifier)
  512. {
  513. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  514. if (!handle)
  515. return {};
  516. return handle->process().current_directory().absolute_path().to_byte_buffer();
  517. }
  518. Optional<KBuffer> procfs$self(InodeIdentifier)
  519. {
  520. char buffer[16];
  521. sprintf(buffer, "%u", current->pid());
  522. return KBuffer::copy((const u8*)buffer, strlen(buffer));
  523. }
  524. Optional<KBuffer> procfs$mm(InodeIdentifier)
  525. {
  526. InterruptDisabler disabler;
  527. KBufferBuilder builder;
  528. u32 vmobject_count = 0;
  529. MemoryManager::for_each_vmobject([&](auto& vmobject) {
  530. ++vmobject_count;
  531. builder.appendf("VMObject: %p %s(%u): p:%4u\n",
  532. &vmobject,
  533. vmobject.is_anonymous() ? "anon" : "file",
  534. vmobject.ref_count(),
  535. vmobject.page_count());
  536. return IterationDecision::Continue;
  537. });
  538. builder.appendf("VMO count: %u\n", vmobject_count);
  539. builder.appendf("Free physical pages: %u\n", MM.user_physical_pages() - MM.user_physical_pages_used());
  540. builder.appendf("Free supervisor physical pages: %u\n", MM.super_physical_pages() - MM.super_physical_pages_used());
  541. return builder.build();
  542. }
  543. Optional<KBuffer> procfs$dmesg(InodeIdentifier)
  544. {
  545. InterruptDisabler disabler;
  546. KBufferBuilder builder;
  547. for (char ch : Console::the().logbuffer())
  548. builder.append(ch);
  549. return builder.build();
  550. }
  551. Optional<KBuffer> procfs$mounts(InodeIdentifier)
  552. {
  553. // FIXME: This is obviously racy against the VFS mounts changing.
  554. KBufferBuilder builder;
  555. VFS::the().for_each_mount([&builder](auto& mount) {
  556. auto& fs = mount.guest_fs();
  557. builder.appendf("%s @ ", fs.class_name());
  558. if (!mount.host().is_valid())
  559. builder.appendf("/");
  560. else {
  561. builder.appendf("%u:%u", mount.host().fsid(), mount.host().index());
  562. builder.append(' ');
  563. builder.append(mount.absolute_path());
  564. }
  565. builder.append('\n');
  566. });
  567. return builder.build();
  568. }
  569. Optional<KBuffer> procfs$df(InodeIdentifier)
  570. {
  571. // FIXME: This is obviously racy against the VFS mounts changing.
  572. KBufferBuilder builder;
  573. JsonArraySerializer array { builder };
  574. VFS::the().for_each_mount([&array](auto& mount) {
  575. auto& fs = mount.guest_fs();
  576. auto fs_object = array.add_object();
  577. fs_object.add("class_name", fs.class_name());
  578. fs_object.add("total_block_count", fs.total_block_count());
  579. fs_object.add("free_block_count", fs.free_block_count());
  580. fs_object.add("total_inode_count", fs.total_inode_count());
  581. fs_object.add("free_inode_count", fs.free_inode_count());
  582. fs_object.add("mount_point", mount.absolute_path());
  583. fs_object.add("block_size", fs.block_size());
  584. fs_object.add("readonly", fs.is_readonly());
  585. if (fs.is_disk_backed())
  586. fs_object.add("device", static_cast<const DiskBackedFS&>(fs).device().absolute_path());
  587. else
  588. fs_object.add("device", fs.class_name());
  589. });
  590. array.finish();
  591. return builder.build();
  592. }
  593. Optional<KBuffer> procfs$cpuinfo(InodeIdentifier)
  594. {
  595. KBufferBuilder builder;
  596. {
  597. CPUID cpuid(0);
  598. builder.appendf("cpuid: ");
  599. auto emit_u32 = [&](u32 value) {
  600. builder.appendf("%c%c%c%c",
  601. value & 0xff,
  602. (value >> 8) & 0xff,
  603. (value >> 16) & 0xff,
  604. (value >> 24) & 0xff);
  605. };
  606. emit_u32(cpuid.ebx());
  607. emit_u32(cpuid.edx());
  608. emit_u32(cpuid.ecx());
  609. builder.appendf("\n");
  610. }
  611. {
  612. CPUID cpuid(1);
  613. u32 stepping = cpuid.eax() & 0xf;
  614. u32 model = (cpuid.eax() >> 4) & 0xf;
  615. u32 family = (cpuid.eax() >> 8) & 0xf;
  616. u32 type = (cpuid.eax() >> 12) & 0x3;
  617. u32 extended_model = (cpuid.eax() >> 16) & 0xf;
  618. u32 extended_family = (cpuid.eax() >> 20) & 0xff;
  619. u32 display_model;
  620. u32 display_family;
  621. if (family == 15) {
  622. display_family = family + extended_family;
  623. display_model = model + (extended_model << 4);
  624. } else if (family == 6) {
  625. display_family = family;
  626. display_model = model + (extended_model << 4);
  627. } else {
  628. display_family = family;
  629. display_model = model;
  630. }
  631. builder.appendf("family: %u\n", display_family);
  632. builder.appendf("model: %u\n", display_model);
  633. builder.appendf("stepping: %u\n", stepping);
  634. builder.appendf("type: %u\n", type);
  635. }
  636. {
  637. // FIXME: Check first that this is supported by calling CPUID with eax=0x80000000
  638. // and verifying that the returned eax>=0x80000004.
  639. alignas(u32) char buffer[48];
  640. u32* bufptr = reinterpret_cast<u32*>(buffer);
  641. auto copy_brand_string_part_to_buffer = [&](u32 i) {
  642. CPUID cpuid(0x80000002 + i);
  643. *bufptr++ = cpuid.eax();
  644. *bufptr++ = cpuid.ebx();
  645. *bufptr++ = cpuid.ecx();
  646. *bufptr++ = cpuid.edx();
  647. };
  648. copy_brand_string_part_to_buffer(0);
  649. copy_brand_string_part_to_buffer(1);
  650. copy_brand_string_part_to_buffer(2);
  651. builder.appendf("brandstr: \"%s\"\n", buffer);
  652. }
  653. return builder.build();
  654. }
  655. Optional<KBuffer> procfs$memstat(InodeIdentifier)
  656. {
  657. InterruptDisabler disabler;
  658. KBufferBuilder builder;
  659. JsonObjectSerializer<KBufferBuilder> json { builder };
  660. json.add("kmalloc_allocated", (u32)sum_alloc);
  661. json.add("kmalloc_available", (u32)sum_free);
  662. json.add("kmalloc_eternal_allocated", (u32)kmalloc_sum_eternal);
  663. json.add("user_physical_allocated", MM.user_physical_pages_used());
  664. json.add("user_physical_available", MM.user_physical_pages());
  665. json.add("super_physical_allocated", MM.super_physical_pages_used());
  666. json.add("super_physical_available", MM.super_physical_pages());
  667. json.add("kmalloc_call_count", g_kmalloc_call_count);
  668. json.add("kfree_call_count", g_kfree_call_count);
  669. slab_alloc_stats([&json](size_t slab_size, size_t num_allocated, size_t num_free) {
  670. auto prefix = String::format("slab_%zu", slab_size);
  671. json.add(String::format("%s_num_allocated", prefix.characters()), (u32)num_allocated);
  672. json.add(String::format("%s_num_free", prefix.characters()), (u32)num_free);
  673. });
  674. json.finish();
  675. return builder.build();
  676. }
  677. Optional<KBuffer> procfs$all(InodeIdentifier)
  678. {
  679. InterruptDisabler disabler;
  680. auto processes = Process::all_processes();
  681. KBufferBuilder builder;
  682. JsonArraySerializer array { builder };
  683. // Keep this in sync with CProcessStatistics.
  684. auto build_process = [&](const Process& process) {
  685. auto process_object = array.add_object();
  686. process_object.add("pid", process.pid());
  687. process_object.add("pgid", process.tty() ? process.tty()->pgid() : 0);
  688. process_object.add("pgp", process.pgid());
  689. process_object.add("sid", process.sid());
  690. process_object.add("uid", process.uid());
  691. process_object.add("gid", process.gid());
  692. process_object.add("ppid", process.ppid());
  693. process_object.add("nfds", process.number_of_open_file_descriptors());
  694. process_object.add("name", process.name());
  695. process_object.add("tty", process.tty() ? process.tty()->tty_name() : "notty");
  696. process_object.add("amount_virtual", (u32)process.amount_virtual());
  697. process_object.add("amount_resident", (u32)process.amount_resident());
  698. process_object.add("amount_shared", (u32)process.amount_shared());
  699. process_object.add("amount_purgeable_volatile", (u32)process.amount_purgeable_volatile());
  700. process_object.add("amount_purgeable_nonvolatile", (u32)process.amount_purgeable_nonvolatile());
  701. process_object.add("icon_id", process.icon_id());
  702. auto thread_array = process_object.add_array("threads");
  703. process.for_each_thread([&](const Thread& thread) {
  704. auto thread_object = thread_array.add_object();
  705. thread_object.add("tid", thread.tid());
  706. thread_object.add("name", thread.name());
  707. thread_object.add("times_scheduled", thread.times_scheduled());
  708. thread_object.add("ticks", thread.ticks());
  709. thread_object.add("state", thread.state_string());
  710. thread_object.add("priority", to_string(thread.priority()));
  711. thread_object.add("syscall_count", thread.syscall_count());
  712. thread_object.add("inode_faults", thread.inode_faults());
  713. thread_object.add("zero_faults", thread.zero_faults());
  714. thread_object.add("cow_faults", thread.cow_faults());
  715. thread_object.add("file_read_bytes", thread.file_read_bytes());
  716. thread_object.add("file_write_bytes", thread.file_write_bytes());
  717. thread_object.add("unix_socket_read_bytes", thread.unix_socket_read_bytes());
  718. thread_object.add("unix_socket_write_bytes", thread.unix_socket_write_bytes());
  719. thread_object.add("ipv4_socket_read_bytes", thread.ipv4_socket_read_bytes());
  720. thread_object.add("ipv4_socket_write_bytes", thread.ipv4_socket_write_bytes());
  721. return IterationDecision::Continue;
  722. });
  723. };
  724. build_process(*Scheduler::colonel());
  725. for (auto* process : processes)
  726. build_process(*process);
  727. array.finish();
  728. return builder.build();
  729. }
  730. Optional<KBuffer> procfs$inodes(InodeIdentifier)
  731. {
  732. extern InlineLinkedList<Inode>& all_inodes();
  733. KBufferBuilder builder;
  734. InterruptDisabler disabler;
  735. for (auto& inode : all_inodes()) {
  736. builder.appendf("Inode{K%x} %02u:%08u (%u)\n", &inode, inode.fsid(), inode.index(), inode.ref_count());
  737. }
  738. return builder.build();
  739. }
  740. struct SysVariable {
  741. String name;
  742. enum class Type : u8 {
  743. Invalid,
  744. Boolean,
  745. String,
  746. };
  747. Type type { Type::Invalid };
  748. Function<void()> notify_callback;
  749. void* address { nullptr };
  750. static SysVariable& for_inode(InodeIdentifier);
  751. void notify()
  752. {
  753. if (notify_callback)
  754. notify_callback();
  755. }
  756. };
  757. static Vector<SysVariable, 16>* s_sys_variables;
  758. static inline Vector<SysVariable, 16>& sys_variables()
  759. {
  760. if (s_sys_variables == nullptr) {
  761. s_sys_variables = new Vector<SysVariable, 16>;
  762. s_sys_variables->append({ "", SysVariable::Type::Invalid, nullptr, nullptr });
  763. }
  764. return *s_sys_variables;
  765. }
  766. SysVariable& SysVariable::for_inode(InodeIdentifier id)
  767. {
  768. auto index = to_sys_index(id);
  769. if (index >= sys_variables().size())
  770. return sys_variables()[0];
  771. auto& variable = sys_variables()[index];
  772. ASSERT(variable.address);
  773. return variable;
  774. }
  775. static ByteBuffer read_sys_bool(InodeIdentifier inode_id)
  776. {
  777. auto& variable = SysVariable::for_inode(inode_id);
  778. ASSERT(variable.type == SysVariable::Type::Boolean);
  779. auto buffer = ByteBuffer::create_uninitialized(2);
  780. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  781. {
  782. LOCKER(lockable_bool->lock());
  783. buffer[0] = lockable_bool->resource() ? '1' : '0';
  784. }
  785. buffer[1] = '\n';
  786. return buffer;
  787. }
  788. static ssize_t write_sys_bool(InodeIdentifier inode_id, const ByteBuffer& data)
  789. {
  790. auto& variable = SysVariable::for_inode(inode_id);
  791. ASSERT(variable.type == SysVariable::Type::Boolean);
  792. if (data.is_empty() || !(data[0] == '0' || data[0] == '1'))
  793. return data.size();
  794. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  795. {
  796. LOCKER(lockable_bool->lock());
  797. lockable_bool->resource() = data[0] == '1';
  798. }
  799. variable.notify();
  800. return data.size();
  801. }
  802. static ByteBuffer read_sys_string(InodeIdentifier inode_id)
  803. {
  804. auto& variable = SysVariable::for_inode(inode_id);
  805. ASSERT(variable.type == SysVariable::Type::String);
  806. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  807. LOCKER(lockable_string->lock());
  808. return lockable_string->resource().to_byte_buffer();
  809. }
  810. static ssize_t write_sys_string(InodeIdentifier inode_id, const ByteBuffer& data)
  811. {
  812. auto& variable = SysVariable::for_inode(inode_id);
  813. ASSERT(variable.type == SysVariable::Type::String);
  814. {
  815. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  816. LOCKER(lockable_string->lock());
  817. lockable_string->resource() = String((const char*)data.data(), data.size());
  818. }
  819. variable.notify();
  820. return data.size();
  821. }
  822. void ProcFS::add_sys_bool(String&& name, Lockable<bool>& var, Function<void()>&& notify_callback)
  823. {
  824. InterruptDisabler disabler;
  825. SysVariable variable;
  826. variable.name = move(name);
  827. variable.type = SysVariable::Type::Boolean;
  828. variable.notify_callback = move(notify_callback);
  829. variable.address = &var;
  830. sys_variables().append(move(variable));
  831. }
  832. void ProcFS::add_sys_string(String&& name, Lockable<String>& var, Function<void()>&& notify_callback)
  833. {
  834. InterruptDisabler disabler;
  835. SysVariable variable;
  836. variable.name = move(name);
  837. variable.type = SysVariable::Type::String;
  838. variable.notify_callback = move(notify_callback);
  839. variable.address = &var;
  840. sys_variables().append(move(variable));
  841. }
  842. bool ProcFS::initialize()
  843. {
  844. static Lockable<bool>* kmalloc_stack_helper;
  845. if (kmalloc_stack_helper == nullptr) {
  846. kmalloc_stack_helper = new Lockable<bool>();
  847. kmalloc_stack_helper->resource() = g_dump_kmalloc_stacks;
  848. ProcFS::add_sys_bool("kmalloc_stacks", *kmalloc_stack_helper, [] {
  849. g_dump_kmalloc_stacks = kmalloc_stack_helper->resource();
  850. });
  851. }
  852. return true;
  853. }
  854. const char* ProcFS::class_name() const
  855. {
  856. return "ProcFS";
  857. }
  858. RefPtr<Inode> ProcFS::create_inode(InodeIdentifier, const String&, mode_t, off_t, dev_t, int&)
  859. {
  860. kprintf("FIXME: Implement ProcFS::create_inode()?\n");
  861. return {};
  862. }
  863. RefPtr<Inode> ProcFS::create_directory(InodeIdentifier, const String&, mode_t, int& error)
  864. {
  865. error = -EROFS;
  866. return nullptr;
  867. }
  868. InodeIdentifier ProcFS::root_inode() const
  869. {
  870. return { fsid(), FI_Root };
  871. }
  872. RefPtr<Inode> ProcFS::get_inode(InodeIdentifier inode_id) const
  873. {
  874. #ifdef PROCFS_DEBUG
  875. dbgprintf("ProcFS::get_inode(%u)\n", inode_id.index());
  876. #endif
  877. if (inode_id == root_inode())
  878. return m_root_inode;
  879. LOCKER(m_inodes_lock);
  880. auto it = m_inodes.find(inode_id.index());
  881. if (it == m_inodes.end()) {
  882. auto inode = adopt(*new ProcFSInode(const_cast<ProcFS&>(*this), inode_id.index()));
  883. m_inodes.set(inode_id.index(), inode.ptr());
  884. return inode;
  885. }
  886. return (*it).value;
  887. }
  888. ProcFSInode::ProcFSInode(ProcFS& fs, unsigned index)
  889. : Inode(fs, index)
  890. {
  891. }
  892. ProcFSInode::~ProcFSInode()
  893. {
  894. LOCKER(fs().m_inodes_lock);
  895. fs().m_inodes.remove(index());
  896. }
  897. InodeMetadata ProcFSInode::metadata() const
  898. {
  899. #ifdef PROCFS_DEBUG
  900. dbgprintf("ProcFSInode::metadata(%u)\n", index());
  901. #endif
  902. InodeMetadata metadata;
  903. metadata.inode = identifier();
  904. metadata.ctime = mepoch;
  905. metadata.atime = mepoch;
  906. metadata.mtime = mepoch;
  907. auto proc_parent_directory = to_proc_parent_directory(identifier());
  908. auto pid = to_pid(identifier());
  909. auto proc_file_type = to_proc_file_type(identifier());
  910. #ifdef PROCFS_DEBUG
  911. dbgprintf(" -> pid: %d, fi: %u, pdi: %u\n", pid, proc_file_type, proc_parent_directory);
  912. #endif
  913. if (is_process_related_file(identifier())) {
  914. auto handle = ProcessInspectionHandle::from_pid(pid);
  915. metadata.uid = handle->process().sys$getuid();
  916. metadata.gid = handle->process().sys$getgid();
  917. }
  918. if (proc_parent_directory == PDI_PID_fd) {
  919. metadata.mode = 00120777;
  920. return metadata;
  921. }
  922. switch (proc_file_type) {
  923. case FI_Root_self:
  924. case FI_PID_cwd:
  925. case FI_PID_exe:
  926. metadata.mode = 0120777;
  927. break;
  928. case FI_Root:
  929. case FI_Root_sys:
  930. case FI_Root_net:
  931. case FI_PID:
  932. case FI_PID_fd:
  933. metadata.mode = 040777;
  934. break;
  935. default:
  936. metadata.mode = 0100644;
  937. break;
  938. }
  939. #ifdef PROCFS_DEBUG
  940. dbgprintf("Returning mode %o\n", metadata.mode);
  941. #endif
  942. return metadata;
  943. }
  944. ssize_t ProcFSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription* description) const
  945. {
  946. #ifdef PROCFS_DEBUG
  947. dbgprintf("ProcFS: read_bytes %u\n", index());
  948. #endif
  949. ASSERT(offset >= 0);
  950. ASSERT(buffer);
  951. auto* directory_entry = fs().get_directory_entry(identifier());
  952. Function<Optional<KBuffer>(InodeIdentifier)> callback_tmp;
  953. Function<Optional<KBuffer>(InodeIdentifier)>* read_callback { nullptr };
  954. if (directory_entry)
  955. read_callback = &directory_entry->read_callback;
  956. else
  957. switch (to_proc_parent_directory(identifier())) {
  958. case PDI_PID_fd:
  959. callback_tmp = procfs$pid_fd_entry;
  960. read_callback = &callback_tmp;
  961. break;
  962. case PDI_Root_sys:
  963. switch (SysVariable::for_inode(identifier()).type) {
  964. case SysVariable::Type::Invalid:
  965. ASSERT_NOT_REACHED();
  966. case SysVariable::Type::Boolean:
  967. callback_tmp = read_sys_bool;
  968. break;
  969. case SysVariable::Type::String:
  970. callback_tmp = read_sys_string;
  971. break;
  972. }
  973. read_callback = &callback_tmp;
  974. break;
  975. default:
  976. ASSERT_NOT_REACHED();
  977. }
  978. ASSERT(read_callback);
  979. Optional<KBuffer> generated_data;
  980. if (!description) {
  981. generated_data = (*read_callback)(identifier());
  982. } else {
  983. if (!description->generator_cache())
  984. description->generator_cache() = (*read_callback)(identifier());
  985. generated_data = description->generator_cache();
  986. }
  987. auto& data = generated_data;
  988. ssize_t nread = 0;
  989. if (data.has_value()) {
  990. nread = min(static_cast<off_t>(data.value().size() - offset), static_cast<off_t>(count));
  991. memcpy(buffer, data.value().data() + offset, nread);
  992. if (nread == 0 && description && description->generator_cache())
  993. description->generator_cache().clear();
  994. }
  995. return nread;
  996. }
  997. InodeIdentifier ProcFS::ProcFSDirectoryEntry::identifier(unsigned fsid) const
  998. {
  999. return to_identifier(fsid, PDI_Root, 0, (ProcFileType)proc_file_type);
  1000. }
  1001. bool ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  1002. {
  1003. #ifdef PROCFS_DEBUG
  1004. dbgprintf("ProcFS: traverse_as_directory %u\n", index());
  1005. #endif
  1006. if (!::is_directory(identifier()))
  1007. return false;
  1008. auto pid = to_pid(identifier());
  1009. auto proc_file_type = to_proc_file_type(identifier());
  1010. auto parent_id = to_parent_id(identifier());
  1011. callback({ ".", 1, identifier(), 2 });
  1012. callback({ "..", 2, parent_id, 2 });
  1013. switch (proc_file_type) {
  1014. case FI_Root:
  1015. for (auto& entry : fs().m_entries) {
  1016. // FIXME: strlen() here is sad.
  1017. if (!entry.name)
  1018. continue;
  1019. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End)
  1020. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type), 0 });
  1021. }
  1022. for (auto pid_child : Process::all_pids()) {
  1023. char name[16];
  1024. size_t name_length = (size_t)sprintf(name, "%u", pid_child);
  1025. callback({ name, name_length, to_identifier(fsid(), PDI_Root, pid_child, FI_PID), 0 });
  1026. }
  1027. break;
  1028. case FI_Root_sys:
  1029. for (int i = 1; i < sys_variables().size(); ++i) {
  1030. auto& variable = sys_variables()[i];
  1031. callback({ variable.name.characters(), variable.name.length(), sys_var_to_identifier(fsid(), i), 0 });
  1032. }
  1033. break;
  1034. case FI_Root_net:
  1035. callback({ "adapters", 8, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_adapters), 0 });
  1036. callback({ "arp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_arp), 0 });
  1037. callback({ "tcp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_tcp), 0 });
  1038. callback({ "udp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_udp), 0 });
  1039. callback({ "local", 5, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_local), 0 });
  1040. break;
  1041. case FI_PID: {
  1042. auto handle = ProcessInspectionHandle::from_pid(pid);
  1043. if (!handle)
  1044. return false;
  1045. auto& process = handle->process();
  1046. for (auto& entry : fs().m_entries) {
  1047. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1048. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  1049. continue;
  1050. // FIXME: strlen() here is sad.
  1051. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_PID, pid, (ProcFileType)entry.proc_file_type), 0 });
  1052. }
  1053. }
  1054. } break;
  1055. case FI_PID_fd: {
  1056. auto handle = ProcessInspectionHandle::from_pid(pid);
  1057. if (!handle)
  1058. return false;
  1059. auto& process = handle->process();
  1060. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  1061. auto* description = process.file_description(i);
  1062. if (!description)
  1063. continue;
  1064. char name[16];
  1065. size_t name_length = (size_t)sprintf(name, "%u", i);
  1066. callback({ name, name_length, to_identifier_with_fd(fsid(), pid, i), 0 });
  1067. }
  1068. } break;
  1069. default:
  1070. return true;
  1071. }
  1072. return true;
  1073. }
  1074. InodeIdentifier ProcFSInode::lookup(StringView name)
  1075. {
  1076. ASSERT(is_directory());
  1077. if (name == ".")
  1078. return identifier();
  1079. if (name == "..")
  1080. return to_parent_id(identifier());
  1081. auto proc_file_type = to_proc_file_type(identifier());
  1082. if (proc_file_type == FI_Root) {
  1083. for (auto& entry : fs().m_entries) {
  1084. if (entry.name == nullptr)
  1085. continue;
  1086. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End) {
  1087. if (name == entry.name) {
  1088. return to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type);
  1089. }
  1090. }
  1091. }
  1092. bool ok;
  1093. unsigned name_as_number = name.to_uint(ok);
  1094. if (ok) {
  1095. bool process_exists = false;
  1096. {
  1097. InterruptDisabler disabler;
  1098. process_exists = Process::from_pid(name_as_number);
  1099. }
  1100. if (process_exists)
  1101. return to_identifier(fsid(), PDI_Root, name_as_number, FI_PID);
  1102. }
  1103. return {};
  1104. }
  1105. if (proc_file_type == FI_Root_sys) {
  1106. for (int i = 1; i < sys_variables().size(); ++i) {
  1107. auto& variable = sys_variables()[i];
  1108. if (name == variable.name)
  1109. return sys_var_to_identifier(fsid(), i);
  1110. }
  1111. return {};
  1112. }
  1113. if (proc_file_type == FI_Root_net) {
  1114. if (name == "adapters")
  1115. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_adapters);
  1116. if (name == "arp")
  1117. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_arp);
  1118. if (name == "tcp")
  1119. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_tcp);
  1120. if (name == "udp")
  1121. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_udp);
  1122. if (name == "local")
  1123. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_local);
  1124. return {};
  1125. }
  1126. if (proc_file_type == FI_PID) {
  1127. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier()));
  1128. if (!handle)
  1129. return {};
  1130. auto& process = handle->process();
  1131. for (auto& entry : fs().m_entries) {
  1132. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1133. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  1134. continue;
  1135. if (entry.name == nullptr)
  1136. continue;
  1137. if (name == entry.name) {
  1138. return to_identifier(fsid(), PDI_PID, to_pid(identifier()), (ProcFileType)entry.proc_file_type);
  1139. }
  1140. }
  1141. }
  1142. return {};
  1143. }
  1144. if (proc_file_type == FI_PID_fd) {
  1145. bool ok;
  1146. unsigned name_as_number = name.to_uint(ok);
  1147. if (ok) {
  1148. bool fd_exists = false;
  1149. {
  1150. InterruptDisabler disabler;
  1151. if (auto* process = Process::from_pid(to_pid(identifier())))
  1152. fd_exists = process->file_description(name_as_number);
  1153. }
  1154. if (fd_exists)
  1155. return to_identifier_with_fd(fsid(), to_pid(identifier()), name_as_number);
  1156. }
  1157. }
  1158. return {};
  1159. }
  1160. void ProcFSInode::flush_metadata()
  1161. {
  1162. }
  1163. ssize_t ProcFSInode::write_bytes(off_t offset, ssize_t size, const u8* buffer, FileDescription*)
  1164. {
  1165. auto* directory_entry = fs().get_directory_entry(identifier());
  1166. Function<ssize_t(InodeIdentifier, const ByteBuffer&)> callback_tmp;
  1167. Function<ssize_t(InodeIdentifier, const ByteBuffer&)>* write_callback { nullptr };
  1168. if (directory_entry == nullptr) {
  1169. if (to_proc_parent_directory(identifier()) == PDI_Root_sys) {
  1170. switch (SysVariable::for_inode(identifier()).type) {
  1171. case SysVariable::Type::Invalid:
  1172. ASSERT_NOT_REACHED();
  1173. case SysVariable::Type::Boolean:
  1174. callback_tmp = write_sys_bool;
  1175. break;
  1176. case SysVariable::Type::String:
  1177. callback_tmp = write_sys_string;
  1178. break;
  1179. }
  1180. write_callback = &callback_tmp;
  1181. } else
  1182. return -EPERM;
  1183. } else {
  1184. if (!directory_entry->write_callback)
  1185. return -EPERM;
  1186. write_callback = &directory_entry->write_callback;
  1187. }
  1188. ASSERT(is_persistent_inode(identifier()));
  1189. // FIXME: Being able to write into ProcFS at a non-zero offset seems like something we should maybe support..
  1190. ASSERT(offset == 0);
  1191. bool success = (*write_callback)(identifier(), ByteBuffer::wrap(buffer, size));
  1192. ASSERT(success);
  1193. return 0;
  1194. }
  1195. KResult ProcFSInode::add_child(InodeIdentifier child_id, const StringView& name, mode_t)
  1196. {
  1197. (void)child_id;
  1198. (void)name;
  1199. return KResult(-EPERM);
  1200. }
  1201. KResult ProcFSInode::remove_child(const StringView& name)
  1202. {
  1203. (void)name;
  1204. return KResult(-EPERM);
  1205. }
  1206. size_t ProcFSInode::directory_entry_count() const
  1207. {
  1208. ASSERT(is_directory());
  1209. size_t count = 0;
  1210. traverse_as_directory([&count](const FS::DirectoryEntry&) {
  1211. ++count;
  1212. return true;
  1213. });
  1214. return count;
  1215. }
  1216. KResult ProcFSInode::chmod(mode_t)
  1217. {
  1218. return KResult(-EPERM);
  1219. }
  1220. ProcFS::ProcFS()
  1221. {
  1222. m_root_inode = adopt(*new ProcFSInode(*this, 1));
  1223. m_entries.resize(FI_MaxStaticFileIndex);
  1224. m_entries[FI_Root_mm] = { "mm", FI_Root_mm, procfs$mm };
  1225. m_entries[FI_Root_mounts] = { "mounts", FI_Root_mounts, procfs$mounts };
  1226. m_entries[FI_Root_df] = { "df", FI_Root_df, procfs$df };
  1227. m_entries[FI_Root_all] = { "all", FI_Root_all, procfs$all };
  1228. m_entries[FI_Root_memstat] = { "memstat", FI_Root_memstat, procfs$memstat };
  1229. m_entries[FI_Root_cpuinfo] = { "cpuinfo", FI_Root_cpuinfo, procfs$cpuinfo };
  1230. m_entries[FI_Root_inodes] = { "inodes", FI_Root_inodes, procfs$inodes };
  1231. m_entries[FI_Root_dmesg] = { "dmesg", FI_Root_dmesg, procfs$dmesg };
  1232. m_entries[FI_Root_self] = { "self", FI_Root_self, procfs$self };
  1233. m_entries[FI_Root_pci] = { "pci", FI_Root_pci, procfs$pci };
  1234. m_entries[FI_Root_devices] = { "devices", FI_Root_devices, procfs$devices };
  1235. m_entries[FI_Root_uptime] = { "uptime", FI_Root_uptime, procfs$uptime };
  1236. m_entries[FI_Root_cmdline] = { "cmdline", FI_Root_cmdline, procfs$cmdline };
  1237. m_entries[FI_Root_modules] = { "modules", FI_Root_modules, procfs$modules };
  1238. m_entries[FI_Root_profile] = { "profile", FI_Root_profile, procfs$profile };
  1239. m_entries[FI_Root_sys] = { "sys", FI_Root_sys };
  1240. m_entries[FI_Root_net] = { "net", FI_Root_net };
  1241. m_entries[FI_Root_net_adapters] = { "adapters", FI_Root_net_adapters, procfs$net_adapters };
  1242. m_entries[FI_Root_net_arp] = { "arp", FI_Root_net_arp, procfs$net_arp };
  1243. m_entries[FI_Root_net_tcp] = { "tcp", FI_Root_net_tcp, procfs$net_tcp };
  1244. m_entries[FI_Root_net_udp] = { "udp", FI_Root_net_udp, procfs$net_udp };
  1245. m_entries[FI_Root_net_local] = { "local", FI_Root_net_local, procfs$net_local };
  1246. m_entries[FI_PID_vm] = { "vm", FI_PID_vm, procfs$pid_vm };
  1247. m_entries[FI_PID_vmobjects] = { "vmobjects", FI_PID_vmobjects, procfs$pid_vmobjects };
  1248. m_entries[FI_PID_stack] = { "stack", FI_PID_stack, procfs$pid_stack };
  1249. m_entries[FI_PID_regs] = { "regs", FI_PID_regs, procfs$pid_regs };
  1250. m_entries[FI_PID_fds] = { "fds", FI_PID_fds, procfs$pid_fds };
  1251. m_entries[FI_PID_exe] = { "exe", FI_PID_exe, procfs$pid_exe };
  1252. m_entries[FI_PID_cwd] = { "cwd", FI_PID_cwd, procfs$pid_cwd };
  1253. m_entries[FI_PID_fd] = { "fd", FI_PID_fd };
  1254. }
  1255. ProcFS::ProcFSDirectoryEntry* ProcFS::get_directory_entry(InodeIdentifier identifier) const
  1256. {
  1257. auto proc_file_type = to_proc_file_type(identifier);
  1258. if (proc_file_type != FI_Invalid && proc_file_type != FI_Root_sys_variable && proc_file_type < FI_MaxStaticFileIndex)
  1259. return const_cast<ProcFSDirectoryEntry*>(&m_entries[proc_file_type]);
  1260. return nullptr;
  1261. }
  1262. KResult ProcFSInode::chown(uid_t, gid_t)
  1263. {
  1264. return KResult(-EPERM);
  1265. }