ProcFS.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/JsonArraySerializer.h>
  27. #include <AK/JsonObject.h>
  28. #include <AK/JsonObjectSerializer.h>
  29. #include <AK/JsonValue.h>
  30. #include <Kernel/Arch/i386/CPU.h>
  31. #include <Kernel/Arch/i386/ProcessorInfo.h>
  32. #include <Kernel/CommandLine.h>
  33. #include <Kernel/Console.h>
  34. #include <Kernel/Devices/BlockDevice.h>
  35. #include <Kernel/Devices/KeyboardDevice.h>
  36. #include <Kernel/FileSystem/Custody.h>
  37. #include <Kernel/FileSystem/FileBackedFileSystem.h>
  38. #include <Kernel/FileSystem/FileDescription.h>
  39. #include <Kernel/FileSystem/ProcFS.h>
  40. #include <Kernel/FileSystem/VirtualFileSystem.h>
  41. #include <Kernel/Heap/kmalloc.h>
  42. #include <Kernel/Interrupts/GenericInterruptHandler.h>
  43. #include <Kernel/Interrupts/InterruptManagement.h>
  44. #include <Kernel/KBufferBuilder.h>
  45. #include <Kernel/KSyms.h>
  46. #include <Kernel/Module.h>
  47. #include <Kernel/Net/LocalSocket.h>
  48. #include <Kernel/Net/NetworkAdapter.h>
  49. #include <Kernel/Net/Routing.h>
  50. #include <Kernel/Net/TCPSocket.h>
  51. #include <Kernel/Net/UDPSocket.h>
  52. #include <Kernel/PCI/Access.h>
  53. #include <Kernel/Process.h>
  54. #include <Kernel/Profiling.h>
  55. #include <Kernel/Scheduler.h>
  56. #include <Kernel/StdLib.h>
  57. #include <Kernel/TTY/TTY.h>
  58. #include <Kernel/VM/MemoryManager.h>
  59. #include <Kernel/VM/PurgeableVMObject.h>
  60. #include <LibC/errno_numbers.h>
  61. namespace Kernel {
  62. enum ProcParentDirectory {
  63. PDI_AbstractRoot = 0,
  64. PDI_Root,
  65. PDI_Root_sys,
  66. PDI_Root_net,
  67. PDI_PID,
  68. PDI_PID_fd,
  69. };
  70. enum ProcFileType {
  71. FI_Invalid = 0,
  72. FI_Root = 1, // directory
  73. __FI_Root_Start,
  74. FI_Root_mm,
  75. FI_Root_mounts,
  76. FI_Root_df,
  77. FI_Root_all,
  78. FI_Root_memstat,
  79. FI_Root_cpuinfo,
  80. FI_Root_inodes,
  81. FI_Root_dmesg,
  82. FI_Root_interrupts,
  83. FI_Root_keymap,
  84. FI_Root_pci,
  85. FI_Root_devices,
  86. FI_Root_uptime,
  87. FI_Root_cmdline,
  88. FI_Root_modules,
  89. FI_Root_profile,
  90. FI_Root_self, // symlink
  91. FI_Root_sys, // directory
  92. FI_Root_net, // directory
  93. __FI_Root_End,
  94. FI_Root_sys_variable,
  95. FI_Root_net_adapters,
  96. FI_Root_net_arp,
  97. FI_Root_net_tcp,
  98. FI_Root_net_udp,
  99. FI_Root_net_local,
  100. FI_PID,
  101. __FI_PID_Start,
  102. FI_PID_vm,
  103. FI_PID_vmobjects,
  104. FI_PID_stack,
  105. FI_PID_fds,
  106. FI_PID_unveil,
  107. FI_PID_exe, // symlink
  108. FI_PID_cwd, // symlink
  109. FI_PID_root, // symlink
  110. FI_PID_fd, // directory
  111. __FI_PID_End,
  112. FI_MaxStaticFileIndex,
  113. };
  114. static inline ProcessID to_pid(const InodeIdentifier& identifier)
  115. {
  116. #ifdef PROCFS_DEBUG
  117. dbg() << "to_pid, index=" << String::format("%08x", identifier.index()) << " -> " << (identifier.index() >> 16);
  118. #endif
  119. return identifier.index() >> 16u;
  120. }
  121. static inline ProcParentDirectory to_proc_parent_directory(const InodeIdentifier& identifier)
  122. {
  123. return (ProcParentDirectory)((identifier.index() >> 12) & 0xf);
  124. }
  125. static inline ProcFileType to_proc_file_type(const InodeIdentifier& identifier)
  126. {
  127. return (ProcFileType)(identifier.index() & 0xff);
  128. }
  129. static inline int to_fd(const InodeIdentifier& identifier)
  130. {
  131. ASSERT(to_proc_parent_directory(identifier) == PDI_PID_fd);
  132. return (identifier.index() & 0xff) - FI_MaxStaticFileIndex;
  133. }
  134. static inline size_t to_sys_index(const InodeIdentifier& identifier)
  135. {
  136. ASSERT(to_proc_parent_directory(identifier) == PDI_Root_sys);
  137. ASSERT(to_proc_file_type(identifier) == FI_Root_sys_variable);
  138. return identifier.index() >> 16u;
  139. }
  140. static inline InodeIdentifier to_identifier(unsigned fsid, ProcParentDirectory parent, ProcessID pid, ProcFileType proc_file_type)
  141. {
  142. return { fsid, ((unsigned)parent << 12u) | ((unsigned)pid.value() << 16u) | (unsigned)proc_file_type };
  143. }
  144. static inline InodeIdentifier to_identifier_with_fd(unsigned fsid, ProcessID pid, int fd)
  145. {
  146. return { fsid, (PDI_PID_fd << 12u) | ((unsigned)pid.value() << 16u) | (FI_MaxStaticFileIndex + fd) };
  147. }
  148. static inline InodeIdentifier sys_var_to_identifier(unsigned fsid, unsigned index)
  149. {
  150. ASSERT(index < 256);
  151. return { fsid, (PDI_Root_sys << 12u) | (index << 16u) | FI_Root_sys_variable };
  152. }
  153. static inline InodeIdentifier to_parent_id(const InodeIdentifier& identifier)
  154. {
  155. switch (to_proc_parent_directory(identifier)) {
  156. case PDI_AbstractRoot:
  157. case PDI_Root:
  158. return { identifier.fsid(), FI_Root };
  159. case PDI_Root_sys:
  160. return { identifier.fsid(), FI_Root_sys };
  161. case PDI_Root_net:
  162. return { identifier.fsid(), FI_Root_net };
  163. case PDI_PID:
  164. return to_identifier(identifier.fsid(), PDI_Root, to_pid(identifier), FI_PID);
  165. case PDI_PID_fd:
  166. return to_identifier(identifier.fsid(), PDI_PID, to_pid(identifier), FI_PID_fd);
  167. }
  168. ASSERT_NOT_REACHED();
  169. }
  170. #if 0
  171. static inline u8 to_unused_metadata(const InodeIdentifier& identifier)
  172. {
  173. return (identifier.index() >> 8) & 0xf;
  174. }
  175. #endif
  176. static inline bool is_process_related_file(const InodeIdentifier& identifier)
  177. {
  178. if (to_proc_file_type(identifier) == FI_PID)
  179. return true;
  180. auto proc_parent_directory = to_proc_parent_directory(identifier);
  181. switch (proc_parent_directory) {
  182. case PDI_PID:
  183. case PDI_PID_fd:
  184. return true;
  185. default:
  186. return false;
  187. }
  188. }
  189. static inline bool is_directory(const InodeIdentifier& identifier)
  190. {
  191. auto proc_file_type = to_proc_file_type(identifier);
  192. switch (proc_file_type) {
  193. case FI_Root:
  194. case FI_Root_sys:
  195. case FI_Root_net:
  196. case FI_PID:
  197. case FI_PID_fd:
  198. return true;
  199. default:
  200. return false;
  201. }
  202. }
  203. static inline bool is_persistent_inode(const InodeIdentifier& identifier)
  204. {
  205. return to_proc_parent_directory(identifier) == PDI_Root_sys;
  206. }
  207. NonnullRefPtr<ProcFS> ProcFS::create()
  208. {
  209. return adopt(*new ProcFS);
  210. }
  211. ProcFS::~ProcFS()
  212. {
  213. }
  214. Optional<KBuffer> procfs$pid_fds(InodeIdentifier identifier)
  215. {
  216. KBufferBuilder builder;
  217. JsonArraySerializer array { builder };
  218. auto process = Process::from_pid(to_pid(identifier));
  219. if (!process) {
  220. array.finish();
  221. return builder.build();
  222. }
  223. if (process->number_of_open_file_descriptors() == 0) {
  224. array.finish();
  225. return builder.build();
  226. }
  227. for (int i = 0; i < process->max_open_file_descriptors(); ++i) {
  228. auto description = process->file_description(i);
  229. if (!description)
  230. continue;
  231. bool cloexec = process->fd_flags(i) & FD_CLOEXEC;
  232. auto description_object = array.add_object();
  233. description_object.add("fd", i);
  234. description_object.add("absolute_path", description->absolute_path());
  235. description_object.add("seekable", description->file().is_seekable());
  236. description_object.add("class", description->file().class_name());
  237. description_object.add("offset", description->offset());
  238. description_object.add("cloexec", cloexec);
  239. description_object.add("blocking", description->is_blocking());
  240. description_object.add("can_read", description->can_read());
  241. description_object.add("can_write", description->can_write());
  242. }
  243. array.finish();
  244. return builder.build();
  245. }
  246. Optional<KBuffer> procfs$pid_fd_entry(InodeIdentifier identifier)
  247. {
  248. auto process = Process::from_pid(to_pid(identifier));
  249. if (!process)
  250. return {};
  251. int fd = to_fd(identifier);
  252. auto description = process->file_description(fd);
  253. if (!description)
  254. return {};
  255. return description->absolute_path().to_byte_buffer();
  256. }
  257. Optional<KBuffer> procfs$pid_vm(InodeIdentifier identifier)
  258. {
  259. auto process = Process::from_pid(to_pid(identifier));
  260. if (!process)
  261. return {};
  262. KBufferBuilder builder;
  263. JsonArraySerializer array { builder };
  264. {
  265. ScopedSpinLock lock(process->get_lock());
  266. for (auto& region : process->regions()) {
  267. if (!region.is_user_accessible() && !Process::current()->is_superuser())
  268. continue;
  269. auto region_object = array.add_object();
  270. region_object.add("readable", region.is_readable());
  271. region_object.add("writable", region.is_writable());
  272. region_object.add("executable", region.is_executable());
  273. region_object.add("stack", region.is_stack());
  274. region_object.add("shared", region.is_shared());
  275. region_object.add("user_accessible", region.is_user_accessible());
  276. region_object.add("purgeable", region.vmobject().is_purgeable());
  277. if (region.vmobject().is_purgeable()) {
  278. region_object.add("volatile", static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile());
  279. }
  280. region_object.add("purgeable", region.vmobject().is_purgeable());
  281. region_object.add("address", region.vaddr().get());
  282. region_object.add("size", region.size());
  283. region_object.add("amount_resident", region.amount_resident());
  284. region_object.add("amount_dirty", region.amount_dirty());
  285. region_object.add("cow_pages", region.cow_pages());
  286. region_object.add("name", region.name());
  287. region_object.add("vmobject", region.vmobject().class_name());
  288. StringBuilder pagemap_builder;
  289. for (size_t i = 0; i < region.page_count(); ++i) {
  290. auto* page = region.physical_page(i);
  291. if (!page)
  292. pagemap_builder.append('N');
  293. else if (page->is_shared_zero_page())
  294. pagemap_builder.append('Z');
  295. else
  296. pagemap_builder.append('P');
  297. }
  298. region_object.add("pagemap", pagemap_builder.to_string());
  299. }
  300. }
  301. array.finish();
  302. return builder.build();
  303. }
  304. Optional<KBuffer> procfs$pci(InodeIdentifier)
  305. {
  306. KBufferBuilder builder;
  307. JsonArraySerializer array { builder };
  308. PCI::enumerate([&array](PCI::Address address, PCI::ID id) {
  309. auto obj = array.add_object();
  310. obj.add("seg", address.seg());
  311. obj.add("bus", address.bus());
  312. obj.add("slot", address.slot());
  313. obj.add("function", address.function());
  314. obj.add("vendor_id", id.vendor_id);
  315. obj.add("device_id", id.device_id);
  316. obj.add("revision_id", PCI::get_revision_id(address));
  317. obj.add("subclass", PCI::get_subclass(address));
  318. obj.add("class", PCI::get_class(address));
  319. obj.add("subsystem_id", PCI::get_subsystem_id(address));
  320. obj.add("subsystem_vendor_id", PCI::get_subsystem_vendor_id(address));
  321. });
  322. array.finish();
  323. return builder.build();
  324. }
  325. Optional<KBuffer> procfs$interrupts(InodeIdentifier)
  326. {
  327. KBufferBuilder builder;
  328. JsonArraySerializer array { builder };
  329. InterruptManagement::the().enumerate_interrupt_handlers([&array](GenericInterruptHandler& handler) {
  330. auto obj = array.add_object();
  331. obj.add("purpose", handler.purpose());
  332. obj.add("interrupt_line", handler.interrupt_number());
  333. obj.add("controller", handler.controller());
  334. obj.add("cpu_handler", 0); // FIXME: Determine the responsible CPU for each interrupt handler.
  335. obj.add("device_sharing", (unsigned)handler.sharing_devices_count());
  336. obj.add("call_count", (unsigned)handler.get_invoking_count());
  337. });
  338. array.finish();
  339. return builder.build();
  340. }
  341. Optional<KBuffer> procfs$keymap(InodeIdentifier)
  342. {
  343. KBufferBuilder builder;
  344. JsonObjectSerializer<KBufferBuilder> json { builder };
  345. json.add("keymap", KeyboardDevice::the().keymap_name());
  346. json.finish();
  347. return builder.build();
  348. }
  349. Optional<KBuffer> procfs$devices(InodeIdentifier)
  350. {
  351. KBufferBuilder builder;
  352. JsonArraySerializer array { builder };
  353. Device::for_each([&array](auto& device) {
  354. auto obj = array.add_object();
  355. obj.add("major", device.major());
  356. obj.add("minor", device.minor());
  357. obj.add("class_name", device.class_name());
  358. if (device.is_block_device())
  359. obj.add("type", "block");
  360. else if (device.is_character_device())
  361. obj.add("type", "character");
  362. else
  363. ASSERT_NOT_REACHED();
  364. });
  365. array.finish();
  366. return builder.build();
  367. }
  368. Optional<KBuffer> procfs$uptime(InodeIdentifier)
  369. {
  370. KBufferBuilder builder;
  371. builder.appendf("%u\n", (g_uptime / 1000));
  372. return builder.build();
  373. }
  374. Optional<KBuffer> procfs$cmdline(InodeIdentifier)
  375. {
  376. KBufferBuilder builder;
  377. builder.append(kernel_command_line().string());
  378. builder.append('\n');
  379. return builder.build();
  380. }
  381. Optional<KBuffer> procfs$modules(InodeIdentifier)
  382. {
  383. extern HashMap<String, OwnPtr<Module>>* g_modules;
  384. KBufferBuilder builder;
  385. JsonArraySerializer array { builder };
  386. for (auto& it : *g_modules) {
  387. auto obj = array.add_object();
  388. obj.add("name", it.value->name);
  389. obj.add("module_init", it.value->module_init);
  390. obj.add("module_fini", it.value->module_fini);
  391. u32 size = 0;
  392. for (auto& section : it.value->sections) {
  393. size += section.capacity();
  394. }
  395. obj.add("size", size);
  396. }
  397. array.finish();
  398. return builder.build();
  399. }
  400. Optional<KBuffer> procfs$profile(InodeIdentifier)
  401. {
  402. InterruptDisabler disabler;
  403. KBufferBuilder builder;
  404. JsonObjectSerializer object(builder);
  405. object.add("pid", Profiling::pid().value());
  406. object.add("executable", Profiling::executable_path());
  407. auto array = object.add_array("events");
  408. bool mask_kernel_addresses = !Process::current()->is_superuser();
  409. Profiling::for_each_sample([&](auto& sample) {
  410. auto object = array.add_object();
  411. object.add("type", "sample");
  412. object.add("tid", sample.tid.value());
  413. object.add("timestamp", sample.timestamp);
  414. auto frames_array = object.add_array("stack");
  415. for (size_t i = 0; i < Profiling::max_stack_frame_count; ++i) {
  416. if (sample.frames[i] == 0)
  417. break;
  418. u32 address = (u32)sample.frames[i];
  419. if (mask_kernel_addresses && !is_user_address(VirtualAddress(address)))
  420. address = 0xdeadc0de;
  421. frames_array.add(address);
  422. }
  423. frames_array.finish();
  424. });
  425. array.finish();
  426. object.finish();
  427. return builder.build();
  428. }
  429. Optional<KBuffer> procfs$net_adapters(InodeIdentifier)
  430. {
  431. KBufferBuilder builder;
  432. JsonArraySerializer array { builder };
  433. NetworkAdapter::for_each([&array](auto& adapter) {
  434. auto obj = array.add_object();
  435. obj.add("name", adapter.name());
  436. obj.add("class_name", adapter.class_name());
  437. obj.add("mac_address", adapter.mac_address().to_string());
  438. if (!adapter.ipv4_address().is_zero()) {
  439. obj.add("ipv4_address", adapter.ipv4_address().to_string());
  440. obj.add("ipv4_netmask", adapter.ipv4_netmask().to_string());
  441. }
  442. if (!adapter.ipv4_gateway().is_zero())
  443. obj.add("ipv4_gateway", adapter.ipv4_gateway().to_string());
  444. obj.add("packets_in", adapter.packets_in());
  445. obj.add("bytes_in", adapter.bytes_in());
  446. obj.add("packets_out", adapter.packets_out());
  447. obj.add("bytes_out", adapter.bytes_out());
  448. obj.add("link_up", adapter.link_up());
  449. obj.add("mtu", adapter.mtu());
  450. });
  451. array.finish();
  452. return builder.build();
  453. }
  454. Optional<KBuffer> procfs$net_arp(InodeIdentifier)
  455. {
  456. KBufferBuilder builder;
  457. JsonArraySerializer array { builder };
  458. LOCKER(arp_table().lock(), Lock::Mode::Shared);
  459. for (auto& it : arp_table().resource()) {
  460. auto obj = array.add_object();
  461. obj.add("mac_address", it.value.to_string());
  462. obj.add("ip_address", it.key.to_string());
  463. }
  464. array.finish();
  465. return builder.build();
  466. }
  467. Optional<KBuffer> procfs$net_tcp(InodeIdentifier)
  468. {
  469. KBufferBuilder builder;
  470. JsonArraySerializer array { builder };
  471. TCPSocket::for_each([&array](auto& socket) {
  472. auto obj = array.add_object();
  473. obj.add("local_address", socket.local_address().to_string());
  474. obj.add("local_port", socket.local_port());
  475. obj.add("peer_address", socket.peer_address().to_string());
  476. obj.add("peer_port", socket.peer_port());
  477. obj.add("state", TCPSocket::to_string(socket.state()));
  478. obj.add("ack_number", socket.ack_number());
  479. obj.add("sequence_number", socket.sequence_number());
  480. obj.add("packets_in", socket.packets_in());
  481. obj.add("bytes_in", socket.bytes_in());
  482. obj.add("packets_out", socket.packets_out());
  483. obj.add("bytes_out", socket.bytes_out());
  484. });
  485. array.finish();
  486. return builder.build();
  487. }
  488. Optional<KBuffer> procfs$net_udp(InodeIdentifier)
  489. {
  490. KBufferBuilder builder;
  491. JsonArraySerializer array { builder };
  492. UDPSocket::for_each([&array](auto& socket) {
  493. auto obj = array.add_object();
  494. obj.add("local_address", socket.local_address().to_string());
  495. obj.add("local_port", socket.local_port());
  496. obj.add("peer_address", socket.peer_address().to_string());
  497. obj.add("peer_port", socket.peer_port());
  498. });
  499. array.finish();
  500. return builder.build();
  501. }
  502. Optional<KBuffer> procfs$net_local(InodeIdentifier)
  503. {
  504. KBufferBuilder builder;
  505. JsonArraySerializer array { builder };
  506. LocalSocket::for_each([&array](auto& socket) {
  507. auto obj = array.add_object();
  508. obj.add("path", String(socket.socket_path()));
  509. obj.add("origin_pid", socket.origin_pid());
  510. obj.add("origin_uid", socket.origin_uid());
  511. obj.add("origin_gid", socket.origin_gid());
  512. obj.add("acceptor_pid", socket.acceptor_pid());
  513. obj.add("acceptor_uid", socket.acceptor_uid());
  514. obj.add("acceptor_gid", socket.acceptor_gid());
  515. });
  516. array.finish();
  517. return builder.build();
  518. }
  519. Optional<KBuffer> procfs$pid_vmobjects(InodeIdentifier identifier)
  520. {
  521. auto process = Process::from_pid(to_pid(identifier));
  522. if (!process)
  523. return {};
  524. KBufferBuilder builder;
  525. builder.appendf("BEGIN END SIZE NAME\n");
  526. {
  527. ScopedSpinLock lock(process->get_lock());
  528. for (auto& region : process->regions()) {
  529. builder.appendf("%x -- %x %x %s\n",
  530. region.vaddr().get(),
  531. region.vaddr().offset(region.size() - 1).get(),
  532. region.size(),
  533. region.name().characters());
  534. builder.appendf("VMO: %s @ %x(%u)\n",
  535. region.vmobject().is_anonymous() ? "anonymous" : "file-backed",
  536. &region.vmobject(),
  537. region.vmobject().ref_count());
  538. for (size_t i = 0; i < region.vmobject().page_count(); ++i) {
  539. auto& physical_page = region.vmobject().physical_pages()[i];
  540. bool should_cow = false;
  541. if (i >= region.first_page_index() && i <= region.last_page_index())
  542. should_cow = region.should_cow(i - region.first_page_index());
  543. builder.appendf("P%x%s(%u) ",
  544. physical_page ? physical_page->paddr().get() : 0,
  545. should_cow ? "!" : "",
  546. physical_page ? physical_page->ref_count() : 0);
  547. }
  548. builder.appendf("\n");
  549. }
  550. }
  551. return builder.build();
  552. }
  553. Optional<KBuffer> procfs$pid_unveil(InodeIdentifier identifier)
  554. {
  555. auto process = Process::from_pid(to_pid(identifier));
  556. if (!process)
  557. return {};
  558. KBufferBuilder builder;
  559. JsonArraySerializer array { builder };
  560. for (auto& unveiled_path : process->unveiled_paths()) {
  561. auto obj = array.add_object();
  562. obj.add("path", unveiled_path.path);
  563. StringBuilder permissions_builder;
  564. if (unveiled_path.permissions & UnveiledPath::Access::Read)
  565. permissions_builder.append('r');
  566. if (unveiled_path.permissions & UnveiledPath::Access::Write)
  567. permissions_builder.append('w');
  568. if (unveiled_path.permissions & UnveiledPath::Access::Execute)
  569. permissions_builder.append('x');
  570. if (unveiled_path.permissions & UnveiledPath::Access::CreateOrRemove)
  571. permissions_builder.append('c');
  572. obj.add("permissions", permissions_builder.to_string());
  573. }
  574. array.finish();
  575. return builder.build();
  576. }
  577. Optional<KBuffer> procfs$pid_stack(InodeIdentifier identifier)
  578. {
  579. auto process = Process::from_pid(to_pid(identifier));
  580. if (!process)
  581. return {};
  582. return process->backtrace();
  583. }
  584. Optional<KBuffer> procfs$pid_exe(InodeIdentifier identifier)
  585. {
  586. auto process = Process::from_pid(to_pid(identifier));
  587. if (!process)
  588. return {};
  589. auto* custody = process->executable();
  590. ASSERT(custody);
  591. return custody->absolute_path().to_byte_buffer();
  592. }
  593. Optional<KBuffer> procfs$pid_cwd(InodeIdentifier identifier)
  594. {
  595. auto process = Process::from_pid(to_pid(identifier));
  596. if (!process)
  597. return {};
  598. return process->current_directory().absolute_path().to_byte_buffer();
  599. }
  600. Optional<KBuffer> procfs$pid_root(InodeIdentifier identifier)
  601. {
  602. auto process = Process::from_pid(to_pid(identifier));
  603. if (!process)
  604. return {};
  605. return process->root_directory_relative_to_global_root().absolute_path().to_byte_buffer();
  606. }
  607. Optional<KBuffer> procfs$self(InodeIdentifier)
  608. {
  609. char buffer[16];
  610. sprintf(buffer, "%d", Process::current()->pid().value());
  611. return KBuffer::copy((const u8*)buffer, strlen(buffer));
  612. }
  613. Optional<KBuffer> procfs$mm(InodeIdentifier)
  614. {
  615. InterruptDisabler disabler;
  616. KBufferBuilder builder;
  617. u32 vmobject_count = 0;
  618. MemoryManager::for_each_vmobject([&](auto& vmobject) {
  619. ++vmobject_count;
  620. builder.appendf("VMObject: %p %s(%u): p:%4u\n",
  621. &vmobject,
  622. vmobject.is_anonymous() ? "anon" : "file",
  623. vmobject.ref_count(),
  624. vmobject.page_count());
  625. return IterationDecision::Continue;
  626. });
  627. builder.appendf("VMO count: %u\n", vmobject_count);
  628. builder.appendf("Free physical pages: %u\n", MM.user_physical_pages() - MM.user_physical_pages_used());
  629. builder.appendf("Free supervisor physical pages: %u\n", MM.super_physical_pages() - MM.super_physical_pages_used());
  630. return builder.build();
  631. }
  632. Optional<KBuffer> procfs$dmesg(InodeIdentifier)
  633. {
  634. InterruptDisabler disabler;
  635. KBufferBuilder builder;
  636. for (char ch : Console::the().logbuffer())
  637. builder.append(ch);
  638. return builder.build();
  639. }
  640. Optional<KBuffer> procfs$mounts(InodeIdentifier)
  641. {
  642. // FIXME: This is obviously racy against the VFS mounts changing.
  643. KBufferBuilder builder;
  644. VFS::the().for_each_mount([&builder](auto& mount) {
  645. auto& fs = mount.guest_fs();
  646. builder.appendf("%s @ ", fs.class_name());
  647. if (mount.host() == nullptr)
  648. builder.appendf("/");
  649. else {
  650. builder.appendf("%u:%u", mount.host()->fsid(), mount.host()->index());
  651. builder.append(' ');
  652. builder.append(mount.absolute_path());
  653. }
  654. builder.append('\n');
  655. });
  656. return builder.build();
  657. }
  658. Optional<KBuffer> procfs$df(InodeIdentifier)
  659. {
  660. // FIXME: This is obviously racy against the VFS mounts changing.
  661. KBufferBuilder builder;
  662. JsonArraySerializer array { builder };
  663. VFS::the().for_each_mount([&array](auto& mount) {
  664. auto& fs = mount.guest_fs();
  665. auto fs_object = array.add_object();
  666. fs_object.add("class_name", fs.class_name());
  667. fs_object.add("total_block_count", fs.total_block_count());
  668. fs_object.add("free_block_count", fs.free_block_count());
  669. fs_object.add("total_inode_count", fs.total_inode_count());
  670. fs_object.add("free_inode_count", fs.free_inode_count());
  671. fs_object.add("mount_point", mount.absolute_path());
  672. fs_object.add("block_size", static_cast<u64>(fs.block_size()));
  673. fs_object.add("readonly", fs.is_readonly());
  674. fs_object.add("mount_flags", mount.flags());
  675. if (fs.is_file_backed())
  676. fs_object.add("source", static_cast<const FileBackedFS&>(fs).file_description().absolute_path());
  677. else
  678. fs_object.add("source", "none");
  679. });
  680. array.finish();
  681. return builder.build();
  682. }
  683. Optional<KBuffer> procfs$cpuinfo(InodeIdentifier)
  684. {
  685. KBufferBuilder builder;
  686. JsonArraySerializer array { builder };
  687. Processor::for_each(
  688. [&](Processor& proc) -> IterationDecision {
  689. auto& info = proc.info();
  690. auto obj = array.add_object();
  691. JsonArray features;
  692. for (auto& feature : info.features().split(' '))
  693. features.append(feature);
  694. obj.add("processor", proc.id());
  695. obj.add("cpuid", info.cpuid());
  696. obj.add("family", info.display_family());
  697. obj.add("features", features);
  698. obj.add("model", info.display_model());
  699. obj.add("stepping", info.stepping());
  700. obj.add("type", info.type());
  701. obj.add("brandstr", info.brandstr());
  702. return IterationDecision::Continue;
  703. });
  704. array.finish();
  705. return builder.build();
  706. }
  707. Optional<KBuffer> procfs$memstat(InodeIdentifier)
  708. {
  709. InterruptDisabler disabler;
  710. KBufferBuilder builder;
  711. JsonObjectSerializer<KBufferBuilder> json { builder };
  712. json.add("kmalloc_allocated", g_kmalloc_bytes_allocated);
  713. json.add("kmalloc_available", g_kmalloc_bytes_free);
  714. json.add("kmalloc_eternal_allocated", g_kmalloc_bytes_eternal);
  715. json.add("user_physical_allocated", MM.user_physical_pages_used());
  716. json.add("user_physical_available", MM.user_physical_pages() - MM.user_physical_pages_used());
  717. json.add("super_physical_allocated", MM.super_physical_pages_used());
  718. json.add("super_physical_available", MM.super_physical_pages() - MM.super_physical_pages_used());
  719. json.add("kmalloc_call_count", g_kmalloc_call_count);
  720. json.add("kfree_call_count", g_kfree_call_count);
  721. slab_alloc_stats([&json](size_t slab_size, size_t num_allocated, size_t num_free) {
  722. auto prefix = String::format("slab_%zu", slab_size);
  723. json.add(String::format("%s_num_allocated", prefix.characters()), num_allocated);
  724. json.add(String::format("%s_num_free", prefix.characters()), num_free);
  725. });
  726. json.finish();
  727. return builder.build();
  728. }
  729. Optional<KBuffer> procfs$all(InodeIdentifier)
  730. {
  731. KBufferBuilder builder;
  732. JsonArraySerializer array { builder };
  733. // Keep this in sync with CProcessStatistics.
  734. auto build_process = [&](const Process& process) {
  735. auto process_object = array.add_object();
  736. StringBuilder pledge_builder;
  737. #define __ENUMERATE_PLEDGE_PROMISE(promise) \
  738. if (process.has_promised(Pledge::promise)) { \
  739. pledge_builder.append(#promise " "); \
  740. }
  741. ENUMERATE_PLEDGE_PROMISES
  742. #undef __ENUMERATE_PLEDGE_PROMISE
  743. process_object.add("pledge", pledge_builder.to_string());
  744. switch (process.veil_state()) {
  745. case VeilState::None:
  746. process_object.add("veil", "None");
  747. break;
  748. case VeilState::Dropped:
  749. process_object.add("veil", "Dropped");
  750. break;
  751. case VeilState::Locked:
  752. process_object.add("veil", "Locked");
  753. break;
  754. }
  755. process_object.add("pid", process.pid().value());
  756. process_object.add("pgid", process.tty() ? process.tty()->pgid().value() : 0);
  757. process_object.add("pgp", process.pgid().value());
  758. process_object.add("sid", process.sid().value());
  759. process_object.add("uid", process.uid());
  760. process_object.add("gid", process.gid());
  761. process_object.add("ppid", process.ppid().value());
  762. process_object.add("nfds", process.number_of_open_file_descriptors());
  763. process_object.add("name", process.name());
  764. process_object.add("tty", process.tty() ? process.tty()->tty_name() : "notty");
  765. process_object.add("amount_virtual", process.amount_virtual());
  766. process_object.add("amount_resident", process.amount_resident());
  767. process_object.add("amount_dirty_private", process.amount_dirty_private());
  768. process_object.add("amount_clean_inode", process.amount_clean_inode());
  769. process_object.add("amount_shared", process.amount_shared());
  770. process_object.add("amount_purgeable_volatile", process.amount_purgeable_volatile());
  771. process_object.add("amount_purgeable_nonvolatile", process.amount_purgeable_nonvolatile());
  772. process_object.add("icon_id", process.icon_id());
  773. auto thread_array = process_object.add_array("threads");
  774. process.for_each_thread([&](const Thread& thread) {
  775. auto thread_object = thread_array.add_object();
  776. thread_object.add("tid", thread.tid().value());
  777. thread_object.add("name", thread.name());
  778. thread_object.add("times_scheduled", thread.times_scheduled());
  779. thread_object.add("ticks", thread.ticks());
  780. thread_object.add("state", thread.state_string());
  781. thread_object.add("cpu", thread.cpu());
  782. thread_object.add("priority", thread.priority());
  783. thread_object.add("effective_priority", thread.effective_priority());
  784. thread_object.add("syscall_count", thread.syscall_count());
  785. thread_object.add("inode_faults", thread.inode_faults());
  786. thread_object.add("zero_faults", thread.zero_faults());
  787. thread_object.add("cow_faults", thread.cow_faults());
  788. thread_object.add("file_read_bytes", thread.file_read_bytes());
  789. thread_object.add("file_write_bytes", thread.file_write_bytes());
  790. thread_object.add("unix_socket_read_bytes", thread.unix_socket_read_bytes());
  791. thread_object.add("unix_socket_write_bytes", thread.unix_socket_write_bytes());
  792. thread_object.add("ipv4_socket_read_bytes", thread.ipv4_socket_read_bytes());
  793. thread_object.add("ipv4_socket_write_bytes", thread.ipv4_socket_write_bytes());
  794. return IterationDecision::Continue;
  795. });
  796. };
  797. ScopedSpinLock lock(g_scheduler_lock);
  798. auto processes = Process::all_processes();
  799. build_process(*Scheduler::colonel());
  800. for (auto& process : processes)
  801. build_process(process);
  802. array.finish();
  803. return builder.build();
  804. }
  805. Optional<KBuffer> procfs$inodes(InodeIdentifier)
  806. {
  807. extern InlineLinkedList<Inode>& all_inodes();
  808. KBufferBuilder builder;
  809. InterruptDisabler disabler;
  810. for (auto& inode : all_inodes()) {
  811. builder.appendf("Inode{K%x} %02u:%08u (%u)\n", &inode, inode.fsid(), inode.index(), inode.ref_count());
  812. }
  813. return builder.build();
  814. }
  815. struct SysVariable {
  816. String name;
  817. enum class Type : u8 {
  818. Invalid,
  819. Boolean,
  820. String,
  821. };
  822. Type type { Type::Invalid };
  823. Function<void()> notify_callback;
  824. void* address { nullptr };
  825. static SysVariable& for_inode(InodeIdentifier);
  826. void notify()
  827. {
  828. if (notify_callback)
  829. notify_callback();
  830. }
  831. };
  832. static Vector<SysVariable, 16>* s_sys_variables;
  833. static inline Vector<SysVariable, 16>& sys_variables()
  834. {
  835. if (s_sys_variables == nullptr) {
  836. s_sys_variables = new Vector<SysVariable, 16>;
  837. s_sys_variables->append({ "", SysVariable::Type::Invalid, nullptr, nullptr });
  838. }
  839. return *s_sys_variables;
  840. }
  841. SysVariable& SysVariable::for_inode(InodeIdentifier id)
  842. {
  843. auto index = to_sys_index(id);
  844. if (index >= sys_variables().size())
  845. return sys_variables()[0];
  846. auto& variable = sys_variables()[index];
  847. ASSERT(variable.address);
  848. return variable;
  849. }
  850. static ByteBuffer read_sys_bool(InodeIdentifier inode_id)
  851. {
  852. auto& variable = SysVariable::for_inode(inode_id);
  853. ASSERT(variable.type == SysVariable::Type::Boolean);
  854. auto buffer = ByteBuffer::create_uninitialized(2);
  855. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  856. {
  857. LOCKER(lockable_bool->lock(), Lock::Mode::Shared);
  858. buffer[0] = lockable_bool->resource() ? '1' : '0';
  859. }
  860. buffer[1] = '\n';
  861. return buffer;
  862. }
  863. static ssize_t write_sys_bool(InodeIdentifier inode_id, const ByteBuffer& data)
  864. {
  865. auto& variable = SysVariable::for_inode(inode_id);
  866. ASSERT(variable.type == SysVariable::Type::Boolean);
  867. if (data.is_empty() || !(data[0] == '0' || data[0] == '1'))
  868. return data.size();
  869. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  870. {
  871. LOCKER(lockable_bool->lock());
  872. lockable_bool->resource() = data[0] == '1';
  873. }
  874. variable.notify();
  875. return data.size();
  876. }
  877. static ByteBuffer read_sys_string(InodeIdentifier inode_id)
  878. {
  879. auto& variable = SysVariable::for_inode(inode_id);
  880. ASSERT(variable.type == SysVariable::Type::String);
  881. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  882. LOCKER(lockable_string->lock(), Lock::Mode::Shared);
  883. return lockable_string->resource().to_byte_buffer();
  884. }
  885. static ssize_t write_sys_string(InodeIdentifier inode_id, const ByteBuffer& data)
  886. {
  887. auto& variable = SysVariable::for_inode(inode_id);
  888. ASSERT(variable.type == SysVariable::Type::String);
  889. {
  890. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  891. LOCKER(lockable_string->lock());
  892. lockable_string->resource() = String((const char*)data.data(), data.size());
  893. }
  894. variable.notify();
  895. return data.size();
  896. }
  897. void ProcFS::add_sys_bool(String&& name, Lockable<bool>& var, Function<void()>&& notify_callback)
  898. {
  899. InterruptDisabler disabler;
  900. SysVariable variable;
  901. variable.name = move(name);
  902. variable.type = SysVariable::Type::Boolean;
  903. variable.notify_callback = move(notify_callback);
  904. variable.address = &var;
  905. sys_variables().append(move(variable));
  906. }
  907. void ProcFS::add_sys_string(String&& name, Lockable<String>& var, Function<void()>&& notify_callback)
  908. {
  909. InterruptDisabler disabler;
  910. SysVariable variable;
  911. variable.name = move(name);
  912. variable.type = SysVariable::Type::String;
  913. variable.notify_callback = move(notify_callback);
  914. variable.address = &var;
  915. sys_variables().append(move(variable));
  916. }
  917. bool ProcFS::initialize()
  918. {
  919. static Lockable<bool>* kmalloc_stack_helper;
  920. if (kmalloc_stack_helper == nullptr) {
  921. kmalloc_stack_helper = new Lockable<bool>();
  922. kmalloc_stack_helper->resource() = g_dump_kmalloc_stacks;
  923. ProcFS::add_sys_bool("kmalloc_stacks", *kmalloc_stack_helper, [] {
  924. g_dump_kmalloc_stacks = kmalloc_stack_helper->resource();
  925. });
  926. }
  927. return true;
  928. }
  929. const char* ProcFS::class_name() const
  930. {
  931. return "ProcFS";
  932. }
  933. NonnullRefPtr<Inode> ProcFS::root_inode() const
  934. {
  935. return *m_root_inode;
  936. }
  937. RefPtr<Inode> ProcFS::get_inode(InodeIdentifier inode_id) const
  938. {
  939. #ifdef PROCFS_DEBUG
  940. dbg() << "ProcFS::get_inode(" << inode_id.index() << ")";
  941. #endif
  942. if (inode_id == root_inode()->identifier())
  943. return m_root_inode;
  944. LOCKER(m_inodes_lock);
  945. auto it = m_inodes.find(inode_id.index());
  946. if (it == m_inodes.end()) {
  947. auto inode = adopt(*new ProcFSInode(const_cast<ProcFS&>(*this), inode_id.index()));
  948. m_inodes.set(inode_id.index(), inode.ptr());
  949. return inode;
  950. }
  951. return (*it).value;
  952. }
  953. ProcFSInode::ProcFSInode(ProcFS& fs, unsigned index)
  954. : Inode(fs, index)
  955. {
  956. }
  957. ProcFSInode::~ProcFSInode()
  958. {
  959. LOCKER(fs().m_inodes_lock);
  960. fs().m_inodes.remove(index());
  961. }
  962. InodeMetadata ProcFSInode::metadata() const
  963. {
  964. #ifdef PROCFS_DEBUG
  965. dbg() << "ProcFSInode::metadata(" << index() << ")";
  966. #endif
  967. InodeMetadata metadata;
  968. metadata.inode = identifier();
  969. metadata.ctime = mepoch;
  970. metadata.atime = mepoch;
  971. metadata.mtime = mepoch;
  972. auto proc_parent_directory = to_proc_parent_directory(identifier());
  973. auto pid = to_pid(identifier());
  974. auto proc_file_type = to_proc_file_type(identifier());
  975. #ifdef PROCFS_DEBUG
  976. dbg() << " -> pid: " << pid << ", fi: " << proc_file_type << ", pdi: " << proc_parent_directory;
  977. #endif
  978. if (is_process_related_file(identifier())) {
  979. auto process = Process::from_pid(pid);
  980. if (process) {
  981. metadata.uid = process->sys$getuid();
  982. metadata.gid = process->sys$getgid();
  983. } else {
  984. // TODO: How to handle this?
  985. metadata.uid = 0;
  986. metadata.gid = 0;
  987. }
  988. }
  989. if (proc_parent_directory == PDI_PID_fd) {
  990. metadata.mode = S_IFLNK | S_IRUSR | S_IWUSR | S_IXUSR;
  991. return metadata;
  992. }
  993. switch (proc_file_type) {
  994. case FI_Root_self:
  995. metadata.mode = S_IFLNK | S_IRUSR | S_IRGRP | S_IROTH;
  996. break;
  997. case FI_PID_cwd:
  998. case FI_PID_exe:
  999. case FI_PID_root:
  1000. metadata.mode = S_IFLNK | S_IRUSR;
  1001. break;
  1002. case FI_Root:
  1003. case FI_Root_sys:
  1004. case FI_Root_net:
  1005. metadata.mode = S_IFDIR | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
  1006. break;
  1007. case FI_PID:
  1008. case FI_PID_fd:
  1009. metadata.mode = S_IFDIR | S_IRUSR | S_IXUSR;
  1010. break;
  1011. default:
  1012. metadata.mode = S_IFREG | S_IRUSR | S_IRGRP | S_IROTH;
  1013. break;
  1014. }
  1015. if (proc_file_type > FI_Invalid && proc_file_type < FI_MaxStaticFileIndex) {
  1016. if (fs().m_entries[proc_file_type].supervisor_only) {
  1017. metadata.uid = 0;
  1018. metadata.gid = 0;
  1019. metadata.mode &= ~077;
  1020. }
  1021. }
  1022. #ifdef PROCFS_DEBUG
  1023. dbg() << "Returning mode " << String::format("%o", metadata.mode);
  1024. #endif
  1025. return metadata;
  1026. }
  1027. ssize_t ProcFSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription* description) const
  1028. {
  1029. #ifdef PROCFS_DEBUG
  1030. dbg() << "ProcFS: read_bytes " << index();
  1031. #endif
  1032. ASSERT(offset >= 0);
  1033. ASSERT(buffer);
  1034. auto* directory_entry = fs().get_directory_entry(identifier());
  1035. Function<Optional<KBuffer>(InodeIdentifier)> callback_tmp;
  1036. Function<Optional<KBuffer>(InodeIdentifier)>* read_callback { nullptr };
  1037. if (directory_entry)
  1038. read_callback = &directory_entry->read_callback;
  1039. else
  1040. switch (to_proc_parent_directory(identifier())) {
  1041. case PDI_PID_fd:
  1042. callback_tmp = procfs$pid_fd_entry;
  1043. read_callback = &callback_tmp;
  1044. break;
  1045. case PDI_Root_sys:
  1046. switch (SysVariable::for_inode(identifier()).type) {
  1047. case SysVariable::Type::Invalid:
  1048. ASSERT_NOT_REACHED();
  1049. case SysVariable::Type::Boolean:
  1050. callback_tmp = read_sys_bool;
  1051. break;
  1052. case SysVariable::Type::String:
  1053. callback_tmp = read_sys_string;
  1054. break;
  1055. }
  1056. read_callback = &callback_tmp;
  1057. break;
  1058. default:
  1059. ASSERT_NOT_REACHED();
  1060. }
  1061. ASSERT(read_callback);
  1062. Optional<KBuffer> generated_data;
  1063. if (!description) {
  1064. generated_data = (*read_callback)(identifier());
  1065. } else {
  1066. if (!description->generator_cache().has_value())
  1067. description->generator_cache() = (*read_callback)(identifier());
  1068. generated_data = description->generator_cache();
  1069. }
  1070. auto& data = generated_data;
  1071. if (!data.has_value())
  1072. return 0;
  1073. if ((size_t)offset >= data.value().size())
  1074. return 0;
  1075. ssize_t nread = min(static_cast<off_t>(data.value().size() - offset), static_cast<off_t>(count));
  1076. memcpy(buffer, data.value().data() + offset, nread);
  1077. if (nread == 0 && description && description->generator_cache().has_value())
  1078. description->generator_cache().clear();
  1079. return nread;
  1080. }
  1081. InodeIdentifier ProcFS::ProcFSDirectoryEntry::identifier(unsigned fsid) const
  1082. {
  1083. return to_identifier(fsid, PDI_Root, 0, (ProcFileType)proc_file_type);
  1084. }
  1085. KResult ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  1086. {
  1087. #ifdef PROCFS_DEBUG
  1088. dbg() << "ProcFS: traverse_as_directory " << index();
  1089. #endif
  1090. if (!Kernel::is_directory(identifier()))
  1091. return KResult(-ENOTDIR);
  1092. auto pid = to_pid(identifier());
  1093. auto proc_file_type = to_proc_file_type(identifier());
  1094. auto parent_id = to_parent_id(identifier());
  1095. callback({ ".", 1, identifier(), 2 });
  1096. callback({ "..", 2, parent_id, 2 });
  1097. switch (proc_file_type) {
  1098. case FI_Root:
  1099. for (auto& entry : fs().m_entries) {
  1100. // FIXME: strlen() here is sad.
  1101. if (!entry.name)
  1102. continue;
  1103. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End)
  1104. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type), 0 });
  1105. }
  1106. for (auto pid_child : Process::all_pids()) {
  1107. char name[16];
  1108. size_t name_length = (size_t)sprintf(name, "%d", pid_child.value());
  1109. callback({ name, name_length, to_identifier(fsid(), PDI_Root, pid_child, FI_PID), 0 });
  1110. }
  1111. break;
  1112. case FI_Root_sys:
  1113. for (size_t i = 1; i < sys_variables().size(); ++i) {
  1114. auto& variable = sys_variables()[i];
  1115. callback({ variable.name.characters(), variable.name.length(), sys_var_to_identifier(fsid(), i), 0 });
  1116. }
  1117. break;
  1118. case FI_Root_net:
  1119. callback({ "adapters", 8, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_adapters), 0 });
  1120. callback({ "arp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_arp), 0 });
  1121. callback({ "tcp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_tcp), 0 });
  1122. callback({ "udp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_udp), 0 });
  1123. callback({ "local", 5, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_local), 0 });
  1124. break;
  1125. case FI_PID: {
  1126. auto process = Process::from_pid(pid);
  1127. if (!process)
  1128. return KResult(-ENOENT);
  1129. for (auto& entry : fs().m_entries) {
  1130. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1131. if (entry.proc_file_type == FI_PID_exe && !process->executable())
  1132. continue;
  1133. // FIXME: strlen() here is sad.
  1134. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_PID, pid, (ProcFileType)entry.proc_file_type), 0 });
  1135. }
  1136. }
  1137. } break;
  1138. case FI_PID_fd: {
  1139. auto process = Process::from_pid(pid);
  1140. if (!process)
  1141. return KResult(-ENOENT);
  1142. for (int i = 0; i < process->max_open_file_descriptors(); ++i) {
  1143. auto description = process->file_description(i);
  1144. if (!description)
  1145. continue;
  1146. char name[16];
  1147. size_t name_length = (size_t)sprintf(name, "%d", i);
  1148. callback({ name, name_length, to_identifier_with_fd(fsid(), pid, i), 0 });
  1149. }
  1150. } break;
  1151. default:
  1152. return KSuccess;
  1153. }
  1154. return KSuccess;
  1155. }
  1156. RefPtr<Inode> ProcFSInode::lookup(StringView name)
  1157. {
  1158. ASSERT(is_directory());
  1159. if (name == ".")
  1160. return this;
  1161. if (name == "..")
  1162. return fs().get_inode(to_parent_id(identifier()));
  1163. auto proc_file_type = to_proc_file_type(identifier());
  1164. if (proc_file_type == FI_Root) {
  1165. for (auto& entry : fs().m_entries) {
  1166. if (entry.name == nullptr)
  1167. continue;
  1168. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End) {
  1169. if (name == entry.name) {
  1170. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type));
  1171. }
  1172. }
  1173. }
  1174. auto name_as_number = name.to_uint();
  1175. if (!name_as_number.has_value())
  1176. return {};
  1177. bool process_exists = false;
  1178. {
  1179. InterruptDisabler disabler;
  1180. process_exists = Process::from_pid(name_as_number.value());
  1181. }
  1182. if (process_exists)
  1183. return fs().get_inode(to_identifier(fsid(), PDI_Root, name_as_number.value(), FI_PID));
  1184. return {};
  1185. }
  1186. if (proc_file_type == FI_Root_sys) {
  1187. for (size_t i = 1; i < sys_variables().size(); ++i) {
  1188. auto& variable = sys_variables()[i];
  1189. if (name == variable.name)
  1190. return fs().get_inode(sys_var_to_identifier(fsid(), i));
  1191. }
  1192. return {};
  1193. }
  1194. if (proc_file_type == FI_Root_net) {
  1195. if (name == "adapters")
  1196. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_adapters));
  1197. if (name == "arp")
  1198. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_arp));
  1199. if (name == "tcp")
  1200. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_tcp));
  1201. if (name == "udp")
  1202. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_udp));
  1203. if (name == "local")
  1204. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_local));
  1205. return {};
  1206. }
  1207. if (proc_file_type == FI_PID) {
  1208. auto process = Process::from_pid(to_pid(identifier()));
  1209. if (!process)
  1210. return {};
  1211. for (auto& entry : fs().m_entries) {
  1212. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1213. if (entry.proc_file_type == FI_PID_exe && !process->executable())
  1214. continue;
  1215. if (entry.name == nullptr)
  1216. continue;
  1217. if (name == entry.name) {
  1218. return fs().get_inode(to_identifier(fsid(), PDI_PID, to_pid(identifier()), (ProcFileType)entry.proc_file_type));
  1219. }
  1220. }
  1221. }
  1222. return {};
  1223. }
  1224. if (proc_file_type == FI_PID_fd) {
  1225. auto name_as_number = name.to_uint();
  1226. if (!name_as_number.has_value())
  1227. return {};
  1228. bool fd_exists = false;
  1229. {
  1230. if (auto process = Process::from_pid(to_pid(identifier())))
  1231. fd_exists = process->file_description(name_as_number.value());
  1232. }
  1233. if (fd_exists)
  1234. return fs().get_inode(to_identifier_with_fd(fsid(), to_pid(identifier()), name_as_number.value()));
  1235. }
  1236. return {};
  1237. }
  1238. void ProcFSInode::flush_metadata()
  1239. {
  1240. }
  1241. ssize_t ProcFSInode::write_bytes(off_t offset, ssize_t size, const u8* buffer, FileDescription*)
  1242. {
  1243. auto result = prepare_to_write_data();
  1244. if (result.is_error())
  1245. return result;
  1246. auto* directory_entry = fs().get_directory_entry(identifier());
  1247. Function<ssize_t(InodeIdentifier, const ByteBuffer&)> callback_tmp;
  1248. Function<ssize_t(InodeIdentifier, const ByteBuffer&)>* write_callback { nullptr };
  1249. if (directory_entry == nullptr) {
  1250. if (to_proc_parent_directory(identifier()) == PDI_Root_sys) {
  1251. switch (SysVariable::for_inode(identifier()).type) {
  1252. case SysVariable::Type::Invalid:
  1253. ASSERT_NOT_REACHED();
  1254. case SysVariable::Type::Boolean:
  1255. callback_tmp = write_sys_bool;
  1256. break;
  1257. case SysVariable::Type::String:
  1258. callback_tmp = write_sys_string;
  1259. break;
  1260. }
  1261. write_callback = &callback_tmp;
  1262. } else
  1263. return -EPERM;
  1264. } else {
  1265. if (!directory_entry->write_callback)
  1266. return -EPERM;
  1267. write_callback = &directory_entry->write_callback;
  1268. }
  1269. ASSERT(is_persistent_inode(identifier()));
  1270. // FIXME: Being able to write into ProcFS at a non-zero offset seems like something we should maybe support..
  1271. ASSERT(offset == 0);
  1272. bool success = (*write_callback)(identifier(), ByteBuffer::wrap(const_cast<u8*>(buffer), size));
  1273. ASSERT(success);
  1274. return 0;
  1275. }
  1276. KResultOr<NonnullRefPtr<Custody>> ProcFSInode::resolve_as_link(Custody& base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level) const
  1277. {
  1278. if (!is_process_related_file(identifier()))
  1279. return Inode::resolve_as_link(base, out_parent, options, symlink_recursion_level);
  1280. // FIXME: We should return a custody for FI_PID or FI_PID_fd here
  1281. // for correctness. It's impossible to create files in ProcFS,
  1282. // so returning null shouldn't break much.
  1283. if (out_parent)
  1284. *out_parent = nullptr;
  1285. auto pid = to_pid(identifier());
  1286. auto proc_file_type = to_proc_file_type(identifier());
  1287. auto process = Process::from_pid(pid);
  1288. if (!process)
  1289. return KResult(-ENOENT);
  1290. if (to_proc_parent_directory(identifier()) == PDI_PID_fd) {
  1291. if (out_parent)
  1292. *out_parent = base;
  1293. int fd = to_fd(identifier());
  1294. auto description = process->file_description(fd);
  1295. if (!description)
  1296. return KResult(-ENOENT);
  1297. auto proxy_inode = ProcFSProxyInode::create(const_cast<ProcFS&>(fs()), *description);
  1298. return Custody::create(&base, "", proxy_inode, base.mount_flags());
  1299. }
  1300. Custody* res = nullptr;
  1301. switch (proc_file_type) {
  1302. case FI_PID_cwd:
  1303. res = &process->current_directory();
  1304. break;
  1305. case FI_PID_exe:
  1306. res = process->executable();
  1307. break;
  1308. case FI_PID_root:
  1309. // Note: we open root_directory() here, not
  1310. // root_directory_relative_to_global_root().
  1311. // This seems more useful.
  1312. res = &process->root_directory();
  1313. break;
  1314. default:
  1315. ASSERT_NOT_REACHED();
  1316. }
  1317. if (!res)
  1318. return KResult(-ENOENT);
  1319. return *res;
  1320. }
  1321. ProcFSProxyInode::ProcFSProxyInode(ProcFS& fs, FileDescription& fd)
  1322. : Inode(fs, 0)
  1323. , m_fd(fd)
  1324. {
  1325. }
  1326. ProcFSProxyInode::~ProcFSProxyInode()
  1327. {
  1328. }
  1329. InodeMetadata ProcFSProxyInode::metadata() const
  1330. {
  1331. InodeMetadata metadata = m_fd->metadata();
  1332. if (m_fd->is_readable())
  1333. metadata.mode |= 0444;
  1334. else
  1335. metadata.mode &= ~0444;
  1336. if (m_fd->is_writable())
  1337. metadata.mode |= 0222;
  1338. else
  1339. metadata.mode &= ~0222;
  1340. if (!metadata.is_directory())
  1341. metadata.mode &= ~0111;
  1342. return metadata;
  1343. }
  1344. KResultOr<NonnullRefPtr<Inode>> ProcFSProxyInode::create_child(const String& name, mode_t mode, dev_t dev, uid_t uid, gid_t gid)
  1345. {
  1346. if (!m_fd->inode())
  1347. return KResult(-EINVAL);
  1348. return m_fd->inode()->create_child(name, mode, dev, uid, gid);
  1349. }
  1350. KResult ProcFSProxyInode::add_child(Inode& child, const StringView& name, mode_t mode)
  1351. {
  1352. if (!m_fd->inode())
  1353. return KResult(-EINVAL);
  1354. return m_fd->inode()->add_child(child, name, mode);
  1355. }
  1356. KResult ProcFSProxyInode::remove_child(const StringView& name)
  1357. {
  1358. if (!m_fd->inode())
  1359. return KResult(-EINVAL);
  1360. return m_fd->inode()->remove_child(name);
  1361. }
  1362. RefPtr<Inode> ProcFSProxyInode::lookup(StringView name)
  1363. {
  1364. if (!m_fd->inode())
  1365. return {};
  1366. return m_fd->inode()->lookup(name);
  1367. }
  1368. KResultOr<size_t> ProcFSProxyInode::directory_entry_count() const
  1369. {
  1370. if (!m_fd->inode())
  1371. return KResult(-EINVAL);
  1372. return m_fd->inode()->directory_entry_count();
  1373. }
  1374. KResultOr<NonnullRefPtr<Inode>> ProcFSInode::create_child(const String&, mode_t, dev_t, uid_t, gid_t)
  1375. {
  1376. return KResult(-EPERM);
  1377. }
  1378. KResult ProcFSInode::add_child(Inode&, const StringView&, mode_t)
  1379. {
  1380. return KResult(-EPERM);
  1381. }
  1382. KResult ProcFSInode::remove_child(const StringView& name)
  1383. {
  1384. (void)name;
  1385. return KResult(-EPERM);
  1386. }
  1387. KResultOr<size_t> ProcFSInode::directory_entry_count() const
  1388. {
  1389. ASSERT(is_directory());
  1390. size_t count = 0;
  1391. KResult result = traverse_as_directory([&count](const FS::DirectoryEntry&) {
  1392. ++count;
  1393. return true;
  1394. });
  1395. if (result.is_error())
  1396. return result;
  1397. return count;
  1398. }
  1399. KResult ProcFSInode::chmod(mode_t)
  1400. {
  1401. return KResult(-EPERM);
  1402. }
  1403. ProcFS::ProcFS()
  1404. {
  1405. m_root_inode = adopt(*new ProcFSInode(*this, 1));
  1406. m_entries.resize(FI_MaxStaticFileIndex);
  1407. m_entries[FI_Root_mm] = { "mm", FI_Root_mm, true, procfs$mm };
  1408. m_entries[FI_Root_mounts] = { "mounts", FI_Root_mounts, false, procfs$mounts };
  1409. m_entries[FI_Root_df] = { "df", FI_Root_df, false, procfs$df };
  1410. m_entries[FI_Root_all] = { "all", FI_Root_all, false, procfs$all };
  1411. m_entries[FI_Root_memstat] = { "memstat", FI_Root_memstat, false, procfs$memstat };
  1412. m_entries[FI_Root_cpuinfo] = { "cpuinfo", FI_Root_cpuinfo, false, procfs$cpuinfo };
  1413. m_entries[FI_Root_inodes] = { "inodes", FI_Root_inodes, true, procfs$inodes };
  1414. m_entries[FI_Root_dmesg] = { "dmesg", FI_Root_dmesg, true, procfs$dmesg };
  1415. m_entries[FI_Root_self] = { "self", FI_Root_self, false, procfs$self };
  1416. m_entries[FI_Root_pci] = { "pci", FI_Root_pci, false, procfs$pci };
  1417. m_entries[FI_Root_interrupts] = { "interrupts", FI_Root_interrupts, false, procfs$interrupts };
  1418. m_entries[FI_Root_keymap] = { "keymap", FI_Root_keymap, false, procfs$keymap };
  1419. m_entries[FI_Root_devices] = { "devices", FI_Root_devices, false, procfs$devices };
  1420. m_entries[FI_Root_uptime] = { "uptime", FI_Root_uptime, false, procfs$uptime };
  1421. m_entries[FI_Root_cmdline] = { "cmdline", FI_Root_cmdline, true, procfs$cmdline };
  1422. m_entries[FI_Root_modules] = { "modules", FI_Root_modules, true, procfs$modules };
  1423. m_entries[FI_Root_profile] = { "profile", FI_Root_profile, false, procfs$profile };
  1424. m_entries[FI_Root_sys] = { "sys", FI_Root_sys, true };
  1425. m_entries[FI_Root_net] = { "net", FI_Root_net, false };
  1426. m_entries[FI_Root_net_adapters] = { "adapters", FI_Root_net_adapters, false, procfs$net_adapters };
  1427. m_entries[FI_Root_net_arp] = { "arp", FI_Root_net_arp, true, procfs$net_arp };
  1428. m_entries[FI_Root_net_tcp] = { "tcp", FI_Root_net_tcp, false, procfs$net_tcp };
  1429. m_entries[FI_Root_net_udp] = { "udp", FI_Root_net_udp, false, procfs$net_udp };
  1430. m_entries[FI_Root_net_local] = { "local", FI_Root_net_local, false, procfs$net_local };
  1431. m_entries[FI_PID_vm] = { "vm", FI_PID_vm, false, procfs$pid_vm };
  1432. m_entries[FI_PID_vmobjects] = { "vmobjects", FI_PID_vmobjects, true, procfs$pid_vmobjects };
  1433. m_entries[FI_PID_stack] = { "stack", FI_PID_stack, false, procfs$pid_stack };
  1434. m_entries[FI_PID_fds] = { "fds", FI_PID_fds, false, procfs$pid_fds };
  1435. m_entries[FI_PID_exe] = { "exe", FI_PID_exe, false, procfs$pid_exe };
  1436. m_entries[FI_PID_cwd] = { "cwd", FI_PID_cwd, false, procfs$pid_cwd };
  1437. m_entries[FI_PID_unveil] = { "unveil", FI_PID_unveil, false, procfs$pid_unveil };
  1438. m_entries[FI_PID_root] = { "root", FI_PID_root, false, procfs$pid_root };
  1439. m_entries[FI_PID_fd] = { "fd", FI_PID_fd, false };
  1440. }
  1441. ProcFS::ProcFSDirectoryEntry* ProcFS::get_directory_entry(InodeIdentifier identifier) const
  1442. {
  1443. auto proc_file_type = to_proc_file_type(identifier);
  1444. if (proc_file_type != FI_Invalid && proc_file_type != FI_Root_sys_variable && proc_file_type < FI_MaxStaticFileIndex)
  1445. return const_cast<ProcFSDirectoryEntry*>(&m_entries[proc_file_type]);
  1446. return nullptr;
  1447. }
  1448. KResult ProcFSInode::chown(uid_t, gid_t)
  1449. {
  1450. return KResult(-EPERM);
  1451. }
  1452. }