ProcFS.cpp 48 KB

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