Skip to main content
SerenityOS includes approximately 80 libraries in Userland/Libraries/, all built from scratch. These libraries range from fundamental data structures (AK) to a complete web browser engine (LibWeb).

Library Organization

Libraries are categorized by functionality:
Core Infrastructure:
  • AK: Application Kit - fundamental data structures
  • LibC: C standard library (POSIX-compatible)
  • LibMain: Modern main() entry point
  • LibCore: Core functionality (event loop, I/O, system)
  • LibThreading: Threading primitives

AK: Application Kit

AK is the foundation library providing fundamental data structures and utilities:
Located in the /AK directory at the repository root, AK is usable in both kernel and userspace.

Core Data Structures

String Types:
  • String: Modern UTF-8 string (immutable, reference-counted)
  • ByteString: Legacy byte string
  • StringView: Non-owning string view
  • FlyString: Interned string for fast comparison
  • StringBuilder: Efficient string building
// Modern string usage
String name = "SerenityOS"sv;
StringView view = name.view();

StringBuilder builder;
builder.append("Hello "sv);
builder.append(name);
String greeting = TRY(builder.to_string());
Collection Types:
  • Vector<T>: Dynamic array (like std::vector)
  • Array<T, N>: Fixed-size array
  • FixedArray<T>: Runtime-sized, non-resizable array
  • HashMap<K, V>: Hash table
  • HashTable<T>: Hash set
  • RedBlackTree<T>: Balanced binary tree
  • IntrusiveList<T>: Intrusive linked list (OOM-safe)
  • CircularQueue<T>: Ring buffer
  • Queue<T>: FIFO queue
  • Stack<T>: LIFO stack
// Vector usage
Vector<int> numbers;
TRY(numbers.try_append(1));
TRY(numbers.try_append(2));

// HashMap usage
HashMap<String, int> scores;
TRY(scores.try_set("player1"sv, 100));
Memory Management:
  • RefPtr<T>: Reference-counted pointer (nullable)
  • NonnullRefPtr<T>: Non-null reference-counted pointer
  • OwnPtr<T>: Unique ownership pointer (nullable)
  • NonnullOwnPtr<T>: Non-null unique pointer
  • WeakPtr<T>: Weak reference
// Reference counting
RefPtr<Object> obj = Object::create();
if (obj) {
    obj->do_something();
}

// Unique ownership
OwnPtr<Data> data = make<Data>();
auto moved = move(data);  // Transfer ownership
Helpers:
  • Optional<T>: Maybe-type (like std::optional)
  • Variant<Ts...>: Type-safe union
  • ErrorOr<T>: Result type for error handling
  • Span<T>: Non-owning array view
  • Function<R(Args...)>: Function wrapper
  • Time: Time and duration types
  • Checked<T>: Overflow-checking arithmetic
// Optional usage
Optional<int> maybe_value = find_value();
if (maybe_value.has_value()) {
    int value = maybe_value.value();
}

// ErrorOr usage
ErrorOr<int> result = parse_number("42"sv);
if (result.is_error()) {
    return result.error();
}
int number = result.value();
Asynchronous I/O:
  • AsyncStream: Base for async streams
  • AsyncInputStream: Async input
  • Stream: Synchronous stream base
  • BufferedStream: Buffered I/O
  • CircularBuffer: Circular buffer
See Asynchronous Design Documentation for details.

AK Highlights

// TRY macro for seamless error propagation
ErrorOr<void> process_file(StringView path)
{
    auto file = TRY(open_file(path));
    auto data = TRY(file->read_all());
    TRY(process_data(data));
    return {};
}

// MUST macro for operations that should never fail
void critical_operation()
{
    MUST(vector.try_append(42));  // Will crash if fails
}

LibC: C Standard Library

SerenityOS’s custom C library provides POSIX compatibility:
  • stdio.h: Standard I/O
  • stdlib.h: Memory, program control
  • string.h: String operations
  • unistd.h: POSIX API
  • pthread.h: Threading
  • math.h: Mathematics
  • time.h: Time functions

LibCore: Core Functionality

LibCore provides essential userspace functionality:

Event Loop

See EventLoop Documentation for comprehensive details.
The event loop is central to GUI and network applications:
#include <LibCore/EventLoop.h>

