ProcFS.cpp 49 KB

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