ProcFS.cpp 46 KB

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