int main()
{
    Core::EventLoop loop;
    
    // Deferred execution
    Core::deferred_invoke([&] {
        dbgln("This runs on next event loop iteration");
    });
    
    // Timers
    auto timer = Core::Timer::create();
    timer->set_interval(1000);
    timer->on_timeout = [] {
        dbgln("Timer fired!");
    };
    timer->start();
    
    return loop.exec();
}

File I/O

// Modern file operations
ErrorOr<void> read_config()
{
    auto file = TRY(Core::File::open("/etc/config.conf"sv,
        Core::File::OpenMode::Read));
    
    auto buffer = TRY(ByteBuffer::create_uninitialized(file->size()));
    TRY(file->read_until_filled(buffer));
    
    return {};
}

Process Management

// Spawn child process
ErrorOr<void> run_command()
{
    auto result = TRY(Core::command("ls", { "-la" }, {}));
    outln("Exit code: {}", result.exit_code);
    outln("Output: {}", result.output);
    return {};
}

LibGUI: GUI Framework

LibGUI provides the graphical user interface framework:

Widgets

  • Button, Label, TextBox, TextEditor
  • ListView, TableView, TreeView
  • ScrollBar, Slider, ProgressBar
  • MenuBar, Menu, MenuItem
  • Window, Dialog, MessageBox
  • Layout managers (Horizontal, Vertical, etc.)

Models

  • Model-View architecture
  • AbstractTableModel
  • SortingProxyModel
  • FileSystemModel
  • Custom model support

Example GUI Application

#include <LibGUI/Application.h>
#include <LibGUI/Button.h>
#include <LibGUI/Window.h>
#include <LibMain/Main.h>

ErrorOr<int> serenity_main(Main::Arguments arguments)
{
    auto app = TRY(GUI::Application::create(arguments));
    
    auto window = GUI::Window::construct();
    window->set_title("My App");
    window->resize(300, 200);
    
    auto button = window->set_main_widget<GUI::Button>("Click me!");
    button->on_click = [&](auto) {
        GUI::MessageBox::show(window, "Button clicked!", "Info");
    };
    
    window->show();
    return app->exec();
}

LibWeb: Web Engine

LibWeb is a complete browser engine built from scratch:
  • HTML5 compliant parser
  • Full DOM tree implementation
  • DOM Level 2 Events
  • Shadow DOM support
  • Custom elements
  • CSS3 selector engine
  • Flexbox layout
  • Grid layout (in progress)
  • Animations and transitions
  • Media queries
  • ES2021+ support
  • JIT compilation (in progress)
  • Garbage collection
  • Module system
  • Full standard library
  • WASM bytecode interpreter
  • Module loading
  • JavaScript integration
  • Growing specification support
  • Fetch API
  • XMLHttpRequest
  • Canvas 2D
  • WebGL (in progress)
  • Web Storage
  • Web Workers
Check compliance:

LibIPC: Inter-Process Communication

LibIPC provides type-safe IPC between processes:
// Define IPC interface in .ipc file
endpoint MyService
{
    SomeMethod(String data) => (i32 result)
    AnotherMethod() =|  // One-way message
}

// Generated client/server stubs handle serialization
See IPC Architecture for details.

Specialized Libraries

  • LibAudio: Audio codecs and playback
  • LibVideo: Video decoding
  • LibDSP: Digital signal processing
  • LibSynthesizer: Audio synthesis

Library Design Patterns

// Use static create() methods
class MyClass {
public:
    static ErrorOr<NonnullOwnPtr<MyClass>> create()
    {
        auto buffer = TRY(ByteBuffer::create_uninitialized(1024));
        auto instance = TRY(adopt_nonnull_own_or_enomem(
            new (nothrow) MyClass(move(buffer))));
        TRY(instance->initialize());
        return instance;
    }
    
private:
    MyClass(ByteBuffer buffer) : m_buffer(move(buffer)) {}
};

Cross-Library Dependencies

Libraries have clear dependency relationships:
AK (foundation)

LibC (C standard library)

LibCore (event loop, I/O)

├─→ LibGfx (graphics) ─→ LibGUI (widgets)
├─→ LibIPC (communication)
├─→ LibThreading (threads)
└─→ LibJS → LibWeb (browser engine)

Further Reading

IPC Details

Learn about inter-process communication

Event Loop

Understand the event system

Smart Pointers

Memory management patterns

Coding Patterns

Common patterns and idioms

Build docs developers (and LLMs) love