ProcFS.cpp 47 KB

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