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