<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ng Song Guan on Medium]]></title>
        <description><![CDATA[Stories by Ng Song Guan on Medium]]></description>
        <link>https://medium.com/@sgn00?source=rss-214056e5b036------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pAiHAmPMytASHXSyQBaxJQ.jpeg</url>
            <title>Stories by Ng Song Guan on Medium</title>
            <link>https://medium.com/@sgn00?source=rss-214056e5b036------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:40:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sgn00/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Accelerating Linux Pipes with Solarflare Onload]]></title>
            <link>https://medium.com/@sgn00/accelerating-linux-pipes-with-solarflare-onload-9c17ba9eb36b?source=rss-214056e5b036------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c17ba9eb36b</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[low-latency]]></category>
            <category><![CDATA[hft]]></category>
            <category><![CDATA[kernel-bypass]]></category>
            <dc:creator><![CDATA[Ng Song Guan]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 12:33:31 GMT</pubDate>
            <atom:updated>2025-08-27T12:33:31.804Z</atom:updated>
            <content:encoded><![CDATA[<p>Kernel bypass is a technique used in applications that demand low-latency or high throughput. One of the industry standard kernel bypass technologies used in trading is <strong>Solarflare Onload, </strong>best known for it’s networking capabilities.</p><p>In this article, I’ll explore the use of Onload but in a less conventional setting: accelerating Linux pipes. Let’s begin by reviewing some key concepts.</p><h3>Why bypass the kernel?</h3><p>User applications typically rely on system calls provided by the OS to interact with hardware and other OS services. Each call transitions into kernel mode and executes kernel code, introducing latency, jitter, and potential throughput bottlenecks. The basic idea of kernel bypass is to shift this work into user space, allowing the application to execute the logic directly and, in some cases, communicate directly with hardware.</p><p>This can improve performance in three main ways:</p><ul><li><strong>Eliminating mode-switch overhead</strong> — Each syscall requires switching between user space and kernel space, validating arguments, and saving/restoring registers. Even a simple call can involve hundreds of instructions.</li><li><strong>Enabling application-specific optimization</strong> — Kernel code prioritizes fairness, portability, and security over raw performance. For specialized workloads like HFT, custom user-space implementations can be written and optimized in a more aggressive manner.</li><li><strong>Reducing data copies</strong> — Transferring data between user space and kernel space typically involves at least one copy in each direction. Bypassing the kernel minimizes these copies.</li></ul><h3>What is Solarflare Onload?</h3><p><a href="https://github.com/Xilinx-CNS/onload">Solarflare Onload</a> (also known as OpenOnload) is an open-source library that implements kernel bypass for Linux. The key strength of Onload is that it is very easy to integrate into an application. It exposes the BSD sockets API and interfaces of some glibc system call wrappers, so most applications can use it <strong>without</strong> requiring rewrites or even recompilation. From the app’s perspective, using Onload can be almost transparent. We will see how this works later.</p><p>For maximum performance in networking workloads, Onload has to be paired with specialized Solarflare NICs. But such hardware isn’t strictly required as Onload can fall back to the <a href="https://www.datadoghq.com/blog/xdp-intro/">Linux XDP (eXpress Data Path) interface</a> on standard Linux systems.</p><p>While Onload is best known for network acceleration, its kernel bypass techniques extends to other Linux facilities such as pipes.</p><h3><strong>Intro to Linux pipes</strong></h3><p>Pipes are an inter-process communication (IPC) mechanism which allows one process to send data to another via the kernel. A pipe establishes a data stream between processes and supports unidirectional communication, i.e. data flows in only one direction.</p><p>Internally, a pipe is backed by a <strong>kernel-managed circular buffer</strong> with two pointers: one for the read end and one for the write end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*iqyjIS3gZN9TJqVpAVcIJg.png" /></figure><p>At the API level, a pipe is created with the pipe() system call, which returns two file descriptors: one for reading and one for writing. Data is then transferred using the standard read() and write() syscalls. The flow looks like this:</p><ol><li>write() — process switches to kernel mode, copies data from user space to the kernel buffer.</li><li>read() — process switches to kernel mode, checks kernel buffer availability, and copies data from the kernel buffer back to user space.</li></ol><p>The example code below shows a parent process sending data to a child process.</p><pre>#include &lt;iostream&gt;<br>#include &lt;unistd.h&gt;    <br>#include &lt;cstring&gt;     <br>#include &lt;sys/wait.h&gt;  <br><br>int main() {<br>    int pipefd[2];<br>    pid_t pid;<br>    const char* message = &quot;Hello World&quot;;<br><br>    // Create a pipe<br>    if (pipe(pipefd) == -1) {<br>        perror(&quot;pipe() failed&quot;);<br>        return 1;<br>    }<br><br>    pid = fork();<br>    if (pid == -1) {<br>        perror(&quot;fork() failed&quot;);<br>        return 1;<br>    }<br><br>    if (pid == 0) {<br>        // --- Child process ---<br>        close(pipefd[1]);  // Close write end<br><br>        char buffer[128];<br>        ssize_t bytesRead = read(pipefd[0], buffer, sizeof(buffer) - 1);<br>        if (bytesRead &gt; 0) {<br>            buffer[bytesRead] = &#39;\0&#39;;<br>            std::cout &lt;&lt; &quot;Child received: &quot; &lt;&lt; buffer &lt;&lt; std::endl;<br>        }<br>        close(pipefd[0]);  // Close read end<br>    } else {<br>        // --- Parent process ---<br>        close(pipefd[0]);  // Close read end<br><br>        write(pipefd[1], message, strlen(message));<br>        close(pipefd[1]);  // Close write end<br><br>        waitpid(pid, nullptr, 0);<br>    }<br><br>    return 0;<br>}</pre><p>Note that each end of the pipe can be used in one of two modes:</p><p><strong>Blocking mode</strong></p><p>This is the default mode of pipes.</p><ul><li>write() blocks if the pipe is full.</li><li>read() blocks if the pipe is empty.</li></ul><p><strong>Non-blocking mode</strong></p><p>To make an end of a pipe non-blocking, you can use fcntl() with O_NONBLOCK flag.</p><ul><li>write() immediately returns if the pipe is full, with errno set to EAGAIN.</li><li>read() immediately returns if the pipe is empty, with errno set to EAGAIN.</li></ul><p>When using pipes, data never flows directly between processes; instead, every transfer goes through the kernel. As such, pipes are not the fastest IPC mechanism. Let’s see how Onload can help with this.</p><h3>Setting up and using Onload</h3><p>Setting up and using Onload is fairly simple and is well documented in their <a href="https://github.com/Xilinx-CNS/onload">README</a>.</p><p>Onload has two components: a <strong>kernel module</strong> and a <strong>user-space shared library</strong>. We run the provided scripts to build and install both components. Since we are not using a Solarflare NIC, we must also configure Onload for XDP.</p><p>Once installed, applications can be launched under Onload simply by prefixing with onload. For example:</p><pre>$ onload ./app</pre><p>The onload command <a href="https://github.com/Xilinx-CNS/onload/blob/master/scripts/onload">is a bash script</a> that uses the <a href="https://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick">LD_PRELOAD</a> mechanism to preload the Onload shared library (libonload.so) at runtime. LD_PRELOAD ensures the Onload library is loaded before any other, allowing it to override functions such as socket(), read(), write(), etc. Note that these functions are not syscalls themselves but glibc wrappers provided in libc.so, which then invoke the actual syscall instruction. When Onload is preloaded, Onload’s own accelerated implementations are called instead of the glibc wrappers, greatly reducing the number of syscalls required.</p><p>Onload can also accelerate pipes via the pipe(), read() and write() calls. With the theory covered, let’s move onto benchmarking.</p><h3><strong>Benchmark: Average Round Trip Time (RTT)</strong></h3><p>We benchmark Linux pipes using a ping-pong test which simulates two processes communicating with each other:</p><ul><li>Parent and child process pinned to separate, isolated cores and both spinning in a loop.</li><li>Communication happens over two pipes: the parent sends a 64-byte message to the child, and child immediately echoes it back to parent.</li><li>We record the time taken for 100,000 such messages to ping-pong and calculate the average RTT.</li></ul><p>The benchmark code can be found here: <a href="https://gist.github.com/sgn00/2314ec8055f8ddaae4981d969ec22ab8">https://gist.github.com/sgn00/2314ec8055f8ddaae4981d969ec22ab8</a></p><h4>Non-Blocking Mode</h4><p>We first test pipes in non-blocking mode, meaning the processes continuously poll the pipes for readiness and never block in the kernel.</p><p><strong>Baseline (non-blocking):</strong></p><pre>$ ./pingpong 100000 64 5 6<br>Mode: Non-blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 4885.12 ns (4.88512 us)</pre><p><strong>With Onload (non-blocking):</strong></p><pre>$ EF_PIPE=1 onload ./pingpong 100000 64 5 6<br>oo:pingpong[48018]: Using Onload 06d97cb8 2025-08-11 master  [0]<br>oo:pingpong[48018]: Copyright (c) 2002-2025 Advanced Micro Devices, Inc.<br>Mode: Non-blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 1037.18 ns (1.03718 us)</pre><p>There’s a ~5X reduction in average RTT when using Onload. To better understand the results, we run strace on the benchmark to see what syscalls are made in the parent process.</p><p>In the baseline run without Onload, we see roughly 100,000 read() and write() syscalls as expected.</p><pre># Baseline (non-blocking)<br>$ strace -c ./pingpong 100000 64 5 6<br>Mode: Non-blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 73653 ns (73.653 us)<br>% time     seconds  usecs/call     calls    errors syscall<br>------ ----------- ----------- --------- --------- ------------------<br> 70.10    2.215710     2215710         1           wait4<br> 15.05    0.475825           4    100004           read<br> 14.82    0.468431           4    100003           write<br>  0.01    0.000328          14        22           mmap<br>  0.01    0.000284         284         1           execve<br>&lt;snip...&gt;</pre><p>With Onload, we no longer see these large number of read() and write() syscalls.</p><pre># With Onload (non-blocking)<br>$ strace -c -- env EF_PIPE=1 onload ./pingpong 100000 64 5 6<br>oo:pingpong[48916]: Using Onload 06d97cb8 2025-08-11 master  [2]<br>oo:pingpong[48916]: Copyright (c) 2002-2025 Advanced Micro Devices, Inc.<br>Mode: Non-blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 1050.85 ns (1.05085 us)<br>% time     seconds  usecs/call     calls    errors syscall<br>------ ----------- ----------- --------- --------- ------------------<br> 49.68    0.061216        3600        17         7 wait4<br> 30.10    0.037082        1324        28           ioctl<br> 12.76    0.015717         178        88           mmap<br>  2.84    0.003496          85        41           munmap<br>  1.55    0.001905          29        65         2 close<br>  1.53    0.001890         189        10           clone<br>  0.48    0.000595         198         3           execve<br>  0.26    0.000318           7        41           openat<br>&lt;snip...&gt;</pre><p>This confirms the Onload library has moved the pipe communication into user space. We can model the Onload accelerated pipe as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*y0ut5ffJgFwY12-8kbGM4w.png" /></figure><p>Under the hood, Onload sets up a shared memory region in user space that both processes can access directly. The library intercepts pipe(), read(), and write() calls, and replaces kernel-buffered IPC with fast shared memory transfers.</p><h4>Blocking Mode</h4><p>Next, we run the benchmark with the pipes set in blocking mode.</p><p><strong>Baseline (blocking):</strong></p><pre>$ ./pingpong -b 100000 64 5 6<br>Mode: Blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 12402.2 ns (12.4022 us)</pre><p>The latency is already much higher in the baseline case. This is expected because, in blocking mode, the kernel can de-schedule a process that is waiting for data and later wake it up, adding context-switch and scheduling overhead.</p><p><strong>With Onload (blocking):</strong></p><pre>$ EF_PIPE=1 onload ./pingpong -b 100000 64 5 6<br>oo:pingpong[51590]: Using Onload 06d97cb8 2025-08-11 master  [4]<br>oo:pingpong[51590]: Copyright (c) 2002-2025 Advanced Micro Devices, Inc.<br>Mode: Blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 12607 ns (12.607 us)</pre><p>With Onload, there is no improvement. Even when using Onload, blocking mode reintroduces kernel involvement for scheduling and wake-ups, and the scheduling overhead dominates here.</p><p>To gain further insight, we run strace again.</p><pre># Baseline (blocking)<br>$ strace -c ./pingpong -b 100000 64 5 6<br>Mode: Blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 60759.3 ns (60.7593 us)<br>% time     seconds  usecs/call     calls    errors syscall<br>------ ----------- ----------- --------- --------- ------------------<br> 34.54    0.497284           4    100003           write<br> 33.39    0.480718      480718         1           wait4<br> 32.01    0.460864           4    100004           read<br>  0.02    0.000258         258         1           execve<br>  0.02    0.000251          11        22           mmap<br>  0.01    0.000090          11         8           mprotect<br>  0.00    0.000050           5        10           close<br>  0.00    0.000046           7         6           openat<br>&lt;snip...&gt;</pre><pre># With Onload (blocking)<br>$ strace -c --env EF_PIPE=1 onload ./pingpong -b 100000 64 5 6<br>oo:pingpong[52734]: Using Onload 06d97cb8 2025-08-11 master  [6]<br>oo:pingpong[52734]: Copyright (c) 2002-2025 Advanced Micro Devices, Inc.<br>Mode: Blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 62641.5 ns (62.6415 us)<br>% time     seconds  usecs/call     calls    errors syscall<br>------ ----------- ----------- --------- --------- ------------------<br> 53.59    0.973567           4    200016           ioctl<br> 45.02    0.817770       48104        17         7 wait4<br>  0.85    0.015528         196        79           mmap<br>  0.22    0.003966          99        40           munmap<br>  0.13    0.002284         228        10           clone<br>  0.12    0.002116          34        62         2 close<br>  0.02    0.000308         154         2           execve<br>  0.01    0.000238           6        38           openat<br>  0.01    0.000219           5        43           read<br>&lt;snip...&gt;</pre><p>Interestingly, we now have a large number of ioctl() syscalls when using Onload. I looked through the Onload code and found that the ioctl() calls are done to interact with the Onload kernel driver in order to implement the blocking mechanisms.</p><p>In blocking mode:</p><ul><li>write()<strong> :</strong> If a reader is blocking on read(), the Onload write() implementation makes an ioctl() syscall into the Onload kernel driver to wake the reader.</li><li>read()<strong> :</strong> If no data is available in the user space shared buffer, a read() triggers an ioctl() syscall to the Onload kernel driver, which blocks the reader in the kernel until data is ready.</li></ul><p>Updating our mental model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*pm-2N2ylPYeikqArdNu_tA.png" /></figure><h4>Tuning Onload Behavior</h4><p>Onload provides runtime configurations to control behavior of its user space implementations. For example, we can configure a blocking read() to spin in user space for a short time window before resorting to blocking.</p><p>This can be done with the following environment variables:</p><pre>$ EF_PIPE_RECV_SPIN=1 EF_SPIN_USEC=10 EF_PIPE=1 onload ./app</pre><p>Here:</p><ul><li>EF_PIPE_RECV_SPIN=1: Enables spin-waiting on pipe reads.</li><li>EF_SPIN_USEC=10: Specifies a 10 µs spin duration before blocking.</li></ul><p>We rerun the blocking mode ping-pong benchmark with these settings:</p><pre>$ EF_PIPE_RECV_SPIN=1 EF_SPIN_USEC=10 EF_PIPE=1 onload ./pingpong -b 100000 64 5 6<br>oo:pingpong[57222]: Using Onload 06d97cb8 2025-08-11 master  [7]<br>oo:pingpong[57222]: Copyright (c) 2002-2025 Advanced Micro Devices, Inc.<br>Mode: Blocking<br>Iterations: 100000, Msg: 64 bytes, Parent CPU: 5, Child CPU: 6<br>Average RTT: 939.935 ns (0.939935 us)</pre><p>The average RTT drops dramatically and is now comparable to Onload’s non-blocking performance. By spinning briefly in user space, we avoid costly context switches in cases where messages are expected to arrive quickly, effectively removing kernel scheduling from the critical path.</p><h3>Use cases of accelerated pipes</h3><p>Onload accelerated pipes can deliver near shared-memory IPC performance with minimal to no application changes. Because enabling them is as simple as prefixing a command with onload, they are a convenient, drop-in option for low-latency IPC.</p><p>We also saw that Onload pipes can be further customized to support spin-before-blocking behavior<strong>.</strong> This approach allows applications to briefly spin for incoming data to achieve lower latency, while still eventually blocking if no data arrives. This means that under low load, the process will block on the pipe and avoid unnecessary CPU usage, but when data is flowing frequently, the brief spin period helps minimize context switches and improves performance.</p><p>But for applications that require the lowest latency IPC and need more fine-grained control, custom lock-free queue implementations remain the best option.</p><h3>Solarflare Onload: beyond pipes</h3><p>While I’ve focused on accelerating Linux pipes, this is only a small part of what Solarflare Onload offers. Pipes make for a simple demonstration because no hardware is involved.</p><p>Networking acceleration is more complex as it involves the NIC. Onload uses the same LD_PRELOAD-based interception on networking functions. Normally, the NIC interacts with the Linux kernel networking stack but when paired with specialized Solarflare NIC hardware, Onload can bypass the kernel entirely, and communicate with the NIC directly from user space.</p><p>In addition to pipes and socket-related functions, Onload can also accelerate multiplexed I/O by intercepting poll, select and epoll function calls.</p><p>For more details and advanced tuning options, you can refer to the <a href="https://docs.amd.com/r/en-US/ug1586-onload-user/Overview?tocId=63rjgTN7r_Dmemajaps5rA">Onload User Guide</a>.</p><h4>References and Further Readings</h4><ul><li><a href="https://databento.com/microstructure/kernel-bypass">What is kernel bypass and how is it used in trading? | Databento Microstructure Guide</a></li><li><a href="https://technologyevangelist.co/2019/04/18/828ns-a-low-latency-legacy/">828ns - A Legacy of Low Latency</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c17ba9eb36b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into std::function]]></title>
            <link>https://medium.com/@sgn00/diving-into-std-function-d342e4b58ea7?source=rss-214056e5b036------2</link>
            <guid isPermaLink="false">https://medium.com/p/d342e4b58ea7</guid>
            <category><![CDATA[type-erasure]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Ng Song Guan]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 12:17:42 GMT</pubDate>
            <atom:updated>2025-08-15T21:40:45.161Z</atom:updated>
            <content:encoded><![CDATA[<p>In languages like Python and Rust, functions are <em>first-class</em> citizens: you can store them in variables, pass them around, and return them from other functions just like any other object. While C++ lacks native support for first-class functions, since C++11, the standard library has provided a close alternative: std::function.</p><p>std::function is a polymorphic function wrapper. It can hold any callable — lambdas, function pointers, or objects with operator() — as long as it matches the specified function signature. Once wrapped, the callable can be copied, moved, stored, and invoked.</p><p>In this article, I’ll look at when to use std::function, when to avoid it, and how such a magical abstraction works under the hood in a strongly-typed language like C++.</p><h3>std::function 101</h3><p>Let’s start with a few examples showcasing its flexibility:</p><pre>#include &lt;functional&gt;<br>#include &lt;string&gt;<br>#include &lt;cassert&gt;<br><br>int add(int x, int y) {<br>    return x + y;<br>}<br><br>struct AddT {<br>    int operator()(int x, int y) {<br>        return x + y;<br>    }<br>};<br><br><br>int main () {<br>    // Store function pointer<br>    std::function&lt;int(int, int)&gt; func1 = add;<br><br>    // Store lambda<br>    std::function&lt;int(int, int)&gt; func2 = [](int x, int y) {<br>        return x + y;<br>    };<br><br>    // Store a callable object<br>    AddT add_obj;<br>    std::function&lt;int(int, int)&gt; func3 = add_obj;<br><br>    // Invoke the std::function<br>    assert(func1(1, 2) == func2(1, 2));<br>    assert(func2(1, 2) == func3(1, 2));<br><br><br>    // Store lambda with captured variable<br>    int z = 0;<br>    std::function&lt;int(int, int)&gt; func4 = [z](int x, int y) {<br>        return x + y + z;<br>    };<br>}</pre><p>Although these callables are of different types, they all share the same interface:</p><pre>int(int, int) // Take in two int parameters and return an int.</pre><p>Curiously, we are able to store all of them into the same type: std::function&lt;int(int, int)&gt;. std::function erases their concrete type and exposes only this signature. This process is called <strong>type erasure</strong>. It allows you to treat completely different callable types in the same way.</p><p>For example, using std::function, we can store different callables together in a single container and invoke them.</p><pre>std::vector&lt;std::function&lt;int(int, int)&gt;&gt; store;<br>store.push_back(func1);<br>store.push_back(func2);<br>store.push_back(func3);<br>for (auto&amp; f : store) {<br>    std::cout &lt;&lt; f(1, 2) &lt;&lt; std::endl;<br>}</pre><h3>When to use std::function?</h3><p>By providing a uniform interface for different callables, std::function enables runtime polymorphism in a more expressive way. Here are two common examples where std::function shines.</p><h4>Producer-consumer task queue</h4><p>Unlike inheritance-based polymorphism, std::function works without requiring us to create class hierarchies.</p><p>Consider a producer-consumer setup where a producer is generating tasks for a consumer to execute. Traditionally, you might do this with a base class and virtual functions:</p><pre>// Base class for runtime polymorphism<br>struct Task {<br>    virtual ~Task() = default;<br>    virtual void execute() = 0;<br>};</pre><pre>// Derived class example<br>struct DoAbc : Task {<br>    void execute() override {<br>        std::cout &lt;&lt; &quot;abc&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>// Another derived class example<br>struct DoXyz : Task {<br>    void execute() override {<br>        std::cout &lt;&lt; &quot;xyz&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>// Create more derived classes as needed<br><br>// threadsafe queue that will be used by producer/consumer<br>threadsafe_queue&lt;std::unique_ptr&lt;Task&gt;&gt; queue;<br><br><br>// Producer thread pushes tasks<br>queue.push(std::make_unique&lt;DoAbc&gt;());<br>queue.push(std::make_unique&lt;DoXyz&gt;());<br><br>// Consumer thread executes tasks<br>auto task = queue.pop();<br>task-&gt;execute();</pre><p>This works, but every new task type requires a new derived class, adding boilerplate and mental overhead.</p><p>With std::function, the same design is reduced to:</p><pre>// threadsafe queue that will be used by producer/consumer<br>threadsafe_queue&lt;std::function&lt;void()&gt;&gt; queue;<br><br>// Producer thread pushes tasks<br>queue.push([](){ std::cout &lt;&lt; &quot;abc&quot; &lt;&lt; std::endl; });<br>queue.push([](){ std::cout &lt;&lt; &quot;xyz&quot; &lt;&lt; std::endl; });<br><br>// Consumer thread executes tasks<br>auto task = queue.pop();<br>task(); // Just call it</pre><p>This version is:</p><ul><li><strong>More concise — </strong>no extra class declarations.</li><li><strong>More expressive </strong>— the task’s logic is visible at the call site.</li><li><strong>More flexible </strong>— the<strong> </strong>lambdas can be easily adjusted and capture state if needed.</li></ul><h4>Event-driven code</h4><p>Another example is event-driven code<strong> </strong>where you register callbacks and trigger them when events occur. std::function allows us to store the callbacks in a single container.</p><p>Consider this event dispatcher, which invokes a registered callback when a file descriptor (fd) becomes ready:</p><pre>class EventDispatcher {<br>private:<br>    std::vector&lt;std::function&lt;void()&gt;&gt; callbacks;<br><br>public:<br>    EventDispatcher(int max_fd) : callbacks(max_fd) {}<br><br>    // Register a callback for fd<br>    void register_callback(int fd, std::function&lt;void()&gt; cb) {<br>        callbacks[fd] = std::move(cb);<br>    }<br><br>    // Handle event by calling registered callback for fd<br>    void handle_event(int fd) const {<br>        callbacks[fd]();<br>    }<br>};<br><br><br>void regular_function() {<br>    std::cout &lt;&lt; &quot;Callback from regular function&quot; &lt;&lt; std::endl;<br>}<br><br><br>int main() {<br>  EventDispatcher dispatcher(10);<br><br>  // Register the callbacks<br>  dispatcher.register_callback(5, regular_function);<br><br>  dispatcher.register_callback(6, [] {<br>      std::cout &lt;&lt; &quot;Callback from lambda&quot; &lt;&lt; std::endl;<br>  });<br><br>  // Assume some code calls the following<br>  dispatcher.handle_event(5);<br>  dispatcher.handle_event(6);<br>}</pre><p>Here, the callbacks come from both a normal function and a lambda, but the dispatcher is able to treat them uniformly thanks to std::function.</p><h3>When <em>not</em> to use std::function?</h3><p>std::function is powerful, but it is not a zero-cost abstraction. It adds runtime overhead in both performance and memory usage. Here are some cases where it is unnecessary.</p><h4>Only passing a callable as a parameter</h4><p>If you only need to accept a callable, invoke it immediately, and don’t need to store it, std::function is overkill.</p><p>Consider these two implementations of a run_task function:</p><pre>#include &lt;iostream&gt;<br>#include &lt;functional&gt;<br><br>// Template-based<br>template &lt;typename F&gt;<br>void run_task1(F&amp;&amp; f) {<br>    f();<br>}<br><br>// std::function-based<br>void run_task2(std::function&lt;void()&gt; f) {<br>    f();<br>}<br><br>int main() {<br>    run_task1([]() {<br>        std::cout &lt;&lt; &quot;Running task (templated)&quot; &lt;&lt; std::endl;<br>    });<br><br>    run_task2([]() {<br>        std::cout &lt;&lt; &quot;Running task (std::function)&quot; &lt;&lt; std::endl;<br>    });<br>}</pre><p>run_task1 is a function template that passes the lambda by its exact type. The compiler knows this type at compile time and the exact call destination so there’s no extra runtime cost here.</p><p>run_task2 wraps the lambda in a std::function&lt;void()&gt;, adding an extra layer of indirection and some runtime overhead¹ which we will discuss more later.</p><h4>No runtime polymorphism needed</h4><p>Even if you need to store a callable, if the callable’s type is fixed at compile time and never changes, you can store it directly without std::function.</p><p>Suppose you’re writing a task runner class that stores a single callable:</p><pre>template &lt;typename Callable&gt;<br>class TaskRunner {<br>public:<br>    TaskRunner(Callable c) : func_(std::move(c)) {}<br><br>    void run() {<br>        func_();<br>    }<br><br>private:<br>    Callable func_;<br>};<br><br>int main() {<br>    TaskRunner task_runner([]() {<br>        std::cout &lt;&lt; &quot;Callable called!&quot; &lt;&lt; std::endl;<br>    });<br>    task_runner.run();<br>}</pre><p>Here, we use a class template to store the callable as a member by its exact type. Since the type is known and doesn’t change, there’s no need for runtime polymorphism.</p><p>Now compare with a std::function version:</p><pre>class TaskRunner {<br>public:<br>    template &lt;typename Callable&gt;<br>    TaskRunner(Callable c) : func_(std::move(c)) {}<br><br>    void run() {<br>        func_();<br>    }<br><br>private:<br>    std::function&lt;void()&gt; func_;<br>};</pre><p>Functionally, this version is equivalent but we are paying for flexibility we do not use. The callable is set once during construction and never changes.</p><h4>What’s the overhead of std::function?</h4><p>The main cost of std::function is due to:</p><ul><li>Invoking a callable through std::function becomes an indirect call (which adds unnecessary overhead if your use case allows a statically dispatched function call).</li><li>std::function may dynamically allocate if the stored callable is large.</li></ul><p>Let’s take a look at how std::function is implemented to better understand these costs.</p><h3><strong>Implementing a simplified std::function</strong></h3><p>We’ll implement a minimal version of std::function, which I’ll call SimpleFunction. It should behave similarly to std::function:</p><pre>SimpleFunction&lt;int(int, int)&gt; my_func = [](int x, int y) {<br>    return x + y;<br>};</pre><p>To start, we know that the type signature of SimpleFunction must be templated on a return type R and an arbitrary number of argument types Args…. We can do this using template partial specialization:</p><pre>template &lt;typename&gt;<br>struct SimpleFunction;<br><br>template &lt;typename R, typename... Args&gt;<br>struct SimpleFunction&lt;R(Args...)&gt; {<br>    // To implement<br>};</pre><p>We also know what the interface of SimpleFunction looks like. It should:</p><ul><li>Accept any callable type F (function pointer, lambda, functor) in the constructor.</li><li>Provide operator() to invoke the stored callable.</li></ul><p>So we extend our skeleton:</p><pre>template &lt;typename&gt;<br>struct SimpleFunction;<br><br>template &lt;typename R, typename... Args&gt;<br>struct SimpleFunction&lt;R(Args...)&gt; {<br><br>    // Constructor<br>    // F is arbitrary callable type (function ptr, lambda, etc.)<br>    template &lt;typename F&gt;<br>    SimpleFunction(F&amp;&amp; f) {<br>      // To implement<br>    }<br><br>    R operator()(Args... args) const {<br>      // To implement<br>    }<br>};</pre><p>The challenge now is: how do we <strong>store</strong> this arbitrary type F (passed into the constructor in SimpleFunction) while still keeping F <strong>out</strong> of the type signature of SimpleFunction?</p><p>This is where <strong>type erasure </strong>comes into play.</p><p>We’ll implement type erasure using a virtual interface. We define an abstract base class called CallableBase. SimpleFunction will store a pointer to this base which hides a concrete implementation.</p><pre>template &lt;typename&gt;<br>struct SimpleFunction;<br><br>template &lt;typename R, typename... Args&gt;<br>struct SimpleFunction&lt;R(Args...)&gt; {<br><br>    // Abstract interface to aid in type erasure.<br>    // We will define a conrete struct to inherit from this later<br>    // which will store F.<br>    struct CallableBase {<br>        virtual R invoke(Args&amp;&amp;... args) = 0;<br>        virtual ~CallableBase() = default;<br>    };<br><br>    // Constructor<br>    // F is arbitrary callable type (function ptr, lambda, etc.)<br>    template &lt;typename F&gt;<br>    SimpleFunction(F&amp;&amp; f) {<br>      // To implement<br>    }<br>    <br>    R operator()(Args... args) const {<br>        return ptr_-&gt;invoke(std::forward&lt;Args&gt;(args)...);<br>    }<br><br>private:<br>    // F will be &#39;hidden&#39; in CallableBase behind this pointer.<br>    std::unique_ptr&lt;CallableBase&gt; ptr_;<br>};</pre><p>Now we define a concrete implementation CallableImpl&lt;F&gt; that inherits from CallableBase and stores the actual callable:</p><pre>#pragma once<br>#include &lt;utility&gt;<br>#include &lt;memory&gt;<br>#include &lt;stdexcept&gt;<br><br>template &lt;typename&gt;<br>struct SimpleFunction;<br><br>template &lt;typename R, typename... Args&gt;<br>struct SimpleFunction&lt;R(Args...)&gt; {<br><br>    // Abstract interface to aid in type erasure.<br>    struct CallableBase {<br>        virtual R invoke(Args&amp;&amp;... args) = 0;<br>        virtual ~CallableBase() = default;<br>    };<br><br>    // Concrete implementation of interface, stores F to be invoked later.<br>    template &lt;typename F&gt;<br>    struct CallableImpl : CallableBase {<br>        CallableImpl(F f) : functor(std::move(f)) {}<br><br>        R invoke(Args&amp;&amp;... args) override {<br>            return functor(std::forward&lt;Args&gt;(args)...);<br>        }<br>    private:<br>        F functor;<br>    };<br><br>    // Constructor<br>    // F is arbitrary callable type (function ptr, lambda, etc.)<br>    template &lt;typename F&gt;<br>    SimpleFunction(F&amp;&amp; f) {<br>        // Use std::decay_t to remove refs and cv qualifiers<br>        using DecayedF = std::decay_t&lt;F&gt;;<br>        // Create CallableImpl which is stored &#39;behind&#39; CallableBase<br>        ptr_ = std::make_unique&lt;CallableImpl&lt;DecayedF&gt;&gt;(std::forward&lt;F&gt;(f));<br>    }<br><br>    R operator()(Args... args) const {<br>        return ptr_-&gt;invoke(std::forward&lt;Args&gt;(args)...);<br>    }<br><br>    // TODO: Implement copy/move operations<br><br>private:<br>    std::unique_ptr&lt;CallableBase&gt; ptr_;<br>};</pre><p><strong>How it works</strong></p><p>When operator() is called:</p><ol><li>It calls the virtual invoke() method on CallableBase.</li><li>Dynamic dispatch calls CallableImpl&lt;F&gt;::invoke().</li><li>This invokes the stored callable F.</li></ol><p>That’s it, we’ve implemented the core idea of std::function. Using a virtual interface, we erased the type of the callable. This is similar to <a href="https://github.com/llvm-mirror/libcxx/blob/master/include/functional#L1617">Clang’s implementation (libc++)</a> of std::function.</p><h3>Runtime costs of SimpleFunction</h3><h4><strong>Heap allocation</strong></h4><p>In SimpleFunction, we<strong> </strong>use std::unique_ptr to store the callable F<strong>.</strong></p><pre>std::unique_ptr&lt;CallableBase&gt; ptr_;</pre><p>This means every SimpleFunction construction allocates heap memory to store the callable. This is necessary because the type F can be of arbitrary size:</p><ul><li>If F is a simple function pointer, it&#39;s usually 8 bytes on a 64-bit system.</li><li>But if F is a capturing lambda or a large function object, it can be much bigger.</li></ul><p>Real std::function implementations reduce heap allocations with Small Buffer Optimization (SBO) — similar to how<a href="https://devblogs.microsoft.com/oldnewthing/20230803-00/?p=108532"> Small String Optimization (SSO) works in </a><a href="https://devblogs.microsoft.com/oldnewthing/20230803-00/?p=108532">std::string</a>. If the callable F fits in a fixed-size internal buffer, it is stored in-place; otherwise, the implementation falls back to the heap.</p><p>I <a href="https://github.com/sgn00/sgfunction/blob/main/bench.cpp">wrote a small Google Benchmark</a> to demonstrate this behavior and to find the SBO threshold for my Clang compiler:</p><pre>--------------------------------------------------------------------------<br>Benchmark                Time             CPU   Iterations UserCounters...<br>--------------------------------------------------------------------------<br>BM_SBO_Size&lt;0&gt;        9.77 ns         9.75 ns     73438385 new_calls=0<br>BM_SBO_Size&lt;8&gt;        10.2 ns         10.2 ns     67428935 new_calls=0<br>BM_SBO_Size&lt;16&gt;       10.0 ns         10.0 ns     70541050 new_calls=0<br>BM_SBO_Size&lt;24&gt;       22.1 ns         22.1 ns     31923384 new_calls=1<br>BM_SBO_Size&lt;32&gt;       24.3 ns         24.2 ns     29114140 new_calls=1<br>BM_SBO_Size&lt;40&gt;       23.8 ns         23.8 ns     29190871 new_calls=1</pre><p>Sweeping across lambda capture sizes shows a jump in latency of std::function construction (and one heap allocation) when going from 16 bytes to 24 bytes captures. This matches the <a href="https://github.com/llvm-mirror/libcxx/blob/master/include/functional#L1934">16 bytes SBO buffer size</a> we can see in the code of Clang’s std::function implementation.</p><h4>Virtual dispatch cost</h4><p>operator() in SimpleFunction uses virtual function dispatch:</p><pre>R operator()(Args... args) const {<br>    return ptr_-&gt;invoke(std::forward&lt;Args&gt;(args)...);<br>}</pre><p>A virtual function call is <a href="https://www.linkedin.com/pulse/snails-tale-virtual-function-calls-sarthak-sehgal-bgxac/">an <strong>indirect call</strong> through a vtable</a>. Since the target function isn’t known at compile time, the compiler generally can’t inline it², which reduces opportunities for other optimizations. Indirect calls also increase the risk of instruction cache misses and CPU branch mis-predictions at runtime.</p><p>By contrast, statically dispatched calls (where the destination is known at compile time) allows for more optimizations by the compiler and is easier on the CPU.</p><h3>Alternative SimpleFunction implementation</h3><p>Type erasure in C++ doesn’t have to use virtual functions and inheritance. We can also implement it using the C-style method — storing the callable as a void*.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*I5pJ9-92xPGwldfIsW4f4A.png" /></figure><p>The general idea is we store:</p><ul><li>A void* pointing to the callable.</li><li>An invoker_ function pointer that knows how to cast this void* back to the original type and call it.</li></ul><p>We start with a basic skeleton:</p><pre>template&lt;typename&gt;<br>struct SimpleFunction;<br><br>template&lt;typename R, typename... Args&gt;<br>struct SimpleFunction&lt;R(Args...)&gt; {<br><br>    template&lt;typename F&gt;<br>    SimpleFunction(F&amp;&amp; f) {<br>        // To implement<br>        // Store F as a void* in ptr_<br>        // Set up invoker_ which knows how to call ptr_<br>    }<br><br>    R operator()(Args... args) const {<br>         // Call the stored F via invoker_<br>        return invoker_(ptr_, std::forward&lt;Args&gt;(args)...);<br>    }<br><br>private:<br>    void* ptr_ = nullptr;<br>    <br>    using InvokerFn = R(*)(void*, Args&amp;&amp;...);<br>    InvokerFn invoker_ = nullptr;<br>};</pre><p>We now implement the constructor to store F on the heap and set the invoker_ function pointer:</p><pre>template &lt;typename F&gt;<br>SimpleFunction(F&amp;&amp; f) {<br>    using DecayedF = std::decay_t&lt;F&gt;;<br>    ptr_ = new DecayedF(std::forward&lt;F&gt;(f));<br><br>    invoker_ = [](void* ptr, Args&amp;&amp;... args) -&gt; R {<br>        return (*static_cast&lt;DecayedF*&gt;(ptr))(std::forward&lt;Args&gt;(args)...);<br>    };<br>}</pre><p>We get type erasure by storing F via void* ptr_ , so F once again doesn’t appear in SimpleFunction’s type signature.</p><p>Finally, we also add a deleter function pointer to free the heap memory we allocated.</p><p>Full example:</p><pre>template&lt;typename&gt;<br>struct SimpleFunction;<br><br>template&lt;typename R, typename... Args&gt;<br>struct SimpleFunction&lt;R(Args...)&gt; {<br><br>    template&lt;typename F&gt;<br>    SimpleFunction(F&amp;&amp; f) {<br>        using DecayedF = std::decay_t&lt;F&gt;;<br>        // Allocate space for F<br>        ptr_ = new DecayedF(std::forward&lt;F&gt;(f));<br><br>        // Set up invoker_<br>        invoker_ = [](void* ptr, Args&amp;&amp;... args) -&gt; R {<br>            return (*static_cast&lt;DecayedF*&gt;(ptr))(std::forward&lt;Args&gt;(args)...);<br>        };<br><br>        // Set up deleter_<br>        deleter_ = [](void* ptr) {<br>            delete static_cast&lt;DecayedF*&gt;(ptr);<br>        };<br>    }<br><br>    ~SimpleFunction() {<br>        if (ptr_ &amp;&amp; deleter_) {<br>            deleter_(ptr_);<br>        }<br>    }<br><br>    // TODO: Implement copy and move operations<br><br>    R operator()(Args... args) const {<br>        return invoker_(ptr_, std::forward&lt;Args&gt;(args)...);<br>    }<br><br>private:<br>    void* ptr_ = nullptr;<br><br>    using InvokerFn = R(*)(void*, Args&amp;&amp;...);<br>    using DeleterFn = void(*)(void*);<br>    InvokerFn invoker_ = nullptr;<br>    DeleterFn deleter_ = nullptr;<br>};</pre><p>This method avoids virtual functions, but we are still performing indirect calls. In practice, both approaches are very close in performance. <a href="https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/std_function.h">GCC’s<strong> </strong>implementation (libstdc++)</a> uses this style of type erasure for std::function.</p><h3>In-place std::function</h3><p>Our earlier SimpleFunction implementations always perform a heap allocation to store the callable. std::function may avoid this via SBO, but it can still allocate dynamically if the callable is too large.</p><p>In performance-critical code, <a href="https://medium.com/@sgn00/high-performance-memory-management-arena-allocators-c685c81ee338">any dynamic allocation can be too expensive</a>. For such use cases, we can eliminate it entirely by storing the callable <strong>in-place</strong> in a fixed-size buffer, and never allow heap fallback. If the callable is too large, compilation simply fails.</p><p>Here’s the adjusted SimpleFunction which uses in-place storage:</p><pre>template&lt;typename, size_t = 1024&gt;<br>struct SimpleFunction;<br><br>template&lt;typename R, typename... Args, size_t CAPACITY&gt;<br>struct SimpleFunction&lt;R(Args...), CAPACITY&gt; {<br><br>    template&lt;typename F&gt;<br>    SimpleFunction(F&amp;&amp; f) {<br>        using DecayedF = std::decay_t&lt;F&gt;;<br>        // Check that our buffer can fit F at compile time<br>        static_assert(sizeof(DecayedF) &lt;= BUF_CAP, &quot;Callable too large for in-place buffer&quot;);<br>        static_assert(alignof(DecayedF) &lt;= alignof(std::max_align_t), &quot;Alignment mismatch&quot;);<br>        // placement new into our buffer<br>        ptr_ = new (buffer_) DecayedF(std::forward&lt;F&gt;(f));<br><br>        invoker_ = [](void* ptr, Args&amp;&amp;... args) -&gt; R {<br>            return (*static_cast&lt;DecayedF*&gt;(ptr))(std::forward&lt;Args&gt;(args)...);<br>        };<br><br>        deleter_ = [](void* ptr) {<br>            static_cast&lt;DecayedF*&gt;(ptr)-&gt;~DecayedF();<br>        };<br>    }<br><br>    ~SimpleFunction() {<br>        if (ptr_ &amp;&amp; deleter_) {<br>            // call destructor<br>            deleter_(ptr_);<br>        }<br>    }<br><br>    // TODO: Implement copy and move operations<br><br>    R operator()(Args... args) const {<br>        if (!invoker_) {<br>            throw std::runtime_error(&quot;bad function call&quot;);<br>        }<br>        return invoker_(ptr_, std::forward&lt;Args&gt;(args)...);<br>    }<br><br>private:<br>    void* ptr_ = nullptr;<br><br>    using InvokerFn = R(*)(void*, Args&amp;&amp;...);<br>    using DeleterFn = void(*)(void*);<br>    InvokerFn invoker_ = nullptr;<br>    DeleterFn deleter_ = nullptr;<br><br>    static constexpr size_t BUF_CAP = CAPACITY - sizeof(ptr_) <br>                                 - sizeof(invoker_) - sizeof(deleter_);<br>    // fixed-size inplace buffer<br>    alignas(std::max_align_t) char buffer_[BUF_CAP];<br>};</pre><p>Example usage:</p><pre>void func() {<br>  SimpleFunction&lt;void(), 100&gt; inplace_f = []{<br>      do_something();<br>  });<br>  inplace_f();<br>}</pre><h4>Notes</h4><ul><li>This approach completely avoids heap allocation.</li><li>The fixed-size buffer means you must choose CAPACITY carefully to suit your use case.</li><li>If the callable is too large to fit in-place, you get a compile-time error via the static_assert.</li></ul><p>There exists <a href="https://github.com/WG21-SG14/SG14/blob/master/SG14/inplace_function.h">stdext::inplace_function</a>, which is a proposed standard extension providing similar guarantees with richer functionality.</p><p>To sum up, std::function is a type-erased, owning wrapper for any callable, offering flexibility at the cost of some performance. We’ve seen some possible design choices but there are actually <a href="https://quuxplusone.github.io/blog/2019/03/27/design-space-for-std-function/">many more</a>. Looking ahead, the C++ standard library is adding more callable wrappers to cover different use cases:</p><ul><li>std::function_ref (C++26) is a non-owning, lightweight reference to an existing callable, analogous to std::string_view vs std::string .</li><li>std::move_only_function (C++23) and std::copyable_function (C++26). These gives developers finer control over performance and ownership semantics.</li></ul><p>My complete SimpleFunction implementations with copy/move operations support can be found here: <a href="https://github.com/sgn00/sgfunction">https://github.com/sgn00/sgfunction</a>.</p><p>[1] The compiler can inline and optimize std::function in some cases. In this simple example, when compiling with Clang on -O3, <a href="https://godbolt.org/z/z3PsM55M9">both run_task functions produced similar assembly</a>.</p><p>[2] In some cases, the compiler can <a href="https://www.hudsonrivertrading.com/hrtbeat/optimising-compiler-performance-a-case-for-devirtualisation/">devirtualize</a> virtual function calls, eliminating their runtime overhead.</p><h4>References and Further Readings</h4><ul><li><a href="https://quuxplusone.github.io/blog/2019/03/18/what-is-type-erasure/">What is Type Erasure?</a></li><li><a href="https://stackoverflow.com/questions/18453145/how-is-stdfunction-implemented">How is std::function implemented?</a></li><li><a href="https://github.com/rigtorp/Function">GitHub - rigtorp/Function: Heap allocation free version of C++11 std::function</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*v_yMfD72apRGOEswm_5InA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d342e4b58ea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High Performance Memory Management: Arena Allocators]]></title>
            <link>https://medium.com/@sgn00/high-performance-memory-management-arena-allocators-c685c81ee338?source=rss-214056e5b036------2</link>
            <guid isPermaLink="false">https://medium.com/p/c685c81ee338</guid>
            <category><![CDATA[hft]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Ng Song Guan]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 12:03:57 GMT</pubDate>
            <atom:updated>2025-07-30T12:03:57.650Z</atom:updated>
            <content:encoded><![CDATA[<p>In performance-critical applications, even small inefficiencies in memory management can be intolerable. Unlike languages such as Java and Python, which rely on garbage collection, C++ gives you precise control over memory allocation and deallocation, making it a popular choice in these domains.</p><p>In this article, I’ll be discussing memory management using arena allocators. I’ll show you how they work, how to write one in C++, and how they can boost performance. But first, let’s take a quick look at how memory allocation typically works in C++.</p><h3><strong>C++ Memory Management 101</strong></h3><p>When you create objects in C++, you generally have two choices based on their storage duration:</p><ul><li><strong>Automatic Storage (Stack Allocation)</strong>: Objects are allocated on the stack, and their lifetimes are tied to their scope.</li><li><strong>Dynamic Storage (Heap Allocation)</strong>: Objects are allocated on the free store (heap), and they survive beyond their creation scope until explicitly deallocated.</li></ul><p>Consider a simple struct Foo.</p><pre>struct Foo {<br>  int x;<br>  int y;<br>};</pre><p>Here’s how you can allocate it:</p><pre>void func() {<br>    /* Stack allocation: cheap and automatic. */<br>    // f1 is destroyed automatically at the end of this scope.<br>    Foo f1{3, 4};<br><br>    /* Heap allocation: flexible but more overhead. */<br>    // f2 persists after the function returns, but requires manual deletion.<br>    Foo* f2 = new Foo{3, 4};  // &#39;old&#39; style<br><br>    // Modern C++ with RAII: automatic cleanup via smart pointer.<br>    std::unique_ptr&lt;Foo&gt; f3 = std::make_unique&lt;Foo&gt;(3, 4);<br>    // f3 will automatically free the heap memory when it goes out of scope.<br><br>    // STL Containers may manage dynamic allocations internally.<br>    // Example: std::vector stores objects on the heap.<br>    std::vector&lt;Foo&gt; vec;<br>    vec.push_back(Foo{3, 4});  // Allocates Foo inside vector&#39;s heap buffer<br>    vec.push_back(Foo{5, 6});  // Vector resizes heap buffer as needed.<br>    // vec and its contents are cleaned up <br>    // automatically when going out of scope.<br>}</pre><p>Stack allocation is very efficient because it simply adjusts the stack pointer register (e.g., decrementing rsp on x86). In contrast, dynamic heap allocation has more overhead. The new keyword invokes the system’s allocator, typically malloc() on Linux.</p><p><strong>What does malloc() actually do?</strong></p><p>malloc() is a library function provided by glibc on Linux¹ (not a system call). It serves as a general-purpose memory allocator, designed to handle diverse allocation patterns across threads and programs. Its implementation is complex, spanning thousands of lines of code. At a high level, a typical call to malloc() involves the following steps:</p><ol><li>Search the free list for an existing block that fits the requested size.</li><li>If none is found, attempt to carve a new block from the available heap space.</li><li>If the heap is too small, call the brk() system call to extend the program’s heap.</li><li>For large allocations, bypass the heap and use mmap() to request memory directly from the OS.</li></ol><p>Although malloc() has been written in an optimized manner, its general-purpose nature makes it slower and unpredictable as compared to stack allocation. The time it takes can vary depending on the heap state. It might involve scanning free lists or even triggering system calls, which add latency due to context switching. Such variability is unacceptable in many high-performance workloads².</p><p>Additionally, every call to malloc() should eventually be paired with a corresponding free() call. But free() also introduces overhead: it must update bookkeeping structures and return the block to the internal free list.</p><p>Another issue is memory fragmentation. malloc() can often scatter allocations across the address space. In workloads which involves allocating many small objects that are accessed in rapid succession, this hurts cache locality as the objects have poor spatial proximity.</p><p>To improve performance, we want to minimize the number of individual malloc() calls. This is where arena allocation comes in.</p><h3><strong>What is an Arena?</strong></h3><p>An arena is actually very simple in concept — we pre-allocate (typically using a single malloc()) a big block of memory upfront, and then perform subsequent allocations from this block.</p><p>The type of arena I’ll be discussing is also known as a linear allocator or bump allocator. It works by maintaining a current offset within the pre-allocated block, which initially starts at 0. Every time an object is allocated, the arena:</p><ol><li>Returns a pointer to the current offset</li><li>Increments (‘bumps’) this offset by the size of the allocated object</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*zBgWCS-8FtxHxYIecZ03dw.png" /></figure><p>Individual deallocations are not supported in arenas. Instead, the entire block of memory is freed at once, similar to tearing down the entire stack frame at the end of a function call.</p><p>Let’s see how we can implement an arena in C++.</p><pre>#pragma once<br>#include &lt;cstddef&gt;<br>#include &lt;new&gt;<br>#include &lt;memory&gt;<br><br>class Arena {<br><br>public:<br>    // Constructor: allocate a raw memory block of given size<br>    explicit Arena(std::size_t size)<br>        : buffer_(static_cast&lt;char*&gt;(::operator new(size))), <br>                    capacity_(size), offset_(0) {}<br><br>    // Destructor: free the memory block<br>    ~Arena() {<br>        ::operator delete(buffer_);<br>    }<br><br>    // Allocate memory of `size` bytes with specified `alignment`<br>    void* allocate(std::size_t size, std::size_t alignment) {<br>        char* current_ptr = buffer_ + offset_;<br>        std::size_t space = capacity_ - offset_;<br>        void* aligned_ptr = current_ptr;<br><br>        // Align the ptr to the specified alignment<br>        if (std::align(alignment, size, aligned_ptr, space) == nullptr) {<br>            throw std::bad_alloc();<br>        }<br><br>        // Bump the offset of the arena<br>        offset_ = static_cast&lt;char*&gt;(aligned_ptr) - buffer_ + size;<br><br>        return aligned_ptr;<br>    }<br><br>    // Reset arena to reuse the memory block from the start<br>    void reset() {<br>        offset_ = 0;<br>    }<br><br>    // Non-copyable, non-movable type<br>    Arena(const Arena&amp;) = delete;<br>    Arena(Arena&amp;&amp;) = delete;<br><br>private:<br>    char* buffer_;           // Start of the allocated memory block<br>    std::size_t capacity_;   // Total size of the block<br>    std::size_t offset_;     // Current allocation offset<br><br>};</pre><p><strong>Characteristics of this arena:</strong></p><ul><li>There’s no deallocate() function. We cannot deallocate individually.</li><li>The reset() function sets the internal offset back to 0, invalidating all previous allocations and allowing the arena buffer to be reused from the start.</li><li>The entire block of memory is automatically freed when the Arena object goes out of scope.</li><li>During allocation, we use std::align to ensure proper <a href="https://learn.microsoft.com/en-us/cpp/cpp/alignment-cpp-declarations?view=msvc-170">alignment</a>.</li></ul><p>Example usage:</p><pre>void parent_func() {<br>  Arena arena(1024); // Create arena with 1024 bytes<br>  func(arena);<br>  // Memory is automatically freed when `arena` goes out of scope<br>}<br><br>void func(Arena&amp; arena) {<br>  // This replaces use of malloc<br>  // auto* ptr = malloc(sizeof(Foo));<br>  auto* ptr = arena.allocate(sizeof(Foo), alignof(Foo));<br>  auto* foo_ptr = new (ptr) Foo({3, 4});<br>}</pre><p>In this example, we allocate raw memory from the arena, and then use placement new to construct Foo in-place. It’s important to remember that object creation in C++ is a two-step process:</p><ol><li>Allocate raw memory.</li><li>Construct the object.</li></ol><p>Normally, this is abstracted away by the new keyword or std::make_unique, but here we handle them separately.</p><p>From this implementation, the advantages of arenas should also be quite clear:</p><ul><li>Each allocation is fast and deterministic as it is just a simple pointer bump with no additional bookkeeping or syscall overhead (similar to stack allocation).</li><li>Potentially better cache locality due to allocating from a contiguous memory block.</li><li>Cheap deallocation by freeing the entire block at once.</li></ul><p>The tradeoff is flexibility. You can’t free individual objects, so all allocations should have similar lifetimes.</p><p><strong>Additional notes on </strong>Arena<strong> class</strong></p><ul><li>It uses a minimalist C-style design. Arena only handles raw memory allocation. Users must handle the construction and destruction of objects. This makes it best for trivially destructible types (e.g., PODs) where no explicit cleanup is required. Later, I’ll show how we can write a more object-oriented C++ arena.</li><li>It is not thread-safe. This implementation can only be used in single-threaded contexts unless you add some form of synchronization mechanism.</li><li>Arena uses <a href="https://en.cppreference.com/w/cpp/memory/new/operator_new">operator new</a> for allocating initial block of memory. For low-latency systems, you can use mmap() with MAP_POPULATE instead to ensure memory is backed by physical pages upfront. This reduces runtime page faults at the cost of higher initial memory commitment, trading space for predictability.</li></ul><h3><strong>Integrating Arena with STL container (custom allocator)</strong></h3><p>By default, STL containers use std::allocator, which relies on operator new (and ultimately malloc()) for each dynamic allocation. We can write a custom allocator that uses Arena to allocate instead and use this in STL containers.</p><p>Here’s a minimal example of a custom stateful allocator that delegates to our Arena class:</p><pre>#pragma once<br>#include &quot;arena.hpp&quot;<br><br>// Implement requirements of a custom allocator class<br>// https://en.cppreference.com/w/cpp/named_req/Allocator.html<br>template &lt;typename T&gt;<br>class ArenaAllocator {<br><br>public:<br>    using value_type = T;<br><br>    explicit ArenaAllocator(Arena* arena) noexcept : arena_(arena) {}<br><br>    template &lt;typename U&gt;<br>    ArenaAllocator(const ArenaAllocator&lt;U&gt;&amp; other) noexcept : arena_(other.arena_) {}<br><br>    template &lt;typename U&gt;<br>    friend class ArenaAllocator;<br><br>    T* allocate(std::size_t n) {<br>        return static_cast&lt;T*&gt;(arena_-&gt;allocate(n * sizeof(T), alignof(T)));<br>    }<br><br>    void deallocate(T* /*p*/, std::size_t /*n*/) noexcept {<br>        // No-op; arena manages memory lifetime<br>    }<br><br>    bool operator==(const ArenaAllocator&amp; other) const noexcept {<br>        return arena_ == other.arena_;<br>    }<br><br>    bool operator!=(const ArenaAllocator&amp; other) const noexcept {<br>        return !(*this == other);<br>    }<br><br>private:<br>    Arena* arena_;<br>};</pre><p>We can now use this allocator with an STL container, such as std::unordered_map:</p><pre>int main() {<br>    Arena arena(1024);<br>    ArenaAllocator&lt;std::pair&lt;const int,int&gt;&gt; my_alloc(&amp;arena);<br><br>    // std::unordered_map using our ArenaAllocator<br>    std::unordered_map&lt;int,int,<br>        std::hash&lt;int&gt;,<br>        std::equal_to&lt;int&gt;,<br>        ArenaAllocator&lt;std::pair&lt;const int,int&gt;&gt;<br>    &gt; umap(0, std::hash&lt;int&gt;(), std::equal_to&lt;int&gt;(), my_alloc);<br><br>    for (int i = 0; i &lt; 12; i++) {<br>        umap[i] = i;<br>    }<br>}</pre><p>std::unordered_map is <a href="https://devblogs.microsoft.com/oldnewthing/20230808-00/?p=108572">implemented as a separate-chaining hash table</a>. On insertion of a new element, it always needs to dynamically allocate a new node via operator new when using the default std::allocator. With our custom ArenaAllocator, we bypass dynamic allocations, and just allocate these new nodes directly from our arena. This improves performance.</p><p>To prove this, I wrote a simple micro-benchmark using <a href="https://github.com/google/benchmark?tab=readme-ov-file#usage">google benchmark</a>, benchmarking time taken to insert elements into std::unordered_map. The benchmark code can be found here: <a href="https://github.com/sgn00/sgarena/blob/main/bench.cpp">https://github.com/sgn00/sgarena/blob/main/bench.cpp</a></p><pre>----------------------------------------------------------------------------<br>Benchmark                                  Time             CPU   Iterations<br>----------------------------------------------------------------------------<br>BM_UnorderedMap_Insert/100              4661 ns         4653 ns       152424<br>BM_UnorderedMap_Insert/1000            42135 ns        42062 ns        16704<br>BM_UnorderedMap_Insert/10000          448031 ns       447597 ns         1579<br>BM_ArenaUnorderedMap_Insert/100         2823 ns         2821 ns       248437<br>BM_ArenaUnorderedMap_Insert/1000       25477 ns        25445 ns        27417<br>BM_ArenaUnorderedMap_Insert/10000     274952 ns       274785 ns         2587</pre><p>The arena-backed version consistently outperforms the version using the default allocator. This is an easy enhancement to std::unordered_map that can be useful in applications where performance matters. That said, in high performance scenarios, it may be worth considering <a href="https://jacksonallan.github.io/c_cpp_hash_tables_benchmark/">an alternative hash table implementation</a> altogether as std::unordered_map is known to be convenient, but not the fastest.</p><h3><strong>A More User Friendly C++ Arena</strong></h3><p>As I mentioned, our current Arena class is rather low level and C-style as it only handles raw memory allocation, leaving object construction and destruction entirely to the caller. This is fine for trivially destructible types, but we can do better in C++.</p><p>To support object construction is simple, we just need to move the placement new call into the arena‘s API. The challenge is destruction — we need to call the destructors of all constructed objects automatically when the arena is destroyed. To solve this, we will need to save the destructors in a list. But where do we get the space for this?</p><p>From the arena itself! We can create a new node type which saves the destructor to be called, and these nodes are also allocated in the arena.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*-eRHl7jf69jyF1wqGH2lQA.png" /><figcaption>Arena with extra linked list of destructor nodes embedded</figcaption></figure><p>As shown in the diagram, the destruct nodes form a reversed linked list. When the arena is destroyed, the arena’s destructor will walk this list to call destructors opposite to the order of construction.</p><p>Here is our new arena implementation:</p><pre>#pragma once<br>#include &lt;cstddef&gt;<br>#include &lt;memory&gt;<br>#include &lt;new&gt;<br>#include &lt;type_traits&gt;<br><br>class ObjArena {<br><br>public:<br>    explicit ObjArena(std::size_t size)<br>        : buffer_(static_cast&lt;char*&gt;(::operator new(size))),<br>            capacity_(size), offset_(0) {}<br><br>    ~ObjArena() {<br>        call_destructors();<br>        ::operator delete(buffer_);<br>    }<br><br>    template &lt;typename T, typename... Args&gt;<br>    T* create(Args&amp;&amp;... args) {<br>        // Allocate space for obj<br>        auto [ptr, new_offset] = allocate(offset_, sizeof(T), alignof(T));<br><br>        if constexpr (std::is_trivially_destructible_v&lt;T&gt;) {<br>            // If T has trivial destructor, then just construct object <br>            // as per normal<br>            T* obj = new (ptr) T(std::forward&lt;Args&gt;(args)...);<br>            offset_ = new_offset;<br>            return obj;<br>        } else {<br>            // Else we need to create a DestructNode, <br>            // to store destructor to be called later<br><br>            // Allocate space for DestructNode<br>            auto [dnode_ptr, final_offset] = allocate(new_offset, <br>                  sizeof(DestructNode), alignof(DestructNode));<br><br>            // Now construct T only after successful allocation<br>            T* obj = new (ptr) T(std::forward&lt;Args&gt;(args)...);<br><br>            auto dtor_call = [](void* p) {<br>                static_cast&lt;T*&gt;(p)-&gt;~T();<br>            };<br>            DestructNode* new_node = new (dnode_ptr) DestructNode{dtor_call, <br>                                                          tail_, obj};<br>            tail_ = new_node;<br><br>            // Commit offset after successful allocation and construction<br>            offset_ = final_offset;<br>            return obj;<br>        }<br>    }<br><br>    void reset() {<br>        call_destructors();<br>        offset_ = 0;<br>    }<br><br>    // Non-copyable, non-movable type<br>    ObjArena(const ObjArena&amp;) = delete;<br>    ObjArena(ObjArena&amp;&amp;) = delete;<br><br>private:<br>    struct DestructNode {<br>        void (*dtor)(void*);<br>        DestructNode* prev;<br>        void* obj;<br>    };<br><br>    char* buffer_;<br>    std::size_t capacity_;<br>    std::size_t offset_;<br>    DestructNode* tail_ = nullptr;<br><br>    void call_destructors() {<br>        while (tail_) {<br>            tail_-&gt;dtor(tail_-&gt;obj);<br>            tail_ = tail_-&gt;prev;<br>        }<br>    }<br><br>    // Check if we have memory of `size` bytes with specified `alignment`<br>    std::pair&lt;void*, std::size_t&gt; allocate(std::size_t curr_offset,<br>                    std::size_t size, std::size_t alignment) {<br>        char* current_ptr = buffer_ + curr_offset;<br>        std::size_t space = capacity_ - curr_offset;<br>        void* aligned_ptr = current_ptr;<br><br>        // Align the ptr to the specified alignment<br>        if (std::align(alignment, size, aligned_ptr, space) == nullptr) {<br>            throw std::bad_alloc();<br>        }<br><br>        auto new_offset = static_cast&lt;char*&gt;(aligned_ptr) - buffer_ + size;<br><br>        return {aligned_ptr, new_offset};<br>    }<br>};</pre><p>Example Usage:</p><pre>struct Bar {<br>    Bar();<br>    ~Bar() {<br>        std::cout &lt;&lt; &quot;non-trivial dtor&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>void func() {<br>    ObjArena arena(1024);<br>    Bar* bar = arena.create&lt;Bar&gt;();<br>    std::cout &lt;&lt; &quot;End of scope&quot; &lt;&lt; std::endl;<br>    /*<br>    Prints:<br>    End of scope<br>    non-trivial dtor<br>    */<br>}</pre><p>Our ObjArena supports any type T, creating destructor nodes only for those with non-trivial destructors. However, there are tradeoffs to supporting non-trivial destructors. Resetting or destroying the arena is now <em>O(n) </em>in time complexity, as it calls every destructor individually.</p><p>Note that there are some changes in ObjArena&#39;s allocate() compared to Arena as we want ObjArena&#39;s create() function to be strong <a href="https://www.stroustrup.com/except.pdf">exception-safe</a>. If allocation or construction throws exceptions, the arena’s offset isn’t updated, preventing inconsistent state.</p><h3>Running out of memory in an arena</h3><p>Our current arena allocates a fixed block of memory upfront during initialization, so it has limited space. If we try to allocate beyond this limit, the arena throws an error. This is in contrast with malloc(), which <a href="https://news.ycombinator.com/item?id=7541650">won’t fail</a> in most cases on a Linux 64 bit platform. There are several ways to handle running out of space in the arena:</p><ol><li><strong>Fail </strong>— Either throw an exception or return a nullptr (our current way). It’s not a bad option. If you know your workload’s memory requirements in advance, there’s no need to overcomplicate things. Let the caller treat this as an exceptional scenario. Also, due to the virtual memory system and demand paging, on most 64 bit platforms, the OS allows us to allocate a very large virtual memory block upfront without issue.</li><li><strong>Grow the arena</strong> —Instead of a single block of memory, the arena can manage multiple blocks, allocating new ones as needed and chaining them like a linked list. This is similar to the internal implementation of std::deque. It adds complexity but removes the fixed size limitation.</li><li><strong>Fallback to </strong>malloc() — If the arena runs out of space, it can internally fall back to malloc(). This means the arena must keep track of which allocations came from the arena and which came from malloc(), and free them accordingly, complicating management.</li></ol><p>In general, I prefer to keep arenas as simple as possible. Over-engineering to handle every edge case risks reinventing (a bad version of) malloc() .</p><h3><strong>Real-World Use of Arenas</strong></h3><p>Arenas are frequently used in performance-critical contexts where many objects share the same lifetime and can be freed together.</p><p>For example in game development, each iteration of the game loop renders a frame, and objects allocated during the frame can all be discarded at the end. An arena is a perfect fit here as we can allocate in the arena during the frame, and then reset the arena at the end of the frame.</p><p>Another common use case is parsing workloads, such as in compilers or Google Protobuf. These systems create many small, short-lived objects and use arenas heavily to avoid the cost of per-object heap allocation. In fact, my arena implementation is based off of <a href="https://protobuf.dev/reference/cpp/arenas/">Google Protobuf</a>.</p><p>In low-latency trading systems, heap allocations during runtime are often avoided altogether. As far as possible, all required memory is pre-allocated during initialization. That memory is then never freed until program shutdown. This is essentially a permanent arena that lives for the duration of the application.</p><h4>std::vector as an arena?</h4><p>You’ve probably already used std::vector in a way that is conceptually similar to an arena.</p><p>Consider the following:</p><pre>void process_frame() {<br>  std::vector&lt;Foo&gt; arena_vec;<br>  // Preallocates memory for 1000 Foo<br>  // (but don&#39;t construct them)<br>  arena_vec.reserve(1000); <br>  process(arena_vec);<br>  // Memory and objects freed automatically on scope exit<br>}<br><br>void process(std::vector&lt;Foo&gt;&amp; vec) {<br>  ...<br>  auto* ptr = create_obj(vec);<br>  ...<br>}<br><br>Foo* create_obj(std::vector&lt;Foo&gt;&amp; vec) {<br>  ...<br>  // Don&#39;t allow allocating beyond capacity of the vector <br>  // or vector will resize and invalidate pointers!<br>  if (vec.size() == vec.capacity()) {<br>    throw std::runtime_error(&quot;Out of space&quot;);<br>  }<br><br>  vec.emplace_back({5, 6});  <br>  return &amp;vec.back();<br>}</pre><p>This isn’t strictly speaking an arena, but it shares the same philosophy: pre-allocate memory upfront, subsequent allocations come from this block, free everything in one go at the end.</p><p>When working with a single homogeneous type, containers like std::vector with reserve() are often all you need to reduce allocation overhead and you don’t actually need to roll your own arena.</p><p>To sum up, in high-performance, low-latency workloads, the general rule is to avoid dynamic allocations altogether. But when dynamic allocations are unavoidable, custom allocators are used to meet the strict performance and latency requirements. Arenas are just one kind of custom allocation technique. Others include stack allocators, pool allocators, and even hybrid schemes like arena-pool allocators. Each comes with trade-offs and is suited to different use cases.</p><p>The full code for my arena implementations can be found here: <a href="https://github.com/sgn00/sgarena">https://github.com/sgn00/sgarena</a></p><p>[1] There are alternatives to glibc malloc that can be used as the system allocator, such as jemalloc and tcmalloc, each offering different characteristics. For example, jemalloc doesn’t use sbrk/brk and only uses mmap internally.</p><p>[2] malloc() can take anywhere from tens of ns up to a few us. These latency spikes are undesirable in low-latency trading.</p><p><strong>References and Further Readings</strong></p><ul><li><a href="https://www.gingerbill.org/article/2019/02/08/memory-allocation-strategies-002/">Memory Allocation Strategies - Part 2</a></li><li><a href="https://nullprogram.com/blog/2023/09/27/">Arena allocator tips and tricks</a></li><li><a href="https://www.rfleury.com/p/untangling-lifetimes-the-arena-allocator">Untangling Lifetimes: The Arena Allocator</a></li><li><a href="https://github.com/JaMo42/cpp-arena-allocator?tab=readme-ov-file">GitHub - JaMo42/cpp-arena-allocator: Region based C++ allocator</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c685c81ee338" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Triple Buffer: Lock-free Concurrency Primitive]]></title>
            <link>https://medium.com/@sgn00/triple-buffer-lock-free-concurrency-primitive-611848627a1e?source=rss-214056e5b036------2</link>
            <guid isPermaLink="false">https://medium.com/p/611848627a1e</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[low-latency]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Ng Song Guan]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 13:10:32 GMT</pubDate>
            <atom:updated>2025-07-18T13:10:32.662Z</atom:updated>
            <content:encoded><![CDATA[<p>In low-latency trading systems, we often have a reader and a writer on separate threads that need to talk to each other. For instance, a market data thread might continuously listen to a live feed, updating the best bid and ask prices for a stock, while a strategy thread analyzes these updates to make real-time buy or sell decisions. There are many ways to transfer data between threads, each with trade-offs depending on performance and design goals.</p><p>In this article, I’ll be focusing on a specific scenario: when the reader only needs the most recent “snapshot” of data from the writer. For this case, we can design a high-performance solution using a concurrency primitive called a <strong>triple buffer</strong>.</p><h3>What’s a triple buffer?</h3><p>The term <em>triple buffer</em> is more commonly associated with <a href="https://en.wikipedia.org/wiki/Multiple_buffering">computer graphics</a>, where it helps reduce screen tearing and latency in rendering. As the name implies, there are three buffers involved. But why three?</p><h4>Single Buffer</h4><p>Let’s start with a single shared buffer used by both the reader and writer. At any one time, either the reader can read from it, or a writer can write to it. This effectively serializes access, and the reader or writer must spend time waiting for each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*1egwO63ARsKw1dIG.png" /></figure><h4>Double Buffer</h4><p>So let’s add another buffer. With two buffers, we can have a front buffer for reader to consume from and a back buffer for writer to produce to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*_kA0ZE5bvXNr02Vp.png" /></figure><p>Once the writer has finished writing, the buffers are swapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*M5c1kucZVS5YbOHR.png" /></figure><p>This is slightly better as the reader and writer can now operate simultaneously on their own buffers. However, we cannot swap the buffers while there is either a read or write in progress. Doing so will result in data corruption. As a result, a slow reader or writer can still block the other.</p><h4>Triple Buffer</h4><p>The solution? Add a third buffer. We now have a a triple buffer — I’ll term them as the front buffer, spare buffer, and back buffer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*9U24chu09Jj1P3cUi580sw.png" /></figure><p>I’ve numbered each of the three buffers so they’re easier to keep track:</p><ul><li>The ‘front’ one initially points to buffer 0 (reader’s current view)</li><li>The ‘spare’ one initially points to buffer 1 (idle, ready for staging)</li><li>The ‘back’ one initially points to buffer 2 (writer’s workspace)</li></ul><p>Here is how a write gets to the reader:</p><ol><li>Writer prepares data in the back buffer.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*HhH88WjLUlEeZM2miN1bsg.png" /></figure><p>2. Once the write is complete, the writer swaps the back buffer and spare buffer. Now the spare buffer holds the written data, and the writer gets a new clean back buffer for the next write.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*ThoylAVnIG3UrFMCdWuAkw.png" /></figure><p>3. The reader, meanwhile, could be reading the front buffer at its own pace. When the reader tries to read again, it notices the spare buffer has data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*cKdzmvZ86BvP5J1vJx2mYg.png" /></figure><p>4. Reader swaps front buffer and spare buffer, so the written data is now in the front buffer. Reader is now able to read the data that the writer wrote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*kZYAKvUZ80LAyln7nJMIxA.png" /></figure><p>Notice how the reader and writer are much more decoupled with the use of three buffers. After a writer publishes the write (step 2), it can immediately return to writing in the back buffer (step 1), without waiting for the reader. Likewise, the reader is free to read from the front buffer (step 3) and swap in new data from the spare buffer (step 4), independent of the writer. The only constraint is that the reader and writer must not swap their buffers at the exact same time.</p><p>To sum up, we have three buffers each with a different role:</p><ul><li><strong>Front</strong>: The reader’s stable view of the data, isolated from ongoing writes.</li><li><strong>Spare</strong>: Holds the latest committed snapshot from the writer, awaiting reader pickup.</li><li><strong>Back</strong>: The writer’s private workspace for preparing updates.</li></ul><h3>Lock-based implementation</h3><p>We start with a lock-based C++ implementation of a triple buffer.</p><pre>#include &lt;mutex&gt;<br>#include &lt;utility&gt;<br><br>template &lt;typename T&gt;<br>struct TripleBuffer {<br><br>    // Writer API - returns a pointer to the back buffer <br>    // for writer to write into.<br>    T* get_for_writer() {<br>        return &amp;buffers_[back_idx_];<br>    }<br><br>    // Writer API - Once finished writing, writer calls <br>    // publish to swap the back and spare buffer.<br>    void publish() {<br>        std::lock_guard lk {mtx_};<br>        std::swap(back_idx_, spare_idx_);<br>        has_update_ = true;<br>    }<br><br>    // Reader API - Reader checks if there&#39;s an update <br>    // on the spare buffer. If there is, it will swap the <br>    // front and spare buffer.<br>    // Then it returns the pointer to front buffer <br>    // for reader to read, and a bool to let reader know <br>    // if this is &#39;new&#39; data.<br>    std::pair&lt;T*, bool&gt; get_for_reader() {<br>        std::lock_guard lk {mtx_};<br>        bool updated = has_update_;<br>        if (has_update_) {<br>            std::swap(front_idx_, spare_idx_);<br>            has_update_ = false;<br>        }<br>        return {&amp;buffers_[front_idx_], updated};<br>    }<br><br>private:<br>    T buffers_[3];<br>    int front_idx_ = 0;<br>    int spare_idx_ = 1;<br>    int back_idx_ = 2;<br><br>    bool has_update_ = false;<br>    std::mutex mtx_;<br>};</pre><p>The implementation is relatively straightforward. A std::mutex guards the critical section, which consists of the code that swaps the spare buffer and flips the has_update_ boolean.</p><p>Here is an example of how a reader will make use of the triple buffer in a low latency system:</p><pre>// Assume the reader thread is pinned to a cpu core<br>template &lt;typename T&gt;<br>void reader_func(TripleBuffer&lt;T&gt;&amp; triple_buffer) {<br>    while (true) {<br>        // Get the front buffer to read from and process it<br>        auto [data, updated] = triple_buffer.get_for_reader();<br>        if (updated) {<br>            process_new_data(data);<br>        } else {<br>            process_data(data);<br>        }<br>    }<br>}</pre><p>And an example snippet for a writer:</p><pre>// Assume the writer thread is pinned to a cpu core<br>template &lt;typename T&gt;<br>void writer_func(TripleBuffer&lt;T&gt;&amp; triple_buffer) {<br>    while (true) {<br>        // Recv data over the network<br>        auto data = recv_data();<br>        // Get the back buffer and write to it<br>        auto* ptr = triple_buffer.get_for_writer();<br>        *ptr = std::move(data);<br>        // Now publish this write (swap buffers)<br>        triple_buffer.publish();<br>    }<br>}</pre><p><strong>Notes on API:</strong></p><ul><li>For the writer API, I’ve split the conventional write() call into two separate calls — get_for_writer() and publish(), allowing writer code to determine how to write the object into the buffer. If you prefer, you can also define a single write function as below:</li></ul><pre>T* get_for_writer();<br>void publish();<br><br>// Can create an rvalue overload as well<br>void write(const T&amp; data) {<br>  T* ptr = get_for_writer();<br>  *ptr = data;<br>  publish();<br>}</pre><ul><li>The pointers returned by get_for_writer() and get_for_reader() are only valid for that particular read/write. They should not be stored for use beyond that.</li></ul><h3>Properties of triple buffer</h3><p>A key property of the triple buffer is that the reader always accesses the most recent committed snapshot from the writer.</p><p>For example, consider a triple buffer that holds an integer. Let’s say a writer writes three integers — 5, then 6, then 7 while the reader is busy with something else. Now, when the reader eventually reads, it will only see 7 as the writer has overwritten the earlier data. A triple buffer effectively drops updates when the reader is slower than writer, and is thus ideal for cases where we are only interested in the latest version of the data. An example is in low-latency trading where a strategy thread only cares about the latest best bid-ask of a security and can tolerate not receiving all the intermediate quote changes.</p><p>But if the reader needs to process every update, then a Single Producer Single Consumer (SPSC) queue is more appropriate. While queues preserve the intermediate updates, we may have to deal with back-pressure problems resulting from a slower reader relative to writer. A triple buffer, by design, avoids this entirely, so the choice of which to use depends on the workload.</p><h3>Lock-free implementation</h3><p>The lock-based implementation is a decent first step. However, both the writer’s publish() function and reader’s get_for_reader() function are trying to acquire the same lock, which results in lock contention when there are many reads and writes happening simultaneously. The full power of a triple buffer can only be exploited via a lock-free implementation.</p><p>We want to get rid of the lock and instead make use of atomics for synchronization. Here, we need to consider two challenges:</p><ol><li>How do we atomically exchange both the integer index and boolean has_update_ together in publish() and get_for_reader() functions?</li></ol><pre>// In the lock-based implementation&#39;s publish() function, <br>// the atomicity of the critical section <br>// is guaranteed by acquiring the lock.<br>void publish() {<br>    std::lock_guard lk {mtx_};<br>    std::swap(back_idx_, spare_idx_);<br>    has_update_ = true;<br>}</pre><p>2. How do we ensure proper <a href="https://en.wikipedia.org/wiki/Memory_ordering">memory ordering</a> (no compiler/cpu re-ordering)?</p><p>To tackle these problems, we can bundle spare_idx_ and has_update_ together in an std::atomic struct variable. Then, we can use std::atomic&lt;T&gt;::exchange — a <a href="https://en.wikipedia.org/wiki/Read%E2%80%93modify%E2%80%93write">read-modify-write</a> operation — to swap the struct atomically.</p><p>Here’s a possible lock-free implementation.</p><pre>#include &lt;atomic&gt;<br>#include &lt;utility&gt;<br><br><br>template &lt;typename T&gt;<br>struct TripleBuffer {<br><br>    // Writer API - returns a pointer to the back buffer <br>    // for writer to write into.<br>    T* get_for_writer() {<br>        return &amp;buffers_[back_idx_];<br>    }<br><br>    // Writer API - Once finished writing, writer calls <br>    // publish to swap the back and spare buffer.<br>    void publish() {<br>        State new_spare {back_idx_, true};<br>        State prev_spare = spare_.exchange(new_spare, <br>                                      std::memory_order_acq_rel);<br>        back_idx_ = prev_spare.idx;<br>    }<br><br>    // Reader API - Reader checks if there&#39;s an update <br>    // on the spare buffer. If there is, it will swap the <br>    // front and spare buffer.<br>    // Then it returns the pointer to front buffer <br>    // for reader to read, and a bool to let reader know <br>    // if this is &#39;new&#39; data.<br>    std::pair&lt;T*, bool&gt; get_for_reader() {<br>        State curr_spare = spare_.load(std::memory_order_relaxed);<br>        bool updated = curr_spare.has_update;<br>        if (curr_spare.has_update) {<br>            State new_spare {front_idx_, false};<br>            State prev_spare = spare_.exchange(new_spare, <br>                                      std::memory_order_acq_rel);<br>            front_idx_ = prev_spare.idx;<br>        }<br>        return {&amp;buffers_[front_idx_], updated};<br>    }<br><br>private:<br>    // On an x86-64 platform, <br>    // this struct is 8 bytes (inclusive of padding),<br>    // so a xchg instruction can swap it atomically.<br>    struct State {<br>        int idx;<br>        bool has_update;<br>    };<br><br>    // Implementation is lock-free as long as <br>    // this static_assert passes<br>    static_assert(std::atomic&lt;State&gt;::is_always_lock_free);<br><br>    T buffers_[3];<br>    int front_idx_ = 0;<br>    // spare_idx_ and has_update_ <br>    // are now moved into an atomic struct<br>    std::atomic&lt;State&gt; spare_ {{1, false}};<br>    int back_idx_ = 2;<br>};</pre><p>The structure of the code remains quite similar to the lock-based implementation, just that we are using atomics instead of a mutex for synchronization.</p><p><strong>A faulty lock-free implementation</strong></p><p>Recall in our lock-based implementation, atomicity is enforced by the mutex:</p><pre>void publish() {<br>    std::lock_guard lk {mtx_};<br>    std::swap(back_idx_, spare_idx_);<br>    has_update_ = true;<br>}</pre><p>A naive lock-free attempt might look like this, using separate atomics:</p><pre>// Class members<br>std::atomic&lt;int&gt; spare_idx_;<br>std::atomic&lt;bool&gt; has_update_;<br><br>void publish() {<br>    has_update_.exchange(true, std::memory_order_acq_rel);<br>    spare_idx_.exchange(new_spare_idx, std::memory_order_acq_rel);<br>}</pre><p>This approach is wrong because while individually each exchange is atomic, collectively they are not. There can be interleaving, e.g. a reader might think it is reading new data because has_update_ has been set to true, even though the spare_idx_ is still pointing to old data.</p><p>In my implementation, I chose to place the index and boolean together as an atomic struct so that these two variables are swapped together atomically. An interesting and potentially faster approach would be to <a href="https://github.com/brilliantsugar/trio/blob/main/trio.h">store pointers directly and use pointer tagging</a>.</p><h3><strong>Benchmark</strong></h3><p>I wrote a quick benchmark to compare the lock-based implementation vs the lock-free one. It measures writer throughput: the time taken for a writer thread to write 200,000,000 integers to the triple buffer while a reader is continuously reading. From this, I calculated the write ops/s. I pinned the reader thread and writer thread to separate CPU cores, and also enabled CPU isolation for these 2 cores to provide a stable benchmark environment. The benchmark code can be found here: <a href="https://github.com/sgn00/triple/blob/main/test_triplebuffer.cpp">https://github.com/sgn00/triple/blob/main/test_triplebuffer.cpp</a></p><p>Here are the results:</p><pre>// Lock-based implementation<br>$ ./a.out lock<br>7095509 write ops/s<br>Consumer new updates: 18584418, total read attempts: 204258584<br><br>$ ./a.out lock<br>7183974 write ops/s<br>Consumer new updates: 17072681, total read attempts: 156454279</pre><pre>// Lock-free implementation<br>$ ./a.out lockfree<br>13600748 write ops/s<br>Consumer new updates: 187102137, total read attempts: 194719299<br><br>$ ./a.out lockfree<br>14399367 write ops/s<br>Consumer new updates: 126193551, total read attempts: 132666996</pre><p>On my machine, the lock-free implementation is more than twice as fast in terms of write ops/s, achieving about 14 million write ops/s compared to 7 million write ops/s with the lock-based implementation. The reader also managed to consume significantly more during the writer’s run.</p><p>Note that these figures only provide a rough sense of the difference in performance and the benchmark isn’t meant to be rigorous.</p><h3><strong>Further Optimization</strong></h3><p>For even better performance in our lock-free triple buffer, we should align the class members to the system’s cache line size so that they reside on separate cache lines. This avoids <a href="https://en.wikipedia.org/wiki/False_sharing">false sharing</a>, where reader and writer threads, when running on separate cores, invalidate each other’s cache lines unnecessarily.</p><p>On most platforms, the cache line size is 64 bytes. C++ provides std::hardware_destructive_interference_size which is a portable constant to determine this.</p><pre>#include &lt;atomic&gt;<br>#include &lt;utility&gt;<br><br>template &lt;typename T&gt;<br>struct TripleBuffer {<br><br>    T* get_for_writer() {<br>        return &amp;buffers_[back_idx_].buf;<br>    }<br><br>    void publish() {<br>        State new_spare {back_idx_, true};<br>        State prev_spare = spare_.exchange(new_spare, <br>                                      std::memory_order_acq_rel);<br>        back_idx_ = prev_spare.idx;<br>    }<br><br>    std::pair&lt;T*, bool&gt; get_for_reader() {<br>        State curr_spare = spare_.load(std::memory_order_relaxed);<br>        bool updated = curr_spare.has_update;<br>        if (curr_spare.has_update) {<br>            State new_spare {front_idx_, false};<br>            State prev_spare = spare_.exchange(new_spare, <br>                                        std::memory_order_acq_rel);<br>            front_idx_ = prev_spare.idx;<br>        }<br>        return {&amp;buffers_[front_idx_].buf, updated};<br>    }<br><br>private:<br>    static constexpr size_t keep_apart_sz = std::hardware_destructive_interference_size;<br><br>    struct State {<br>        int idx;<br>        bool has_update;<br>    };<br><br>    // We align both the indices and the buffers, <br>    // so that they will be on separate cache lines.<br>    struct alignas(keep_apart_sz) Buffer {<br>        T buf;<br>    };<br><br>    Buffer buffers_[3];<br>    alignas(keep_apart_sz) int front_idx_ = 0;<br>    alignas(keep_apart_sz) std::atomic&lt;State&gt; spare_ {{1, false}};<br>    alignas(keep_apart_sz) int back_idx_ = 2;<br>};</pre><p>I benchmarked this aligned version and got the following results:</p><pre>// Optimized aligned version<br>$ ./a.out optimized<br>17418573 write ops/s<br>Consumer new updates: 101502096, total read attempts: 184864822<br><br>$ ./a.out optimized<br>19636094 write ops/s<br>Consumer new updates: 82327129, total read attempts: 173827439<br><br>$ ./a.out optimized<br>15882294 write ops/s<br>Consumer new updates: 98531752, total read attempts: 149386389</pre><p>There’s some variation but on average we do see an improvement of a few million write ops/s. Not bad for a small code change. This highlights the importance of understanding how <a href="https://people.freebsd.org/~lstewart/articles/cpumemory.pdf">memory works at the hardware level</a> when optimizing for performance.</p><p>In this article, I’ve shown how to implement a lock-free triple buffer which supports a single producer and single consumer. While I’ve been focusing on inter-thread communication, a triple buffer can also be used for inter-process communication via shared memory.</p><p>It’s also possible to extend a triple buffer to support <a href="https://users.rust-lang.org/t/spmc-buffer-triple-buffering-for-multiple-consumers/10118">multiple consumers</a>. This is useful in a fan-out design where a single producer broadcasts updates to many consumers simultaneously. However, if you need multiple producers, it is best to explore other concurrency primitives.</p><p>The full code for my triple buffer implementations can be found here: <a href="https://github.com/sgn00/triple">https://github.com/sgn00/triple</a></p><h4><strong>References and Further Readings</strong></h4><p><a href="https://github.com/HadrienG2/triple-buffer">https://github.com/HadrienG2/triple-buffer</a></p><p><a href="https://brilliantsugar.github.io/posts/how-i-learned-to-stop-worrying-and-love-juggling-c++-atomics/">https://brilliantsugar.github.io/posts/how-i-learned-to-stop-worrying-and-love-juggling-c++-atomics/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=611848627a1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contributing back to the cloud security community]]></title>
            <link>https://medium.com/csg-govtech/contributing-back-to-the-cloud-security-community-68abb6eac728?source=rss-214056e5b036------2</link>
            <guid isPermaLink="false">https://medium.com/p/68abb6eac728</guid>
            <category><![CDATA[csg]]></category>
            <category><![CDATA[pacu]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cloudgoat]]></category>
            <category><![CDATA[govtech]]></category>
            <dc:creator><![CDATA[Ng Song Guan]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 04:20:09 GMT</pubDate>
            <atom:updated>2020-08-26T04:42:14.149Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learnings derived from my contributions to the AWS open source community in the area of cloud security — in particular to CloudGoat and Pacu</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wF7X-HTxtn4uG78X.jpg" /><figcaption>Source: <a href="https://www.verdict.co.uk/cloud-computing-timeline/">https://www.verdict.co.uk/cloud-computing-timeline/</a></figcaption></figure><h3>Introduction</h3><p>During my internship with the Cybersecurity Group in the Government Technology Agency of Singapore (GovTech), I was tasked to conduct cloud security testing research with cybersecurity specialists in the Red Team. The research focused primarily on Amazon Web Services (AWS) as it continues to be the <a href="https://www.statista.com/chart/18819/worldwide-market-share-of-leading-cloud-infrastructure-service-providers/">most dominant player</a> within this space.</p><p>Notably, the open source community has been actively contributing to security testing related tools for AWS. A challenge was thus issued to me during my internship stint to contribute back to the same open source community by developing or enhancing tools in the areas of:</p><ol><li>Scenario-based learning of cloud security; and</li><li>Automation of cloud penetration testing techniques.</li></ol><p>In this article, I will be sharing my learning journey in the area of cloud security and my contributions to the open source community.</p><h3>Learning AWS Security via Cloudgoat</h3><p>To get me started on my learning, my team recommended various cloud security tools and sites. One of them, <a href="https://github.com/RhinoSecurityLabs/cloudgoat">Cloudgoat</a>, is a “vulnerable-by-design” AWS deployment tool that automates the deployment of intentionally misconfigured AWS resources. It consists of several independent scenarios reflecting various vulnerable deployment designs. Notably, one of the scenarios called “cloud_breach_s3” was modelled after the infamous <a href="https://rhinosecuritylabs.com/aws/capital-one-cloud_breach_s3-cloudgoat/">2019 Capital One data breach</a>.</p><p>Each scenario can have one or more attack paths, that in turn, exploit misconfigurations in one or more AWS services. The scenarios are also graded based on their difficulty (Easy, Moderate, Hard) and how extensive (Small, Medium, Large) it is based on the number of AWS resources deployed. When you deploy a scenario, Cloudgoat uses <a href="https://www.terraform.io/">terraform</a> to automate the set-up of the AWS infrastructure related to the scenario. I worked through the different scenarios and found this tool immensely useful in solidifying my understanding of AWS security.</p><p>Particularly, serverless computing, which involves the AWS Lambda service, has been gaining traction and redefining modern web architecture. While Cloudgoat has some scenarios that touch on the AWS Lambda service, I felt that it was lacking a standalone scenario to expose Lambda and security misconfigurations specific to it. Thus, a new scenario on Lambda security would be very relevant.</p><p>As such, I decided to create a scenario called “lambda_privesc”, that focuses on AWS Identity and Access Management (IAM) concepts and privilege escalation techniques via Lambda. The privilege escalation technique that I modelled from was based on a <a href="https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/">very informative blog article</a> by RhinoSecurityLabs, who are also the creators of Cloudgoat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*-HTjibkHxtoGWwkM1A7kKA.png" /><figcaption>Outline of the attack path for lambda_privesc</figcaption></figure><p>After deciding on the design of the scenario, I set out to create it. Thankfully, creating a Cloudgoat scenario was straightforward:</p><ul><li>First, I developed terraform scripts that were needed to automate the deployment of the AWS resources for the scenario.</li><li>Next, I followed the documentation convention for the other scenarios in Cloudgoat, which encompasses a walkthrough, cheat sheet and a scenario outline diagram.</li><li>Finally, after carefully vetting the work done, I submitted a pull request to Cloudgoat’s public repository.</li></ul><p>My scenario was subsequently <a href="https://github.com/RhinoSecurityLabs/cloudgoat/pull/64">reviewed, accepted and merged</a> into the master branch of Cloudgoat and is now available to everyone. The process of designing the scenario led me to conduct independent research, readings and exploration of various misconfigurations that could happen in real-world scenarios. This helped me to learn more about the different attack possibilities related to AWS, beyond what I already knew.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*KxUW-KjGGPvhMPCDRc4UJg.png" /><figcaption>Pull Request merged! :)</figcaption></figure><h3>Contributing to Pacu</h3><p>As my team conducts cloud security assessments regularly, I was also tasked to explore an AWS cloud security tool called <a href="https://github.com/RhinoSecurityLabs/pacu">Pacu</a> and to understand how we can leverage this tool to augment the team’s testing methodology.</p><p>Created and maintained by RhinoSecurityLabs, Pacu is an open source AWS exploitation framework that is designed for offensive security testing against cloud environments. It is a popular tool with more than 1500 stars on its Github repository!</p><p>Pacu is also a highly modular framework, with each module serving a specific function. For example, the “ec2__enum” module extracts information relevant to ec2 instances in the target AWS accounts. Using Pacu is as simple as choosing a module that you would like to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*lOi6ZHXzVQBHxCr50h-4aQ.png" /><figcaption>Examples of Pacu modules</figcaption></figure><p>Upon closer examination and discussion with the team, we identified that modules performing enumeration on database services such as Relational Database Service (RDS) and DynamoDB, were lacking. This is important because a crucial aspect of post exploitation during a typical cloud penetration testing assessment is to “pillage” for sensitive data within the AWS account. A common technique to hunt for these treasures is to look for accessible databases or snapshots of these databases. Instead of performing these checks manually, we thought that introducing a module in Pacu to automate this would be a better idea.</p><p>Thus, I created my first module called “rds__enum_snapshots”. As its name implies, “rds__enum_snapshots” seeks to enumerate RDS snapshots. The module outputs information on the various RDS snapshots in the account, such as the permissions (public, private or shared), encryption and owner (this or another account). This information aids in planning an attack path to exfiltrate data and audit for misconfigurations on RDS snapshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*OSbWmYfgDUHZeVgJix1rlg.png" /><figcaption>Output of rds__enum_snapshots module</figcaption></figure><p>Writing the code for Pacu was relatively straightforward. First, I studied the <a href="https://github.com/RhinoSecurityLabs/pacu/wiki/Contribution-Guidelines">contribution guidelines</a> to understand how contributions should be made. I also examined the codes of other modules, especially the “ebs__enum_snapshots” module, and tried to model my module after it. Additionally, I followed Pacu’s styling guidelines by using a python linter.</p><p>After submitting my code as a <a href="https://github.com/RhinoSecurityLabs/pacu/pull/187">pull request</a>, Pacu requested for the Amazon Aurora to be included in the enumeration. For those who are unfamiliar, Aurora is an AWS-managed service that makes use of relational databases. I quickly implemented the extra feature and submitted it.</p><p>The module was approved but pending merge, as it will introduce a breaking change to Pacu’s database file. I then started to work on my second module, “dynamodb__enum”, which is designed to enumerate DynamoDB tables. This module has been submitted as a <a href="https://github.com/RhinoSecurityLabs/pacu/pull/191">pull request</a> and is awaiting review.</p><p>Developing Pacu modules allowed me to work closely with AWS Software Development Kits (SDK). I deep dived into the services mentioned earlier and explored how post exploitation activities can be conducted on them.</p><h3>Tips on Open Source Contributions</h3><p>Having experienced the entire contribution process, I would like to offer some tips when it comes to open source project contributions:</p><ol><li>Include buffer time when your pull request is submitted. The maintainers of the project may provide comments or make requests to ensure that the proposed changes tie in nicely with the overall project design.</li><li>Follow the contribution guidelines outlined by the maintainers. Some projects may require your contribution to follow a specific format, syntax or other requirements. Adhering to these guidelines will greatly speed up your contribution process and minimise revisions.</li><li>Do not be disheartened if your contribution is rejected. This may be due to many different factors. Continue to brainstorm for new ideas and work on other open source projects!</li></ol><h3>Conclusion</h3><p>It has been a privilege to be able to contribute to the open source community. Beyond the technical learnings and recognition, it was also immensely fulfilling as I know that the contributions that I have made to the open source community is impactful and has a global outreach.</p><p>The journey wasn’t easy, and our success is due in no small part to my team’s guidance. In addition, the folks from RhinoSecurityLabs have been engaging and forthcoming, which made the entire process more enjoyable!</p><p>Finally, I would like to encourage all my readers (yes, you!) to contribute to the open source community. No contribution is too small — fixing “typos” in the source codes can have a significant impact too! With more contributors, the open source community will be more vibrant, and that ultimately translates to a safer cyberspace with better tools and projects for all to use!</p><p><strong>Written by: Song Guan</strong></p><p><em>A year 2 computer science student from the National University of Singapore who is passionate about cybersecurity. In his spare time, Song Guan loves to explore various domains of information technology and attempt to “break them”!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68abb6eac728" width="1" height="1" alt=""><hr><p><a href="https://medium.com/csg-govtech/contributing-back-to-the-cloud-security-community-68abb6eac728">Contributing back to the cloud security community</a> was originally published in <a href="https://medium.com/csg-govtech">CSG @ GovTech Singapore</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>