<?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[RE: Exploit - Medium]]></title>
        <description><![CDATA[Exploration of reverse engineering, binary analysis, and exploit development - Medium]]></description>
        <link>https://medium.com/re-exploit?source=rss----1c237f011383---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>RE: Exploit - Medium</title>
            <link>https://medium.com/re-exploit?source=rss----1c237f011383---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:26:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/re-exploit" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What Happens to Rust Ownership When You Compile It?]]></title>
            <link>https://medium.com/re-exploit/what-happens-to-rust-ownership-when-you-compile-it-509d4e1ce509?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/509d4e1ce509</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[binary-analysis]]></category>
            <category><![CDATA[resever-engineer-rust]]></category>
            <category><![CDATA[rust-ownership]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Thu, 28 May 2026 12:01:02 GMT</pubDate>
            <atom:updated>2026-05-28T12:12:46.970Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A binary analysis of drop flags, drop glue, and the erasure of borrow semantics across debug and release builds</em></p><p>Rust’s ownership system is the language’s defining feature. The borrow checker enforces, at compile time, that every value has exactly one owner, that references do not outlive the values they point to, and that mutable and immutable borrows cannot coexist. These guarantees are central to Rust’s memory safety story.</p><p>But what actually survives in the compiled binary? If you hand a stripped Rust executable to a reverse engineer, how much of the ownership structure can they recover?</p><p>This post answers that question with a concrete binary analysis. We compiled a controlled Rust programme exercising five ownership patterns, exported the Binary Ninja disassembly for both debug and release builds (Windows x64, MSVC toolchain), and traced each ownership concept from its MIR representation down to the final machine instructions. The results are specific and in some cases surprising.</p><p>The short answer: the drop sequence survives, drop flags partially survive in debug builds, and almost everything else is gone.</p><h3>The Test Programme</h3><p>The programme exercises five distinct ownership patterns explicitly:</p><pre>fn ownership_test() {<br>    // Pattern 1: move semantics<br>    let a = String::from(&quot;hello&quot;);<br>    let b = a;              // a is moved, borrow checker invalidates a</pre><pre>    println!(&quot;{}&quot;, b);</pre><pre>    // Pattern 2: shared borrows<br>    let s = String::from(&quot;world&quot;);<br>    let r1 = &amp;s;<br>    let r2 = &amp;s;            // two shared borrows, legal<br>    println!(&quot;{} {}&quot;, r1, r2);</pre><pre>    // Pattern 3: mutable borrow<br>    let mut t = String::from(&quot;foo&quot;);<br>    let m = &amp;mut t;<br>    m.push_str(&quot;bar&quot;);</pre><pre>    // Pattern 4: ownership transfer into function<br>    takes_ownership(b);     // b moved here, no longer valid after this line</pre><pre>    // Pattern 5: clone preserves both values<br>    let orig = String::from(&quot;original&quot;);<br>    let copy = orig.clone();<br>    println!(&quot;{} {}&quot;, orig, copy);<br>}</pre><pre>fn takes_ownership(s: String) {<br>    println!(&quot;{}&quot;, s);<br>}   // s dropped here</pre><p>We compiled this with --debug and --release, exported the Binary Ninja linear disassembly, and also captured the MIR output (-Z dump-mir=all) for both profiles. The platform is Windows x64 with the MSVC toolchain, so the calling convention is Windows fastcall (first four arguments in rcx/rdx/r8/r9) and the allocator is MSVC HeapAlloc/HeapFree rather than jemalloc.</p><h3>The MIR Layer: Where Ownership Is Still Visible</h3><p>Before examining the binary, it is worth pausing at MIR (Mid-level Intermediate Representation), which is the last stage of the Rust compiler where ownership semantics are fully explicit. Looking at the MIR output is instructive because it shows exactly what the compiler knows about ownership before codegen discards it.</p><p>The debug MIR for the move (let b = a) contains this:</p><pre>_54 = const false;<br>_1 = &lt;String as From&lt;&amp;str&gt;&gt;::from(const &quot;hello&quot;) -&gt; [return: bb1, ...];<br>// bb1:<br>_54 = const true;<br>_2 = move _1;       // b = move a</pre><p>_54 is a <strong>drop flag</strong> -- a boolean that tracks whether _1 (bound to a, then moved into _2 which is b) needs to be dropped on an unwind path. When b is subsequently moved into takes_ownership, the flag is cleared:</p><pre>_54 = const false;<br>_34 = move _2;<br>_33 = takes_ownership(move _34)</pre><p>Drop flags exist because of panic unwinding. If an exception unwinds the stack mid-function, the runtime needs to know which values are currently live and need dropping. The flag encodes that information. In release mode, the compiler proves statically which values are live at every unwind point and eliminates the flags entirely.</p><p>The scope structure in the MIR also encodes the full nesting of borrows:</p><pre>scope 5 { debug s =&gt; _10;<br>  scope 6 { debug r1 =&gt; _11;<br>    scope 7 { debug r2 =&gt; _12;<br>      scope 10 { debug t =&gt; _22;<br>        scope 11 { debug m =&gt; _23; }</pre><p>Every borrow is named, scoped, and given a lifetime. r1 and r2 are both &amp;std::string::String, distinguished from m which is &amp;mut std::string::String. This information exists in MIR. It does not exist in the compiled binary.</p><h3>Debug Build: Pattern 1 — Move Semantics</h3><p><strong>Source:</strong></p><pre>let a = String::from(&quot;hello&quot;);<br>let b = a;</pre><p><strong>Binary (</strong><strong>0x140002440 region, </strong><strong>sub_140002440 = </strong><strong>ownership_test):</strong></p><pre>; String::from(&quot;hello&quot;) -- allocates heap, fills String struct<br>lea  rdx, [rel &quot;hello&quot;]<br>lea  rcx, [rbp-0x18]         ; destination: a&#39;s stack slot (var_1c0)<br>mov  r8d, 0x5                ; length<br>call sub_140003930            ; &lt;String as From&lt;&amp;str&gt;&gt;::from<br><br>; drop flag: a is now live<br>mov  byte [rbp+0x167], 0x1<br>; move a into b -- three field copies (ptr, len, cap)<br>mov  rax, qword [rbp-0x8]    ; a.cap<br>mov  qword [rbp+0x10], rax   ; b.cap<br>movups xmm0, xmmword [rbp-0x18]  ; a.ptr + a.len (16 bytes, SSE load)<br>movaps xmmword [rbp], xmm0       ; b.ptr + b.len</pre><p>The move is a movups/movaps pair for the first 16 bytes (ptr and len) and a separate mov for the cap field. Three field copies. The source slot at rbp-0x18 is not zeroed. No instruction marks a as invalid. The borrow checker&#39;s enforcement that a cannot be read after this point is not present in the binary.</p><p>The only trace of the ownership transfer is the drop flag at rbp+0x167, which is 0x1 from this point until b is moved into takes_ownership.</p><h3>Debug Build: Pattern 4 — Ownership Transfer Into a Function</h3><p><strong>Source:</strong></p><pre>takes_ownership(b);</pre><p><strong>Binary (</strong><strong>0x1400025e1):</strong></p><pre>mov  byte [rbp+0x167], 0x0   ; drop flag cleared -- b is no longer owned here<br>mov  rax, qword [rbp+0x10]   ; b.cap<br>mov  qword [rbp+0xe0], rax   ; copy to argument slot<br>movaps xmm0, xmmword [rbp]   ; b.ptr + b.len<br>movaps xmmword [rbp+0xd0], xmm0  ; copy to argument slot<br>lea  rcx, [rbp+0xd0]         ; rcx = &amp;arg (Windows ABI: by-value String as pointer)<br>call sub_140002800            ; takes_ownership(b)</pre><p>The drop flag goes to zero immediately before the call. This is the binary encoding of “b is no longer the owner”. Inside sub_140002800 (which is takes_ownership), the function ends with:</p><pre>mov  rcx, qword [rbp-0x38]<br>call sub_140003a90            ; drop_in_place&lt;String&gt;</pre><p>sub_140003a90 calls sub_140003ab0, which calls sub_140003b10 (the dealloc path wrapping HeapFree). This is <strong>drop glue</strong> -- compiler-generated destructor code that runs at the end of the callee because the callee now owns the value.</p><p>Two things are observable here. First, the drop call in takes_ownership confirms that the function received ownership -- a function that merely borrowed would not produce this destructor. Second, the absence of a drop for b in ownership_test after the call confirms the transfer -- b&#39;s stack slot is not cleaned up here because it no longer owns anything.</p><p>Both of these are indirect signals. Neither encodes the borrow checker’s actual constraint (“b cannot be used after this call”).</p><h3>Debug Build: Patterns 2 and 3 — Borrows, Shared and Mutable</h3><p><strong>Source:</strong></p><pre>let r1 = &amp;s;<br>let r2 = &amp;s;<br>// ...<br>let m = &amp;mut t;<br>m.push_str(&quot;bar&quot;);</pre><p><strong>Binary for shared borrows (</strong><strong>0x1400024f4):</strong></p><pre>lea  rax, [rbp+0x48]         ; address of s (var_160)<br>mov  qword [rbp+0x60], rax   ; r1 = &amp;s<br>mov  qword [rbp+0x68], rax   ; r2 = &amp;s</pre><p><strong>Binary for mutable borrow (</strong><strong>0x14000259a):</strong></p><pre>lea  rcx, [rbp+0xb8]         ; address of t (var_f0)<br>mov  qword [rbp+0x180], rcx  ; m = &amp;mut t</pre><p>These are identical operations: take the address of a stack slot, store it in another slot. The lea for r1 and the lea for m produce the same instruction shape. The borrow checker enforced that r1 and r2 are shared (no mutation allowed), that m is exclusive (no other borrow can coexist), and that none of these references outlive s or t. None of that information is present in the binary.</p><p>A disassembler looking at mov qword [rbp+0x60], rax cannot determine whether rax is a shared borrow, a mutable borrow, or a raw pointer. The distinction is a compile-time property that has been fully erased.</p><h3>Debug Build: Drop Sequence at Scope Exit</h3><p><strong>MIR (</strong><strong>bb23--</strong><strong>bb26):</strong></p><pre>drop(_36)   // copy<br>drop(_35)   // orig<br>drop(_26)   // t<br>drop(_12)   // s</pre><p>LIFO order — innermost scope drops first.</p><p><strong>Binary (</strong><strong>0x1400026ca--</strong><strong>0x1400026f8):</strong></p><pre>lea  rcx, [rbp+0x108]    ; &amp;copy<br>call sub_140003a90        ; drop_in_place&lt;String&gt;<br><br>lea  rcx, [rbp+0xf0]     ; &amp;orig<br>call sub_140003a90        ; drop_in_place&lt;String&gt;<br>lea  rcx, [rbp+0xb8]     ; &amp;t<br>call sub_140003a90        ; drop_in_place&lt;String&gt;<br>lea  rcx, [rbp+0x48]     ; &amp;s<br>call sub_140003a90        ; drop_in_place&lt;String&gt;</pre><p>Four call sub_140003a90 instructions, each preceded by a lea loading a different stack offset. The LIFO order matches the MIR exactly.</p><p>This is the richest ownership signal in the entire debug binary. From this sequence alone, a reverse engineer can determine:</p><ol><li>Four distinct heap-owning values were live in this function</li><li>They were heap-allocated (not borrowed — borrowed values do not get drop calls)</li><li>They were destroyed in LIFO order, consistent with Rust’s scoping rules</li></ol><p>What cannot be determined from the drop sequence: the borrow structure (which values had borrows taken out against them), the lifetime relationships between the values, or whether any of the dropped values were ever borrowed mutably.</p><p>Note that b and a are notably absent from the drop sequence. a was moved into b, then b was moved into takes_ownership. Neither is dropped here -- the drop happened inside takes_ownership. This absence is itself an ownership signal: a missing drop implies a value was moved out rather than owned to scope end.</p><h3>Drop Flags: The Debug-Only Ownership Trace</h3><p>The drop flag at rbp+0x167 toggles throughout the function. Here is the complete timeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*wZZn56EeNOJ8wbXv8VxX0A.png" /></figure><p>The unwind handler sub_140002710 reads this flag with test byte [rbp+0x167], 0x1 and conditionally drops b only if the flag is set. This handles the case where a panic occurs after b is allocated but before it is moved into takes_ownership.</p><p>Drop flags are a direct artefact of Rust’s ownership model. No equivalent mechanism exists in C, because C has no compiler-enforced ownership and therefore no automatic destructor to conditionally invoke. The presence of these toggling booleans is a Rust-specific binary signature — though one that only appears in debug builds.</p><h3>Release Build: What Remains</h3><p>The release build (sub_140001000) is substantially more compact. Binary Ninja lifts most of it to HLIL pseudocode that resembles C. Here is the drop sequence equivalent:</p><pre>// Conditional HeapFree calls at function exit (0x140001234--0x140001276)<br>if (rdx_8 != 0)<br>    j_sub_140001650(rax_2, rdx_8, 1)   // free t (&quot;foobar&quot;)<br><br>if (rdx_7 != 0)<br>    j_sub_140001650(rax_5, rdx_7, 1)   // free orig (&quot;original&quot;)<br>if (rdx_6 != 0)<br>    j_sub_140001650(rdx_6, ...)         // free copy<br>if (rdx_9 != 0)<br>    j_sub_140001650(rax_1, rdx_9, 1)   // free s (&quot;world&quot;)</pre><p>j_sub_140001650 is a thunk to HeapFree. The null checks (!= 0 on the capacity field) are the release-mode equivalent of drop flags -- a static null check rather than a dynamic boolean. The LIFO ordering of the four frees is preserved.</p><p>The drop glue abstraction (drop_in_place&lt;String&gt;) is gone. There are no sub_140003a90 calls. Instead, the compiler inlined the destructor down to a direct conditional HeapFree.</p><p>Drop flags are entirely absent. The compiler proved statically that no value’s liveness is ambiguous at any unwind point in this function, so no runtime flags are needed.</p><p>For the borrows (r1, r2, m): they do not produce any binary output at all in the release build. The borrowed values are used transiently and optimised away -- no stack slots are allocated for them, no lea instructions appear. The entire s/r1/r2 pattern collapses to an allocation, a sub_140003b80 call (= println!), and a later HeapFree.</p><h3>Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*_5ZOg84yIyxM7JZiqcK5vA.png" /></figure><h3>What This Means for Static Analysis</h3><p>The findings above have direct implications for anyone attempting to detect or characterise Rust malware through static binary analysis.</p><p><strong>What is recoverable without symbols:</strong> The drop sequence — both the count of owned heap values and their LIFO destruction order — is visible in both debug and release builds. The presence of drop_in_place calls (or inlined HeapFree sequences) is a Rust-characteristic pattern distinguishable from C&#39;s manual free calls. In the debug build, drop flags are a reliable Rust-specific signal.</p><p><strong>What is not recoverable:</strong> Borrow relationships, lifetime scopes, and the exclusivity constraints enforced by the borrow checker are completely absent. A mutable borrow and a shared borrow compile to the same instruction. A move and a copy compile to the same field-copy sequence. The source-level ownership structure that a Rust programmer reasons about does not exist in the binary.</p><p><strong>The asymmetry matters for detection:</strong> Rust’s drop glue density (number of drop_in_place calls per function) is measurably higher than equivalent C code for the same data structure manipulation. This is because Rust inserts destructors at every scope exit for every owned value, whereas C requires the programmer to insert free calls manually. This difference in destructor density is a detectable binary signature even in stripped, release-mode binaries.</p><p><strong>Drop flags are a debug-only signal:</strong> If you are analysing a debug build (which some deployed malware is, particularly early variants during development), the presence of toggling boolean slots adjacent to String or Vec stack frames is a strong Rust indicator. In release builds, the flags are gone, but the conditional null-checked HeapFree pattern at function exits is structurally distinct from typical C cleanup code.</p><h3>Connection to the Akira v2 Analysis</h3><p>The patterns identified here correspond directly to what was observed in the Akira v2 ransomware binary. In the lock function analysis, three of the same patterns appear:</p><p>The files.into_iter() move at the loop setup (0x4d398x region) produces three field copies of the Vec&lt;PathBuf&gt; fat pointer -- exactly the same three-field pattern seen here for String. No source invalidation. The IntoIter::drop call at 0x4d3a2a is the downstream evidence of the move, analogous to the sub_140003a90 calls at scope exit here.</p><p>The MutexGuard RAII drop at 0x4d3a0b and 0x4d3b40 is the same drop_in_place pattern. It confirms ownership of the guard, not the borrow constraints the guard enforced.</p><p>The Arc reference counting (lock inc qword [rax] at 0x4d3e7e) is a pattern that does not appear in the simple String programme above, because Arc introduces reference-counted shared ownership that has no equivalent here. In Akira, the lock inc is the only binary trace of the Thread/JoinHandle shared ownership -- but it encodes only that a reference count was incremented, not the borrow rules on the Arc&#39;s contents.</p><p>In both the controlled programme and the Akira binary, the same conclusion holds: the drop sequence survives, borrow semantics do not.</p><h3>Conclusion</h3><p>Rust’s ownership system is a compile-time abstraction. It exists fully at the source level, partially at MIR (where drop flags and scope annotations are still present), and residually at the binary level (where only the consequences of ownership — destructor calls and drop flags — survive).</p><p>The key findings from this analysis:</p><ol><li><strong>Moves leave no direct trace.</strong> The three-field copy pattern is identical to any struct copy. The only indirect evidence is a drop flag toggle (debug builds) or the absence of a subsequent drop (both builds).</li><li><strong>Borrow semantics are completely absent.</strong> Shared borrows and mutable borrows compile to the same lea/mov pattern. Lifetime bounds produce no binary output at all.</li><li><strong>Drop glue is the primary ownership artefact.</strong> The call sequence to drop_in_place (or the inlined HeapFree equivalent in release) is the most reliable ownership signal available in the binary. Its presence confirms heap ownership; its absence at a call site implies a value was moved rather than owned to scope end.</li><li><strong>Drop flags are a Rust-specific debug signal.</strong> The toggling boolean slots are generated specifically to support Rust’s unwind-safe ownership model and have no direct equivalent in C or C++ binaries.</li><li><strong>The information loss is architectural, not a tooling limitation.</strong> Better decompilers will not recover borrow semantics, because the information does not exist in the binary. This is a fundamental consequence of ownership being a compile-time abstraction that the code generator does not need to preserve.</li></ol><p>For static malware detection, this means that ownership-based characterisation of Rust binaries must focus on what survives: destructor density, drop flag patterns, Arc refcount operations, and the structural shape of scope-exit cleanup code. The richer ownership semantics that distinguish Rust from C at the source level are, by compilation, rendered invisible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=509d4e1ce509" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/what-happens-to-rust-ownership-when-you-compile-it-509d4e1ce509">What Happens to Rust Ownership When You Compile It?</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reversing Akira’s Rust Experiment : A Breakdown Part 3]]></title>
            <link>https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-3-443e3551825a?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/443e3551825a</guid>
            <category><![CDATA[rust-based-malware]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[reverse-engineer-rust]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[akirav2]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Wed, 27 May 2026 19:27:01 GMT</pubDate>
            <atom:updated>2026-06-24T21:13:42.704Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This post is a breakdown and commentary on <strong>Ben Herzog’s Check Point Research </strong>(December 2024), <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Inside Akira Ransomware’s Rust Experiment</a> &amp; <a href="https://www.virusbulletin.com/conference/vb2025/abstracts/inside-akira-ransomwares-rust-experiment/">his talk in 2025</a>. All technical claims are grounded in the linked primary sources below. Combined with some methodologies of <strong>Cindy Xiao</strong>’s amazing reports/talks in <a href="https://github.com/cxiao/rust-reversing-workshop-recon-2024">2024</a>, <a href="https://github.com/cxiao/reconstructing-rust-types-talk-re-verse-2025">2025</a> (mainly for reconstructing types).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EchqP7I6oKpxCcXcGtuTPQ.png" /></figure><blockquote>If you haven’t read<a href="https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-1-937e0388d2c7?postPublishedType=repub"> Part 1</a> and Part 2, it’s encouraged to read the threat reports at least (see <strong>References — Threat Reports </strong>below), so the activities of the binary are clear alongside the binary analysis, including the latest <strong>Tactics, Techniques, and Procedures (TTPs).</strong></blockquote><h3>Table of Contents</h3><ul><li>Info of the binary in this analysis</li><li>Section 5: lock and Thread Spawning</li><li>Section 6: Lock_Closure and Encryption</li></ul><h4>Further Reading</h4><ul><li>1. Why UAWAVAUATSH exists</li><li>2. REX — Register Extension.</li><li>3. Mutex</li></ul><h4>References</h4><h3>Reversing Akira’s Rust Experiment: A Breakdown Part 1</h3><blockquote>This post is a breakdown and commentary on <strong>Ben Herzog’s Check Point Research </strong>(December 2024), <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Inside Akira Ransomware’s Rust Experiment</a> &amp; <a href="https://www.virusbulletin.com/conference/vb2025/abstracts/inside-akira-ransomwares-rust-experiment/">his talk in 2025</a>. All technical claims are grounded in the linked primary sources below. Combined with <strong>Cindy Xiao</strong>’s amazing reports/talks in <a href="https://github.com/cxiao/rust-reversing-workshop-recon-2024">2024</a>, <a href="https://github.com/cxiao/reconstructing-rust-types-talk-re-verse-2025">2025</a> (about reconstructing types and more).</blockquote><p>There will be a part 2 to break down the rest. I separate them so this article won’t be <strong><em>__too_long_</em>_</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpO6uNZPlZqZuD7mlYDsqg.png" /></figure><p>For this analysis, Binary Ninja (v5.3.9434) is used without enabling any plugins. <strong>Binary:</strong> akirav2.elf , SHA25:60ee1d284ed663073872012c7bde7fac5ca1121403f1a5d2d5411317df282796c.</p><h4>A note on source references</h4><blockquote>The commit hash is updated on 10th Jun 2026. <strong><em>79e9716c…</em> is rustc 1.74.0 stable</strong> (released 2023-11-16). Akirav2’s <em>.rodata</em> contains std panic-path strings of the form <em>/rustc/&lt;commit&gt;/library/...</em>.<strong><em>db034cee…</em> is a </strong><strong><em>master</em>/nightly commit from ~1 year later, </strong>which I was mistakenly pinned in the article. If you see any links related to <strong><em>db034cee… , </em></strong><em>please consider it was based on previosu wrong assumption but it works to some degree.</em></blockquote><p>The Rust standard library is under active development and files move between releases. Source links in this post are pinned to commit 79e9716c980570bfd1f666e3b16ac583f0168962 — <a href="https://releases.rs/docs/1.74.0/"><strong>rustc 1.74.0 stable</strong></a>, the toolchain that compiled this Akira v2 binary. This is recoverable directly from the binary: its .rodata embeds /rustc/79e9716c…/library/... panic paths, and it is corroborated by version-pinned FunctionID analysis resolving the sample to 1.74.0.</p><p>This matters because stdlib code is inlined directly into the final binary at compile time: what you see in the disassembly reflects the stdlib at that specific commit, not the current main branch. Following a newer version of the same file risks misidentifying inlined boilerplate or drawing incorrect conclusions about what the malware authors wrote versus what the compiler contributed.</p><blockquote>If a pinned link returns a 404, the file has likely been relocated. Navigate to the <a href="https://github.com/rust-lang/rust/tree/db034cee00570a9b82ea8b9e9e95221dbd745698">repository root</a> and search by filename.</blockquote><h3>Section 5: lock and Thread Spawning</h3><p>After flag processing, default_action calls lock, which is a thin wrapper. Its job is to spawn threads worker threads, each running lock_closure, and then join them. The structure mirrors yarnish.rs almost exactly, with the indicatif MultiProgress handle passed into each thread via Arc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*X7sSZSG3C71wdVBZz7OlWQ.png" /><figcaption>Xref panel of `lock`</figcaption></figure><p>This binary is a bit different from <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">the CheckPoint report</a> that I didn’t find tick_chars(“⠁⠂⠄⡀⢀⠠⠐⠈ “) . Instead, it showed up as UTF-8 encoding.</p><p>If you check the source code of yarnish.rs :</p><pre>pub fn main() {<br>    let mut rng = rand::rng();<br>    let started = Instant::now();<br>    let spinner_style = ProgressStyle::with_template(&quot;{prefix:.bold.dim} {spinner} {wide_msg}&quot;)<br>        .unwrap()<br>        .tick_chars(&quot;⠁⠂⠄⡀⢀⠠⠐⠈ &quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p51lKPkqHZOkx0J2dIfBUA.png" /><figcaption>In .rodata section, all the strings are combined without null-terminator</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*MJbPml7e8HSMogNLdXaQqQ.png" /><figcaption>In `default_action`, the structure is clearer with the string slice</figcaption></figure><p>If you check the disassembly of default_action , you can see the pattern of source code yarnish.rs aligned in order.</p><p><strong>Where are the </strong><strong>tick_chars ?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btztdBPokHpnhsIHA64JVg.png" /></figure><p><strong>The real situation</strong></p><p>The tick_chars(&quot;⠁⠂⠄⡀⢀⠠⠐⠈ &quot;) call is compiled in, but the <a href="https://en.wikipedia.org/wiki/Braille">Braille</a> spinner string is what is not finding. The figure above shows .rodata at 0x4414eb containing e2 a0 81 e2 a0 82 e2 a0 84 e2 a1 80 e2-a2 80 e2 a0 a0 e2 a0 90 followed by e2 a0 88 20 at 0x441500.</p><p>Decoding those as UTF-8:</p><pre>e2 a0 81 = ⠁   (U+2801)<br>e2 a0 82 = ⠂   (U+2802)<br>e2 a0 84 = ⠄   (U+2804)<br>e2 a1 80 = ⡀   (U+2840)<br>e2 a2 80 = ⢀   (U+2880)<br>e2 a0 a0 = ⠠   (U+2820)<br>e2 a0 90 = ⠐   (U+2810)<br>e2 a0 88 = ⠈   (U+2808)<br>20       = (space)</pre><p>That is exactly &quot;⠁⠂⠄⡀⢀⠠⠐⠈ &quot;, the tick string from yarnish.rs, present verbatim in .rodata. Binary Ninja has labelled this region data_4414eb and is rendering the bytes as literal dots rather than recognising the Braille Unicode. The string is there; it is a display/encoding issue in how Binary Ninja is showing that .rodata range.</p><p><strong>For </strong><strong>yarnish.rs reconstruction</strong></p><p>The tick_chars call and its argument string are both present in the binary. Your reconstructed source should include .tick_chars(&quot;⠁⠂⠄⡀⢀⠠⠐⠈ &quot;). The chain is with_template(...).unwrap().tick_chars(...), matching yarnish.rs exactly.</p><blockquote><strong>RE relevance:</strong> this is a clean example of a Unicode string literal surviving into <em>.rodata</em> with full fidelity, recoverable by UTF-8 decoding of the raw hex even when the decompiler renders it as garbage. Worth noting as a corpus evidence tier (<em>.rodata</em> string recovery) in your detection pipeline.</blockquote><h3>Reconstructing the lock function</h3><blockquote>Before beginning reconstruction, the build environment is fixed from binary evidence.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*LbyJKtFxykHP05pYtIRJiA.png" /></figure><p>The source file for lock is confirmed as akiranew/src/lock.rs from the .data.rel.ro log format metadata at 0x5e7028:</p><pre>&quot;akiranew/src/lock.rs#&gt;- File crypting... File lock started: , thread id: ...&quot;</pre><h3>The Graphic Overview of lock</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*XS-2REsbyzmHSNDPGOdGzQ.png" /></figure><h3>The yarnish.rs template</h3><p>The structural origin of lock is based on<a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">indicatif&#39;s </a><a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">yarnish.rs example</a>. The relevant section is:</p><pre>let handles: Vec&lt;_&gt; = (0..4u32)<br>    .map(|i| {<br>        let count = rng.random_range(30..80);<br>        let pb = m.add(ProgressBar::new(count));<br>        pb.set_style(spinner_style.clone());<br>        pb.set_prefix(format!(&quot;[{}/?]&quot;, i + 1));<br>        thread::spawn(move || {<br>            // ... work ...<br>            pb.finish_with_message(&quot;waiting...&quot;);<br>        })<br>    })<br>    .collect();<br>for h in handles {<br>    let _ = h.join();<br>}<br>m.clear().unwrap();</pre><p>The Akira authors adopted this skeleton and replaced the dummy work body with encryption logic, the fixed range (0..4u32) with an iterator over the file list, and the thread count with a runtime semaphore. The differences are documented in each step below.</p><h3>Step 1 — Function prologue and argument layout</h3><p><strong>Address range:</strong> 0x4d38a5 -- 0x4d38d2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*tvcXoKEe0In9fg46qWFayA.png" /></figure><pre>push rbp, r15, r14, r13, r12, rbx<br>sub  rsp, 0x2a8</pre><p>The frame size is 0x2a8 (680 bytes). Six callee-saved registers are preserved, consistent with a function that holds many live values across multiple call sites. The following comments are based on Checkpoint report, if you was investigating without reviewing it, you will see more clues later.</p><pre>int64_t* akira_v2::lock::lock(<br>    int64_t* arg1,   // Vec&lt;PathBuf&gt; -- the file list<br>    int64_t  arg2,   // thread limit (u64)<br>    char*    arg3,   // exclude regex (*const u8)<br>    int64_t* arg4    // operator options struct<br>)</pre><p>The compiler saves the incoming registers to the stack immediately after the prologue. The System V AMD64 ABI, which governs all Linux x86–64 binaries including akirav2.elf, specifies that the first six integer or pointer arguments are passed in registers rdi, rsi, rdx, rcx, r8, r9 in that order (x86-psABIs project, 2024, §3.2.3).</p><blockquote>The authoritative primary source is the <strong><em>S</em></strong><a href="https://medium.com/gitlab.com/x86-psABIs/x86-64-ABI"><strong><em>ystem V Application Binary Interface AMD64 Architecture Processor Supplement</em></strong></a>, version 1.0. Maintained at with the compiled PDF at <a href="https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf">github.com/hjl-tools/x86-psABI/wiki/x86–64-psABI-1.0.pdf</a>, section 3.2.3, Figure 3.4 (register usage table: <em>%rdi</em> = 1st argument, <em>%rsi</em> = 2nd, <em>%rdx</em> = 3rd, <em>%rcx</em> = 4th).</blockquote><p>The save sequence in the binary is:</p><pre>mov  r12,  rdi                           ; r12    = arg1 (rdi)<br>mov  qword [rsp+0x188 {var_150}], rsi   ; var_150 = arg2 (rsi)<br>mov  qword [rsp+0x38  {var_2a0}], rdx   ; var_2a0 = arg3 (rdx)<br>mov  qword [rsp+0x40  {var_298}], rcx   ; var_298 = arg4 (rcx)</pre><p>The compiler does not save in ABI order, it schedules saves however suits instruction throughput. The mapping from ABI position to stack slot must be read from the registers, not from the order of the mov instructions.</p><blockquote><strong><em>arg1</em> is </strong><strong><em>Vec&lt;PathBuf&gt;</em> confirmed</strong> from the later <em>imul rcx, [r12+0x10], 0x18</em> (<em>capacity * 24</em>, where 24 = <em>sizeof(PathBuf)</em> = ptr + len + cap = 3 × 8 bytes).</blockquote><p>The semantic labels for arg2 (rsi / var_150), arg3 (rdx / var_2a0), and arg4 (rcx / var_298) are <strong>training-derived</strong>, which of these holds the thread limit, the exclude regex pointer, and the operator options struct requires tracing the read sites of each stack variable through the function body. Binary Ninja&#39;s resolved signature labels them arg2: int64_t, arg3: char*, arg4: int64_t*, but the semantic assignment cannot be confirmed from the prologue alone.</p><h3>Step 2 — ProgressStyle initialisation</h3><p><strong>Address range:</strong> 0x4d38cb -- 0x4d390c</p><p>This is the direct binary equivalent of yarnish.rs:</p><pre>let spinner_style = ProgressStyle::with_template(&quot;...&quot;).unwrap().tick_chars(&quot;...&quot;);</pre><pre>lea  rsi, [rel data_441490[0x24]]   ; template string in .rodata<br>lea  r15, [rsp+0x100 {var_1d8}]     ; destination on stack<br>push 0x37 / pop rdx                 ; template length = 55 bytes<br>mov  rdi, r15<br>call indicatif::style::ProgressStyle::with_template  ; 0x4d38e0</pre><p>The with_template call returns Result&lt;ProgressStyle, TemplateError&gt;. The Result-returning signature confirms indicatif &gt;= 0.17.0 (versions prior to 0.17 returned ProgressStyle directly). The .rodata panic path confirms 0.17.7 exactly.</p><pre>call core::result::Result::unwrap    ; 0x4d38f4<br>call indicatif::style::ProgressStyle::tick_chars  ; 0x4d3904</pre><p>The completed ProgressStyle lives in r15 / var_1d8 for the duration of the function.</p><h3>Step 3 — MultiProgress and Arc allocation</h3><p><strong>Address range:</strong> 0x4d390c -- 0x4d3951</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*SzYy60ExNo7ucDx5yXgr6g.png" /></figure><p>Two consecutive exchange_malloc calls allocate the MultiProgress and its internal shared state. Both follow the same Arc field initialisation pattern:</p><pre>call alloc::alloc::exchange_malloc  ; size=0x8, align=0x8 (first call)<br>mov  qword [rax],     r13  {0x1}    ; ArcInner.strong = 1<br>mov  qword [rax+0x8], r13  {0x1}    ; ArcInner.weak   = 1<br>and  dword [rax+0x10], 0x0          ; ArcInner.data zeroed</pre><p>The field offsets are <strong>Verified</strong> from the pinned stdlib source at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/alloc/src/sync.rs">library/alloc/src/sync.rs</a>. ArcInner&lt;T&gt; is declared #[repr(C)], which guarantees field order matches declaration order. The fields in source order are:</p><pre>#[repr(C)]<br>struct ArcInner&lt;T: ?Sized&gt; {<br>    strong: atomic::AtomicUsize,   // +0x00, 8 bytes on x86-64<br>    weak:   atomic::AtomicUsize,   // +0x08, 8 bytes on x86-64<br>    data:   T,                     // +0x10 (for T with align &lt;= 8)<br>}</pre><p>Arc::new initialises both counts to 1, confirmed in the same source file:</p><pre>let x: Box&lt;_&gt; = Box::new(ArcInner {<br>    strong: atomic::AtomicUsize::new(1),<br>    weak:   atomic::AtomicUsize::new(1),<br>    data,<br>});</pre><p>The #[repr(C)] annotation is load-bearing: without it, Rust&#39;s default repr(Rust) would permit field re-ordering and the offset claim would not be verifiable from source inspection alone.</p><pre>call alloc::alloc::exchange_malloc   ; size=0x30, align=0x8 (second call)<br>; same initialisation pattern, larger payload</pre><p>The 48-byte second allocation is the MultiProgress inner state. These correspond to MultiProgress::new() in yarnish.rs. No MultiProgress::new symbol survives in the binary because the constructor is fully inlined.</p><h3>Step 4 — File iterator construction</h3><p><strong>Address range:</strong> 0x4d397d -- 0x4d39b0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*-lZkx56dq621onNfpKT0uw.png" /></figure><p>This is the single most important structural divergence from yarnish.rs. The yarnish.rs example iterates (0..4u32) which is a fixed range. Akira iterates the file list directly:</p><pre>mov  rax, qword [r12]           ; rax = files.ptr<br>mov  rdx, qword [r12+0x8]       ; rdx = files.len<br>imul rcx, qword [r12+0x10], 0x18  ; rcx = files.cap * 24<br>add  rcx, rax                   ; rcx = end pointer (ptr + cap*stride)<br>mov  qword [r15 {var_1d8}],       rax  ; IntoIter.buf   = ptr<br>mov  qword [r15+0x8 {var_1d0}],   rdx  ; IntoIter.len   = len<br>mov  qword [r15+0x10 {var_1c8}],  rax  ; IntoIter.start = ptr<br>mov  qword [r15+0x18 {i_1}],      rcx  ; IntoIter.end   = end ptr</pre><p>The imul multiplier 0x18 (24) equals sizeof(PathBuf) on x86-64: PathBuf = Vec&lt;u8&gt; = (ptr: *mut u8, len: usize, cap: usize) = 3 × 8 = 24 bytes. This construction is the IntoIter&lt;PathBuf&gt; struct being built on the stack.</p><p><strong>Loop head at </strong><strong>0x4d39b0:</strong></p><pre>cmp  rax, rcx   ; current_ptr == end_ptr?<br>je   0x4d3a22   ; yes → drop IntoIter and exit</pre><p><strong>Loop exit at </strong><strong>0x4d3a22:</strong></p><pre>call _$LTalloc..vec..into_it...op..Drop$GT$::drop</pre><p>The IntoIter destructor runs when the file list is exhausted. This is the outer boundary of the entire map(...).collect() equivalent.</p><h3>Step 5 — Per-iteration seed generation (Akira-specific)</h3><p><strong>Address range:</strong> 0x4d3c69 -- 0x4d3d1c</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*PJGJ4hVw6MzZJ6En7LxtNw.png" /></figure><p>There is no equivalent in yarnish.rs. This block is unique to Akira.</p><p><strong>SystemTime::now and </strong><strong>duration_since</strong>(symbol names read directly from disassembly). Signatures are defined in the pinned stdlib at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/time.rs">library/std/src/time.rs</a>. SystemTime::now() returns the current wall-clock time. SystemTime::duration_since returns Result&lt;Duration, SystemTimeError&gt;; the jne 0x4d42de at 0x4d3c82 is the error branch for the SystemTimeError case (time went backwards).</p><pre>call std::time::SystemTime::now         ; 0x4d3c69 -- Verified<br>mov  qword [rsp+0x50 {var_288}], rax    ; store seconds<br>mov  dword [rsp+0x58 {var_280_1}], edx  ; store subsec_nanos<br>mov  rdi, r12  {var_1d8}<br>mov  rsi, r13  {var_288}<br>call std::time::SystemTime::duration_since  ; 0x4d3c7d -- Verified<br>cmp  qword [rsp+0x100 {var_1d8}], 0x0<br>jne  0x4d42de                           ; error path</pre><p><strong>getpid</strong>(symbol name read directly from disassembly). getpid() is a POSIX system call returning the calling process&#39;s PID as pid_t (a 32-bit integer on Linux x86-64), returned in eax (<a href="https://man7.org/linux/man-pages/man2/getpid.2.html">Linux man page: getpid(2)</a>).</p><pre>call qword [rel getpid]                 ; 0x4d3c99 -- Verified<br>mov  dword [rsp+0x98 {var_240_1}], eax  ; pid stored as u32<br>mov  byte  [rsp+0xa8 {var_230_1}], 0x1<br>mov  qword [rsp+0x9c {var_23c_1}], 0xde ; constant -- see note below<br>and  dword [rsp+0xa4 {var_234_1}], 0x0</pre><blockquote><strong>Note on </strong><strong><em>0xde</em>:</strong> the constant at <em>+0x9c</em> is binary-observed. Its semantic meaning whether it is a version tag, a seed format discriminant, or an unrelated constant is <strong>unknown</strong> and cannot be determined without source code for <em>akiranew</em>.</blockquote><p><strong>HashStruct::hash</strong> (mangled symbol name read from disassembly). This is an internal function in the akiranew workspace crate; no public source is available. The 64-byte output size is <strong>hand-calculated</strong> from the four consecutive movups instructions each loading 16 bytes (4 × 16 = 64):</p><pre>call akira_v2::prng::HashStruct::hash::h869e36ed471afafc  ; 0x4d3ce0 -- Verified (symbol)<br>movups xmm0, xmmword [rsp+0x50 {var_288}]   ; bytes  0-15  -- Hand-calculated<br>movups xmm1, xmmword [rsp+0x60 {var_278}]   ; bytes 16-31<br>movups xmm2, xmmword [rsp+0x90 {var_248_1}] ; bytes 32-47<br>movups xmm3, xmmword [rsp+0xa0 {var_23c_1+0x4}] ; bytes 48-63</pre><p>The interpretation of these 64 bytes as encryption key material is <strong>functional inference</strong>, the output is passed into the closure capture struct (Step 8) and ultimately into lock_closure, but the claim that it constitutes a key rather than, say, an IV or a nonce requires further analysis of lock_closure to confirm.</p><p><strong>Log string evidence </strong>(binary-observed from .data.rel.ro at data_5e7018 / 0x5e7018): the string &quot;File crypting... File lock started: , thread id: ...&quot; is emitted from akiranew/src/lock.rs and references a thread ID, consistent with getpid() being used to identify threads. This is corroborating evidence, not proof of the key derivation mechanism.</p><h3>Step 6 — ProgressBar construction and MultiProgress::add</h3><p><strong>Address range:</strong> 0x4d3d29 -- 0x4d3d83</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*rvyg7NXoC3ZcANSwy3KfyA.png" /></figure><pre>call alloc::alloc::exchange_malloc  ; size=0x58 (88 bytes) -- ProgressBar Arc<br>mov  qword [rax],     r15  {0x1}    ; strong = 1<br>mov  qword [rax+0x8], r15  {0x1}    ; weak   = 1<br>and  dword [rax+0x10], 0x0<br>mov  byte  [rax+0x14], 0x0<br>lea  rdi,  [rax+0x15]</pre><pre>push 0x43 / pop rdx  {0x43}         ; length = 67 -- the file path string length<br>call qword [rel data_611b10] {memcpy}  ; copy file path into ProgressBar prefix</pre><p>The file path (67 bytes) is copied directly into the ProgressBar internal buffer. In yarnish.rs, the prefix is format!(&quot;[{}/?]&quot;, i + 1). In Akira, it is the target file path, giving the operator a live view of which file is being encrypted on each progress bar line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*EsQJBN2HbU7jnPlHPVsA1w.png" /></figure><pre>call indicatif::draw_target::...DrawTarget::stderr   ; 0x4d3d65<br>call indicatif::progress_bar::...::with_draw_target  ; 0x4d3d73<br>call indicatif::multi::MultiProgress::add            ; 0x4d3d83</pre><p>This is let pb = m.add(ProgressBar::new(count)) from yarnish.rs, expanded into three calls because ProgressBar::new and the draw target setup are not merged by the compiler at this optimisation level. The result (the managed ProgressBar) is held in r13 / var_288.</p><h3>Step 7 — Shared mutex and thread-limit semaphore</h3><p><strong>Address range:</strong> 0x4d3d91 -- 0x4d3dab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*4Q4G_fRfPdgNEl_IHCLXCQ.png" /></figure><h4>Mutex&lt;T&gt;::lock and Result::unwrap</h4><blockquote>The source for <em>Mutex::lock</em> at the pinned commit is at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sync/mutex.rs"><em>library/std/src/sync/mutex.rs</em></a> .</blockquote><pre>call std::sync::mutex::Mutex&lt;T&gt;::lock   ; 0x4d3d91 -- Verified<br>call core::result::Result::unwrap       ; 0x4d3da3 -- Verified</pre><p>The mutex at data_5ebe00 is a static object in .data.rel.ro. The claim that it is distinct from the MultiProgress internal mutex is a <strong>functional inference</strong> based on two different static addresses appearing at two different mutex call sites in the disassembly. What data_5ebe00 actually guards requires tracing its read sites, the thread-limit interpretation is not binary-confirmed.</p><p>Further into the loop body:</p><pre>call std::thread::scoped::Sco...um_running_threads::hb34fb126c362d0f3  ; 0x4d4062</pre><h4>std::thread::scoped::Scope::num_running_threads.</h4><blockquote>The function lives inside <em>ScopeData</em> in <a href="https://doc.rust-lang.org/src/std/thread/scoped.rs.html"><em>library/std/src/thread/scoped.rs</em></a>:</blockquote><pre>pub(super) struct ScopeData {<br>    num_running_threads: Atomic&lt;usize&gt;,<br>    a_thread_panicked:   Atomic&lt;bool&gt;,<br>    main_thread:         Thread,<br>}</pre><p>Scoped threads were stabilised at Rust <strong>1.63.0</strong>, confirmed by the #[stable(feature = &quot;scoped_threads&quot;, since = &quot;1.63.0&quot;)] attribute visible in the same source file. The toolchain used to compile akirav2.elf is nightly-2024-10-06, which is well past 1.63, so the stable API is available.</p><p>The claim that num_running_threads is used as a semaphore enforcing arg2 as a thread limit is <strong>functional inference</strong>, the observation is that num_running_threads is called before Thread::new in the loop body, which is consistent with a throttle. The exact blocking mechanism (whether the loop spins, parks, or uses a condition variable, <em>A.K.A. condvar</em>) requires further disassembly of the code between 0x4d4062 and 0x4d3e7e.</p><h3>Step 8 — Closure capture struct construction</h3><p><strong>Address range:</strong> 0x4d406d -- 0x4d40a0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*FucGvN15mOs3603tqULEBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*FVAHCBIGxnp0SfYooJzR-A.png" /><figcaption>Review `r13`</figcaption></figure><p><strong>exchange_malloc size and alignment</strong>:</p><pre>call alloc::alloc::exchange_malloc   ; size=0x58 (88 bytes), align=0x8</pre><p>The field mapping for closure fields +0x00, +0x08, +0x10 is therefore:</p><pre>+0x00  r14  -- (ptr-sized value)<br>+0x08  rbx  -- (ptr-sized value)<br>+0x10  r13  -- output_capture: Option&lt;Arc&lt;Mutex&lt;Vec&lt;u8&gt;&gt;&gt;&gt; (return value of set_output_capture at 0x4d4026)<br>+0x18  xmm0 -- 16 bytes from HashStruct::hash output<br>+0x28  rcx  -- pointer (var_268)<br>+0x30  rcx  -- pointer (var_2b0)<br>+0x38  rcx  -- pointer (var_148_1)</pre><p><strong>+0x10 resolved:</strong> At 0x4d4026, r13 is assigned the return value of std::io::stdio::set_output_capture, which returns Option&lt;Arc&lt;Mutex&lt;Vec&lt;u8&gt;&gt;&gt;&gt;, the previous stdout capture handle. The test rax, rax / je 0x4d403e / lock inc qword [r13] sequence immediately after (binary-observed) is the Option&lt;Arc&gt; handling: if Some, bump the refcount; if None, skip. This matches the output_capture variable captured by the main shim closure in the verified thread.rs source at the pinned commit:</p><pre>crate::io::set_output_capture(output_capture);</pre><h4>PathBuf layout</h4><p>The layout of PathBuf on x86_64-unknown-linux-gnu at the pinned commit is (ptr, len, cap) = 3 × 8 = 24 bytes.</p><p>The proof chain is:</p><pre>PathBuf { inner: OsString }<br>  → OsString { inner: Buf }<br>    → #[repr(transparent)] pub struct Buf { pub inner: Vec&lt;u8&gt; }<br>      → Vec&lt;u8&gt; = (ptr: *mut u8, len: usize, cap: usize)</pre><ul><li>PathBuf { inner: OsString } (single-field, <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/path.rs#L1174">library/std/src/path.rs</a>)</li><li>OsString { inner: Buf } (single-field, <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/ffi/os_str.rs#L1710">library/std/src/ffi/os_str.rs</a>)</li><li>#[repr(transparent)] pub struct Buf { pub inner: Vec&lt;u8&gt; } <br>(<strong>Verified</strong> from <a href="https://doc.rust-lang.org/nightly/src/std/sys/os_str/bytes.rs.html">library/std/src/sys/os_str/bytes.rs</a>)</li><li>Vec&lt;u8&gt; = (ptr: *mut u8, len: usize, cap: usize) = 3 × 8 = 24 bytes.</li></ul><p>The #[repr(transparent)] on Buf is the load-bearing guarantee: it makes the Vec&lt;u8&gt; equivalence a language specification rather than a compiler implementation detail. The two outer single-field structs (PathBuf, OsString) are not formally repr(transparent) and their layout is technically an implementation detail, but the chain is consistent with the imul rcx, [r12+0x10], 0x18 stride evidence in Step 4.</p><p>The field mapping for closure fields +0x00, +0x08, +0x10 is therefore:</p><pre>+0x00  r14  -- Vec&lt;u8&gt;.ptr  (PathBuf data pointer)<br>+0x08  rbx  -- Vec&lt;u8&gt;.len  (PathBuf byte length)<br>+0x10  r13  -- output_capture: Option&lt;Arc&lt;Mutex&lt;Vec&lt;u8&gt;&gt;&gt;&gt; (set_output_capture return value -- see above)</pre><p>Note that +0x10 is <strong>not</strong> Vec&lt;u8&gt;.cap. The r13 register was loaded from set_output_capture at 0x4d4026, not from the PathBuf capacity field. The capacity field of PathBuf is not stored in the closure -- only ptr and len are needed to reference the file path slice inside lock_closure.</p><p><strong>+0x18 key material: Functional inference.</strong> The movups xmmword [rax+0x18], xmm0 stores the value in xmm0, which was loaded from the HashStruct::hash output region in Step 5. This is a register-trace inference across intervening instructions, not a direct binary observation of the key derivation path end-to-end.</p><p><strong>Fields beyond </strong><strong>+0x38.</strong> The exact field count and types beyond +0x38 require further disassembly of lock_closure.</p><h3>Step 9 — First Thread::new: the encryption thread</h3><p><strong>Address range:</strong> 0x4d3e6f -- 0x4d3e91</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*LoJleYQppMnnYhNzOmr-kA.png" /><figcaption>Disassembly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHHYyGRKBR3MaovrxiBb1g.png" /><figcaption>HLIL in Binary Ninja</figcaption></figure><h3>Starting from High Level IL</h3><p><strong>Thread::new call site (</strong><strong>0x4d3e7e):</strong></p><pre>char const (** rax_24)[0x28] =<br>    std::thread::Thread::new::h977b0e8df4ff7524()</pre><p>Binary Ninja has typed rax_24 as char const (**)[0x28], a pointer to a pointer to a 0x28-byte (40-byte) array. This is Binary Ninja&#39;s best-effort type inference for the return value. The key observation is that rax_24 is a <strong>pointer</strong>, not an integer. Thread::new is returning a pointer in rax.</p><p><strong>0x4d3e83:</strong></p><pre>char const (** var_2c0)[0x28] = rax_24</pre><p>The return value is stored into var_2c0.</p><p><strong>0x4d3e8d:</strong></p><pre>char const (* temp5_1)[0x28] = *rax_24<br>*rax_24 = &amp;(**rax_24)[1]</pre><p>This is the lock inc in HLIL form. Binary Ninja has lifted it as: dereference rax_24 to get temp5_1 (the current value), then write (**rax_24)[1] back, i.e., increment the qword at the address rax_24 points to. This is an atomic increment of a counter at the address returned by Thread::new.</p><p><strong>0x4d3e91:</strong></p><pre>if (temp5_1 s&gt; -1)</pre><p>This is the jle 0x4d42da overflow check. The s&gt; -1 (signed greater than -1) is the jle taken when the incremented value was ≤ -1 (i.e., overflow/underflow). This is exactly the Arc refcount overflow guard from <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/alloc/src/sync.rs">sync.rs</a>:</p><pre>if old_size &gt; MAX_REFCOUNT { abort(); }</pre><p><strong>0x4d3e9a: the </strong><strong>else branch (overflow path):</strong></p><pre>uint64_t rax_25 = alloc::alloc::exchange_malloc::hc6dbbe43d4abbe5a .1241<br>*rax_25 = 1<br>*(rax_25 + 8) = 1<br>*(rax_25 + 0x10) = zx.o(0)<br>var_268 = rax_25</pre><p>A fresh allocation of size .1241 (some allocation size). Two fields set to 1, third field zeroed. This is <strong>another </strong><strong>Arc allocation: </strong>strong=1, weak=1, data=0. The var_268 assignment is storing this new Arc pointer. This is the JoinHandle&#39;s packet Arc being allocated in the success path of Thread::new.</p><h3>Then Disassembly</h3><pre>call std::sys_common::thread::min_stack   ; 0x4d3e6f<br>mov  qword [rsp+0x1b0 {var_128_1}], rax<br>xor  edi, edi  {0x0}                      ; stack = 0 (use default)<br>call std::thread::Thread::new             ; 0x4d3e7e</pre><p><strong>std::thread::Thread::new is observed at </strong><strong>0x4d3e7e.</strong> The symbol name is read directly from the disassembly. The pinned source is at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">library/std/src/sys/pal/unix/thread.rs</a>:</p><pre>pub unsafe fn new(stack: usize, p: Box&lt;dyn FnOnce()&gt;) -&gt; io::Result&lt;Thread&gt;</pre><p>The xor edi, edi setting stack = 0 is verified against the Thread::new source: when stack = 0 is passed, the implementation uses cmp::max(0, min_stack_size(&amp;attr)), which collapses to min_stack_size. min_stack is called at 0x4d3e6f immediately before to cache that value.</p><p>The implementation details (double-boxing, Box::into_raw(Box::new(p)), pthread_create, thread_start) are <strong>Verified</strong> from <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">library/std/src/sys/pal/unix/thread.rs</a> at commit db034cee:</p><pre>let p = Box::into_raw(Box::new(p));</pre><p>and <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs#L99">thread_start</a> is the extern &quot;C&quot; callback at the end of <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs#L48">Thread::new</a> in the same file. After Thread::new returns:</p><pre>mov  qword [rsp+0x18 {var_2c0}], rax<br>lock inc qword [rax]                ; Arc refcount bump</pre><p><strong>lock inc: Binary Ninja HLIL evidence.</strong> The HLIL at 0x4d3e7e--0x4d3e91 reads:</p><pre>char const (** rax_24)[0x28] =<br>    std::thread::Thread::new::h977b0e8df4ff7524()<br>char const (** var_2c0)[0x28] = rax_24<br>char const (* temp5_1)[0x28] = *rax_24<br>*rax_24 = &amp;(**rax_24)[1]          // ← this is the lock inc<br>if (temp5_1 s&gt; -1) { ... }        // ← overflow guard</pre><p>The overflow guard if (temp5_1 s&gt; -1) matches the Arc refcount overflow check in pasted <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/alloc/src/sync.rs">alloc/src/sync.rs</a>:</p><pre>if old_size &gt; MAX_REFCOUNT { abort(); }</pre><p>where MAX_REFCOUNT = (isize::MAX) as usize .</p><blockquote>On x86–64, <em>isize::MAX = 2^63 - 1 = 9_223_372_036_854_775_807 = 0x7fff_ffff_ffff_ffff</em>.</blockquote><p>At the pinned commit, Thread is defined in <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/mod.rs">library/std/src/thread/mod.rs</a> as:</p><pre>pub struct Thread(Inner);<br><br>enum Inner {<br>    Main(&amp;&#39;static (ThreadId, Parker)),<br>    Other(Pin&lt;Arc&lt;OtherInner&gt;&gt;),<br>}</pre><p>The Arc being incremented by lock inc is therefore the Arc&lt;OtherInner&gt; inside Inner::Other, accessed via the Thread handle returned from Thread::new.</p><p>The subsequent basic block at 0x4d3e9a allocates JoinInner::packet :</p><pre>struct JoinInner&lt;&#39;scope, T&gt; {<br>    native: imp::Thread,<br>    thread: Thread,<br>    packet: Arc&lt;Packet&lt;&#39;scope, T&gt;&gt;,<br>}</pre><p>The Arc&lt;Packet&gt; is the communication channel between the spawned thread and its JoinHandle.</p><p>Then immediately:</p><pre>xor  edi, edi<br>call std::io::stdio::set_output_capture   ; 0x4d3ec4</pre><p>This is inside the inlined main shim closure body. The main shim is constructed in Builder::spawn_unchecked_ in <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/mod.rs">library/std/src/thread/mod.rs</a> . The shim at db034cee is:</p><pre>let main = move || {<br>    if let Err(_thread) = set_current(their_thread.clone()) {<br>        rtabort!(&quot;something here is badly broken!&quot;);<br>    }<br>    if let Some(name) = their_thread.cname() {<br>        imp::Thread::set_name(name);<br>    }<br>    crate::io::set_output_capture(output_capture);<br>    let f = f.into_inner();<br>    let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {<br>        crate::sys::backtrace::__rust_begin_short_backtrace(f)<br>    }));<br>    ...</pre><p>set_output_capture is defined at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/io/stdio.rs">library/std/src/io/stdio.rs</a>. It returns Option&lt;Arc&lt;Mutex&lt;Vec&lt;u8&gt;&gt;&gt;&gt;, the previous capture state. xor edi, edi passes None (null pointer as the first argument), confirmed by the SysV ABI (rdi = first argument, cited in Step 1 via x86-psABIs v1.0 §3.2.3).</p><h3>Step 10 — Second Thread::new: the indicatif ticker thread</h3><p><strong>Address range:</strong> 0x4d3fbf -- 0x4d4016</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*nSJlx0mT3NnIsmzeBSagsA.png" /></figure><p><a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs"><strong>yarnish.rs</strong></a><strong> line </strong><a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs#L76"><strong>pb.set_style(spinner_style.clone())</strong></a><strong>:</strong></p><pre>let handles: Vec&lt;_&gt; = (0..4u32)<br>        .map(|i| {<br>            let count = rng.gen_range(30..80);<br>            let pb = m.add(ProgressBar::new(count));<br>            pb.set_style(spinner_style.clone());<br>            pb.set_prefix(format!(&quot;[{}/?]&quot;, i + 1));<br>            thread::spawn(move || {<br>                let mut rng = rand::thread_rng();<br>                let pkg = PACKAGES.choose(&amp;mut rng).unwrap();<br>                for _ in 0..count {<br>                    let cmd = COMMANDS.choose(&amp;mut rng).unwrap();<br>                    thread::sleep(Duration::from_millis(rng.gen_range(25..200)));<br>                    pb.set_message(format!(&quot;{pkg}: {cmd}&quot;));<br>                    pb.inc(1);<br>                }<br>                pb.finish_with_message(&quot;waiting...&quot;);<br>            })<br>        })<br>        .collect();</pre><p>This block maps directly to yarnish.rs lines 34--36 at commit <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs#L29">0c037edc</a>:</p><pre>pb.set_style(spinner_style.clone());     // yarnish.rs line 34<br>pb.set_prefix(format!(&quot;[{}/?]&quot;, i + 1)); // yarnish.rs line 35<br>thread::spawn(move || { ... })           // yarnish.rs line 36</pre><p><strong>Ticker::drop_in_place at </strong><strong>0x4d3f95</strong>. This is dropping the Ticker handle from the <strong>previous loop iteration</strong>, not spawning a new thread. The Ticker is an indicatif-internal struct managing the spinner animation.</p><pre>call core::ptr::drop_in_place...ss_bar..Ticker$GT$  ; 0x4d3f95 -- Verified</pre><p><strong>pb.set_style(spinner_style.clone())</strong> (mapped to yarnish.rs line 34). ProgressStyle::clone produces the cloned style; set_style applies it to the ProgressBar:</p><pre>call _$LT$indicatif::style::...Clone$GT$::clone     ; 0x4d3fbf -- Verified<br>                                                     ; = spinner_style.clone()<br>mov  rdi, qword [rsp+0x50 {var_288}]<br>mov  rsi, r12  {var_1d8}<br>call indicatif::progress_bar::...ressBar::set_style  ; 0x4d3fd1 -- Verified<br>                                                     ; = pb.set_style(...)</pre><h4><strong>thread::spawn(move || { ... }) -- the spawn call:</strong></h4><p>This is the <strong>same encryption thread</strong> spawn as Step 9, not a separate ticker thread. The thread::spawn call chain is inlined; Thread::new at 0x4d3fe3 is its innermost call:</p><pre>call std::sys_common::thread::min_stack              ; 0x4d3fd9 -- Verified<br>mov  r15, rax<br>xor  edi, edi                                        ; stack = 0 (default)<br>call std::thread::Thread::new                        ; 0x4d3fe3 -- Verified<br>                                                     ; = thread::spawn(move || {...})</pre><p>ProgressStyle::clone + set_style before Thread::new does <strong>not</strong> indicate a separate enable_steady_tick ticker thread. It maps to pb.set_style(spinner_style.clone()) in yarnish.rs. There is only <strong>one</strong> encryption-related Thread::new call visible in the screenshots provided. Whether enable_steady_tick spawns a second thread cannot be confirmed without additional disassembly showing a second Thread::new call.</p><p><strong>Arc::new and </strong><strong>lock inc after </strong><strong>Thread::new</strong> -- <strong>Verified</strong> as part of JoinInner construction (established from HLIL in Step 9):</p><pre>call alloc::sync::Arc&lt;T&gt;::new        ; 0x4d4008 -- Verified<br>mov  qword [rsp+0x70 {var_268}], rax<br>lock inc qword [rax]                 ; 0x4d4012 -- Verified (Arc::clone)</pre><p>Arc::clone confirmed from pasted <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/alloc/src/sync.rs">alloc/src/sync.rs</a>.</p><h3>Step 11 —Mutex-protected Vec::push and loop back-edge</h3><p><strong>Address range:</strong> 0x4d39e0 -- 0x4d3a20</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*ZU1uHNJq0q89mTm4l4d09A.png" /></figure><p>The Vec::push at 0x4d39ff does not occur in isolation, it is wrapped in a Mutex::lock guard:</p><pre>004d39e0   call std::sync::mutex::Mutex&lt;T&gt;::lock    ; acquire Mutex&lt;Vec&lt;JoinHandle&gt;&gt;<br>004d39eb   mov  rsi, r12  {data_5e7080}<br>004d39ee   call core::result::Result::unwrap<br>004d39f3   mov  r13, rax                            ; r13 = MutexGuard<br>004d39ff   call alloc::vec::Vec::push               ; push JoinHandle under guard<br>004d3a0b   call core::ptr::drop_in_place(...)       ; drop MutexGuard (unlock)<br>004d3a10   mov  rax, qword [rsp+0x110 {var_1c8}]    ; IntoIter.start advance<br>004d3a18   mov  rcx, qword [rsp+0x118 {i_1}]        ; IntoIter.end<br>004d3a20   jmp  0x4d39b0                            ; loop back-edge</pre><p><strong>The </strong><strong>Mutex is Akira&#39;s own code, not from the stdlib -- Verified</strong> from the pasted <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/scoped.rs">library/std/src/thread/scoped.rs</a>. ScopeData contains no Mutex whatsoever:</p><pre>pub(super) struct ScopeData {<br>    num_running_threads: AtomicUsize,<br>    a_thread_panicked: AtomicBool,<br>    main_thread: Thread,<br>}</pre><p>The scope() function waits for all threads using park/unpark exclusively -<strong>(Verified</strong> from the pasted scoped.rs):</p><pre>while scope.data.num_running_threads.load(Ordering::Acquire) != 0 {<br>    park();<br>}</pre><p>Each finishing thread calls self.main_thread.unpark() via decrement_num_running_threads. There is no Mutex, no Condvar, and no Vec anywhere in the scoped thread stdlib machinery at db034cee. The Mutex at data_5e7080 therefore belongs to akiranew/src/lock.rs.</p><p><strong>What the </strong><strong>Mutex guards -- unknown.</strong> The Vec::push argument is var_d0 / r15 (binary-observed). Tracing r15 back to its assignment site has not been completed from the available screenshots. The guarded Vec could hold encrypted file paths, progress records, ransom note entries, or something else entirely. The earlier label Vec&lt;JoinHandle&gt; was <strong>wrong</strong> and is retracted -- scoped threads do not need a Mutex&lt;Vec&gt; for handle management.</p><ul><li><strong>Mutex::lock</strong> : Source at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sync/mutex.rs">library/std/src/sync/mutex.rs</a>.</li><li><strong>Vec::push</strong>: Source at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/alloc/src/vec/mod.rs">library/alloc/src/vec/mod.rs</a>.</li><li><strong>MutexGuard drop: Verified</strong> (symbol binary-observed).</li><li><strong>Loop back-edge</strong> — <strong>Verified</strong> (binary-observed). jmp 0x4d39b0 returns to the loop head from Step 4.</li><li><strong>yarnish.rs comparison:</strong> No mutex appears in the yarnish.rs template at <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs#L29">0c037edc</a>. The presence of a mutex-protected Vec::push in every loop iteration is an Akira-specific addition whose purpose requires further analysis of lock.rs.</li></ul><blockquote>More details about tracing back mutex can be found in the sectin of <strong>Further Reading</strong> below.</blockquote><p><strong>Akira deviation from </strong><strong>yarnish.rs:</strong> The yarnish.rs template at commit <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs#L29">0c037edc</a> pushes handles into a plain Vec&lt;_&gt; with no mutex:</p><pre>}).collect();</pre><p>Akira wraps the Vec&lt;JoinHandle&gt; in a Mutex, acquiring it before each push. This is <strong>binary-observed</strong>, no such mutex appears in yarnish.rs. The mutex at data_5e7080 is distinct from the one at data_5ebe00 seen in Step 7.</p><h3>Step 11b — Real Thread::new: sys::unix::thread::Thread::new</h3><p><strong>Address range:</strong> 0x4d4062 -- 0x4d40d2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pa8vVUhMQVaVX-pWzuRlmQ.png" /><figcaption>High Level IL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*Myy9lC9CGUYzmtWRH9k1eA.png" /><figcaption>Disassembly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iEODm9uHrFBp5hFOb3DHg.png" /><figcaption>Graphi View</figcaption></figure><p>The graph view reveals the <strong>actual</strong> pthread_create-invoking Thread::new, which was not visible in the earlier screenshots.</p><p><strong>num_running_threads and closure struct</strong>:</p><pre>004d405e   add  rdi, 0x10<br>004d4062   call std::thread::scoped::Sco...um_running_threads  ; semaphore check</pre><p>Immediately after the semaphore check, the closure capture struct is built:</p><pre>004d406d   push 0x58 / pop rdi {0x58}              ; size = 88 bytes<br>004d406c   push 0x8  / pop rsi {0x8}               ; align = 8<br>004d406d   call alloc::alloc::exchange_malloc      ; allocate closure struct</pre><p>Then 14 mov instructions fill the struct fields from stack variables (var_288, var_278, var_2b0, var_148_1, var_150, var_2a8 etc.) followed by two movups for the XMM key material, and at 0x4d40cb:</p><pre>004d40cb   lea  rcx, [rel data_5e66a8]              ; vtable pointer</pre><p>Then the actual spawn:</p><pre>004d40d2   call std::sys::unix::thread::Thread::new::hd257ed4d46662134</pre><blockquote><strong>This is a different mangled symbol from </strong><strong>0x4d3e7e</strong> (h977b0e8df4ff7524).</blockquote><p>The symbol hd257ed4d46662134 resolves to std::sys::unix::thread::Thread::new, the PAL-level function in <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">library/std/src/sys/pal/unix/thread.rs</a> that calls pthread_create directly. This is imp::Thread::new in the spawn_unchecked_ closing lines (<strong>Verified</strong> from <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/mod.rs">library/std/src/thread/mod.rs</a>):</p><pre>Ok(JoinInner {<br>    native: unsafe { imp::Thread::new(stack_size, main)? },<br>    thread: my_thread,<br>    packet: my_packet,<br>})</pre><p>JoinInner is defined in <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/mod.rs">library/std/src/thread/mod.rs</a>:</p><pre>struct JoinInner&lt;&#39;scope, T&gt; {<br>    native: imp::Thread,<br>    thread: Thread,<br>    packet: Arc&lt;Packet&lt;&#39;scope, T&gt;&gt;,<br>}</pre><p>Thread at db034cee is pub struct Thread(Inner) where Inner is an enum with Other(Pin&lt;Arc&lt;OtherInner&gt;&gt;)<strong>(Verified</strong> from <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/mod.rs">library/std/src/thread/mod.rs</a>).</p><p><strong>Error path after </strong><strong>Thread::new</strong>:</p><pre>004d40f2   call core::ptr::drop_in_place...P$$RPS$GT$  ; drop Box&lt;dyn FnOnce()&gt;<br>004d40fc   call core::ptr::drop_in_place...Thread$GT$  ; drop partial Thread</pre><p>This matches the verified sys/pal/unix/thread.rs source:</p><pre>return if ret != 0 {<br>    drop(Box::from_raw(p));   // drop the double-boxed closure<br>    Err(io::Error::from_raw_os_error(ret))<br>} else {<br>    Ok(Thread { id: native })<br>};</pre><p>The data_5e66a8 vtable pointer at 0x4d40cb is the Box&lt;dyn FnOnce()&gt; vtable, the call_once slot pointing to the main shim, as described in the <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">report </a>(Herzog, 2024, Figures 24--26).</p><h3>Step 12 — Loop back-edge and IntoIter drop</h3><p><strong>Address range:</strong> 0x4d3a10 -- 0x4d3a22</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*koK811fJTdK3MFSBjfxBIQ.png" /></figure><pre>mov  rax, qword [rsp+0x110 {var_1c8}]   ; load updated IntoIter.start<br>mov  rcx, qword [rsp+0x118 {i_1}]       ; load IntoIter.end<br>jmp  0x4d39b0                           ; back to loop head</pre><p>When start == end, execution falls through to:</p><pre>call _$LTalloc..vec..into_it...op..Drop$GT$::drop  ; 0x4d3a2a</pre><p>The file list memory is freed. The Vec&lt;JoinHandle&gt; now contains one handle per file. A post-loop log call confirms completion before the join phase.</p><h3>Step 13 — Join loop and Mutex cleanup</h3><p><strong>Address range:</strong> 0x4d3b40 -- 0x4d3b9f</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*CJCVzU0xPYPYZSL2Db5vBg.png" /></figure><pre>call std::sync::mutex::Mutex&lt;T&gt;::lock    ; 0x4d3b43  (data_5e7028)<br>call core::result::Result::unwrap<br>// ...<br>call std::sync::mutex::Mutex&lt;T&gt;::lock    ; 0x4d3b73  (data_5e7040)<br>call core::result::Result::unwrap<br>call core::ptr::drop_in_place(...)       ; MutexGuard drop</pre><p>The two static addresses data_5e7028 and data_5e7040 are now fully identified from .data.rel.ro. Binary Ninja&#39;s annotation shows both point into the log format vtable for &quot;File lock started: , thread id: ...&quot;, these are not user-visible mutex objects but the Debug formatter vtables for the log call arguments. The actual join loop (pthread_join via Thread::join) follows:</p><pre>call Thread::join  →  libc::pthread_join(id, ptr::null_mut())</pre><p>This corresponds to yarnish.rs:</p><pre>for h in handles { let _ = h.join(); }</pre><h3>Reconstructed source</h3><p>Combining all steps, the reconstructed lock function is:</p><pre>fn lock(<br>    files: Vec&lt;PathBuf&gt;,<br>    thread_limit: u64,<br>    exclude: *const u8,<br>    opts: *const OperatorOptions,<br>) {<br>    // Step 2: ProgressStyle<br>    let spinner_style = ProgressStyle::with_template(&quot;...&quot;).unwrap()<br>        .tick_chars(&quot;...&quot;);<br><br>    // Step 3: MultiProgress<br>    let m = MultiProgress::new();<br><br>    // Step 7: scoped thread scope with semaphore<br>    std::thread::scope(|scope| {<br>        // Step 4: iterate files (NOT (0..n) as in yarnish.rs)<br>        let handles: Vec&lt;_&gt; = files.into_iter().map(|path| {<br><br>            // Step 5: per-file seed (Akira-specific)<br>            let now = SystemTime::now()<br>                .duration_since(UNIX_EPOCH)<br>                .unwrap();<br>            let pid = unsafe { libc::getpid() };<br>            let key = akira_v2::prng::HashStruct::hash(now, pid);<br>            // key = 64 bytes stored in closure<br><br>            // Step 6: ProgressBar with file path as prefix<br>            let pb = m.add(ProgressBar::new(...));<br>            pb.set_style(spinner_style.clone());  // Step 10: yarnish.rs line 34<br>            pb.set_prefix(path.display().to_string());  // file path, not &quot;[i/?]&quot;<br>            // Note: enable_steady_tick presence unconfirmed from screenshots<br><br>            // Step 7: wait for semaphore slot<br>            while scope.num_running_threads() &gt;= thread_limit as usize {}<br><br>            // Step 9/10: spawn encryption thread<br>            scope.spawn(move || {<br>                log::info!(&quot;File lock started: , thread id: {}&quot;, ...);<br>                lock_closure(path, key, pb, ...);<br>            })<br><br>        }).collect();  // Step 11: Mutex&lt;Vec&lt;??&gt;&gt; -- contents unknown<br><br>        // Step 13: join all<br>        for h in handles { h.join().unwrap(); }<br>    });<br>}</pre><h3>Section 7: lock_closure and Encryption</h3><pre>lock (user code, inlined)<br>  → Builder::spawn_unchecked_ (inlined)<br>    → main shim (inlined)<br>      → catch_unwind (inlined)<br>        → __rust_begin_short_backtrace (NOT inlined -- #[inline(never)])<br>          → lock_closure (the encryption function)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odN0vKa-Yrjh1d1xSK4-xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*tIC2htgXOACfvRryeivxAA.png" /></figure><p>This is the symmetric key generated by random number (<a href="https://docs.rs/rand/latest/src/rand/rngs/thread.rs.html#137-148">ThreadRng</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*Zctfgya6f2OPZp0nkL4a9g.png" /></figure><p>As identifed in CheckPoint report, Akirav2 malware author used <a href="https://dalek.rs/">dalek.rs</a>- <a href="https://github.com/dalek-cryptography/curve25519-dalek/tree/main/curve25519-dalek">curve25519</a> to implement “a high-speed, secure elliptic curve used primarily for ECDH key exchange (X25519) and digital signatures (Ed25519), offering 128-bit security with 256-bit keys” (<a href="https://medium.com/@aditrizky052/unlocking-the-power-of-curve25519-ed25519-x25519-the-modern-pillars-of-secure-and-high-speed-a3daefbad0a4">source</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hJOaWe_YcuRgdgZDbfSPbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*yeZdGf-qMKNgaxe2JtLIUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBQ-XeOuOEGlt63kgqs7rg.png" /><figcaption>Ransom note</figcaption></figure><blockquote><strong>Correction (24 June 2026)</strong>. An earlier version of this section described the symmetric primitive as ChaCha20 and the key-wrapping as RSA. That is the scheme used by the older C++ Akira lineage, not the Rust v2 ESXi encryptor analysed here. The Rust v2 pipeline is X25519 (curve25519-dalek 4.1.1) for asymmetric key wrapping and SOSEMANUK (via rust-crypto 0.2.36) for symmetric per-file encryption, with the session key drawn from a ChaCha12 CSPRNG (rand 0.8.5 / rand_chacha 0.3.1, surfaced as thread_rng / ThreadRng). I independently confirmed SOSEMANUK in my own static recovery: the FSM multiplier 0x54655307 with a rotate-left-7 appears 20 times in the HLIL/SSA, the Serpent24 key-schedule constant 0x9E3779B9 is present, and the literal string “sosemanuk” survives in .rodata. Crate versions come from my 29-crate recovery; algorithm roles are corroborated by Check Point. Apologies for the earlier conflation.</blockquote><p>The actual encryption logic lives in lock_closure. Key points from Check Point&#39;s analysis:</p><ul><li><strong>File targeting</strong>: the closure walks the filesystem, filtering by extension. ESXi-relevant extensions (.vmdk, .vmx, .vmsn, .nvram and others) are the primary targets.</li><li><strong>Symmetric encryption</strong>: a per-file session key is generated per run, and the file payload is encrypted with SOSEMANUK, a software-oriented stream cipher chosen (like other stream ciphers) for throughput on targets without hardware AES acceleration. The implementation comes from the legacy rust-crypto 0.2.36 crate (DaGenix), where SOSEMANUK is heavily inlined and must be recovered from its characteristic constants rather than a named import. In this sample the fingerprints are unambiguous: the FSM multiplier 0x54655307 followed by a rotate-left-7 (the SOSEMANUK FSM update, recovered 20 times in the HLIL/SSA), the Serpent key-schedule constant 0x9E3779B9, and the residual string “sosemanuk” in .rodata.</li><li><strong>Randomness: </strong>the session key is drawn from ThreadRng (thread_rng), which in rand 0.8.5 is a ReseedingRng&lt;ChaCha12Core, OsRng&gt;. In other words the CSPRNG is ChaCha12 from rand_chacha 0.3.1, reseeded from the OS via getrandom 0.2.10. This is the only place ChaCha appears in the Rust v2 binary: as the RNG that produces key material, not as the file cipher. (See Part 2 for the thread_rng recovery.)</li><li><strong>Key protection</strong>: the session key is wrapped with a per-binary hardcoded X25519 (curve25519) public key, the dalek curve25519-dalek 4.1.1 stack, not RSA. The public key is embedded in the binary and written alongside the encrypted files; only the operator’s matching private key can recover the session key, enabling decryption upon ransom payment.</li></ul><h3>Further Reading</h3><h3>1. Why UAWAVAUATSH exists</h3><blockquote>Source: <a href="https://github.com/torvalds/linux/blob/v6.11/arch/x86/lib/x86-opcode-map.txt">https://github.com/torvalds/linux/blob/v6.11/arch/x86/lib/x86-opcode-map.txt</a></blockquote><p>It is Binary Ninja’s hex view ASCII column rendering the raw machine code bytes of the HumanDuration::fmt function prologue. There is no string UAWAVAUATSH anywhere in the ELF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*84D68wlD2y7lIqBEZ2bxFw.png" /></figure><h4>The encoding mechanics</h4><blockquote>The opcode map file is stable across kernel versions for x86–64, the encodings do not change. But I pin v6.11 rather than master, for the same reason the Rust stdlib commit pinned here: reproducibility.</blockquote><p>The Linux kernel opcode map (canonical reference for x86 instruction encoding) lists: 0x55 = PUSH rBP/r13, 0x56 = PUSH rSI/r14, 0x57 = PUSH rDI/r15, 0x54 = PUSH rSP/r12 (<a href="https://github.com/torvalds/linux/blob/v6.11/arch/x86/lib/x86-opcode-map.txt">GitHub</a>).</p><h4>The REX prefix range (0x40–0x4f)</h4><p>In 64-bit mode (o64), opcodes 0x40–0x4f are REX prefix bytes, not instructions. Specifically: 0x41 = REX.B, 0x48 = REX.W<a href="https://github.com/torvalds/linux/blob/v6.11/arch/x86/lib/x86-opcode-map.txt"> (github</a>, <a href="https://wiki.osdev.org/X86-64_Instruction_Encoding">OSDev Wiki</a>).</p><p>In 32-bit mode those same bytes were single-byte INC/DEC instructions, but in 64-bit mode they are all repurposed as REX prefix encodings.</p><pre>  <br>top row:    INC eAX   INC eCX   INC eDX  ...   (i64)<br>bottom row: REX       REX.B     REX.X    ...   (o64)<br><br>mode        0x41 means<br>  --------    ----------<br>  32-bit      INC eCX        (top row, superscript i64 = illegal in 64-bit)<br>  64-bit      REX.B prefix   (bottom row, superscript o64 = only in 64-bit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*jWZWgT6AqCIg8lLD_oi_xg.png" /><figcaption><a href="https://cdrdv2-public.intel.com/671110/325383-sdm-vol-2abcd.pdf">Intel SDM </a>Table A-2, row 4</figcaption></figure><pre>INC(i64) general register / REX(o64) Prefixes<br><br>  40      41      42      43      44      45      46      47<br>  eAX     eCX     eDX     eBX     eSP     eBP     eSI     eDI<br>  REX     REX.B   REX.X   REX.XB  REX.R   REX.RB  REX.RX  REX.RXB</pre><p>The two superscripts do all the work:</p><ul><li>i64 = invalid in 64-bit mode: the INC eAX meaning of 0x40 is illegal in 64-bit mode</li><li>o64 = only in 64-bit mode: the REX meaning of 0x40 only exists in 64-bit mode</li></ul><p>And row 5 shows the PUSH encoding you need:</p><pre>PUSH(d64) general register<br><br>  50      51      52      53      54      55      56      57<br>  rAX/r8  rCX/r9  rDX/r10 rBX/r11 rSP/r12 rBP/r13 rSI/r14 rDI/r15</pre><p>The /r8–/r15 disambiguation in row 5 is exactly what REX.B from row 4 provides. 0x55 alone = push rbp. 0x41 0x55 = REX.B prefix + 0x55 = push r13. Same opcode byte, extended register selected by the preceding REX.B.</p><p>This is the primary source. The Linux v6.11 opcode map entry 41: INC eCX (i64) | REX.B (o64) is a direct transcription of this SDM table. Both sources agree, and the SDM is the ground truth since it is the processor specification.</p><p>So the connection to UAWAVAUATSH is:</p><pre>akirav2.elf is a 64-bit ELF<br>    → CPU is in 64-bit long mode<br>    → 0x41 = REX.B  (not INC eCX)<br>    → 0x41 0x57 = REX.B + PUSH rDI/r15 = push r15<br>    → Binary Ninja renders 0x41 as &#39;A&#39;, 0x57 as &#39;W&#39;<br>    → hence &quot;AW&quot; in the ASCII column</pre><h3>2. REX — Register Extension.</h3><p><a href="https://cdrdv2-public.intel.com/671110/325383-sdm-vol-2abcd.pdf"><strong>REX</strong></a> stands for <strong>Register Extension</strong>. It is a one-byte prefix introduced in x86–64 to extend the instruction set beyond what the original 32-bit encoding could address.</p><p>The byte has the fixed high nibble 0100 (hence 0x4_), with the low nibble encoding four flag bits:</p><pre>0100 W R X B<br>     │ │ │ └─ REX.B — extends the r/m field, SIB base, or opcode reg field<br>     │ │ └─── REX.X — extends the SIB index field<br>     │ └───── REX.R — extends the ModRM reg field<br>     └─────── REX.W — promotes operand size to 64 bits</pre><p><strong>Why it was needed</strong></p><p>The original x86 encoding only had 3 bits to identify a register, giving eight registers (rax–rdi). x86-64 added eight more (r8–r15). Rather than redesigning the entire encoding, Intel and AMD added the REX prefix to supply a fourth bit for each register field, doubling the addressable register count.</p><p><strong>The four specific bits</strong></p><p>REX.W (0x48) — use 64-bit operand size instead of the default 32-bit. Most mov, add, sub etc. instructions need this when operating on 64-bit values.</p><p>REX.B (0x41) — extends the register encoded in the opcode byte itself (e.g. the low 3 bits of a push/pop opcode), or the r/m field of ModRM. This is how 0x41 0x57 becomes push r15 instead of push rdi — the B bit flips the register selection from the base-8 register to the extended one.</p><p>REX.R (0x44) — extends the reg field of the ModRM byte.</p><p>REX.X (0x42) — extends the index field of the SIB byte.</p><p><strong>Why </strong><strong>0x41 renders as </strong><strong>A in ASCII</strong></p><p>0x41 is the ASCII code for A. Since REX prefixes occupy 0x40–0x4f, and that range maps directly onto uppercase Latin letters @ABCDEFGHIJKLMNO, every REX.B prefix byte in a hex viewer renders as A. This is purely coincidental — the x86-64 architects chose that range because it freed up the old INC/DEC opcodes in 64-bit mode, not because of any ASCII consideration.</p><p>When pushing extended registers, 0x41 precedes the base push opcode. For example, to push r9 the encoding is 0x41 followed by 0x50 + (9 - 8) = 0x51. The original eight registers push with a single byte; extended registers require two bytes: the REX.B prefix plus the base opcode (<a href="https://eklitzke.org/x86-register-encoding">Eklitzke</a>).</p><p>Applying this to UAWAVAUATSH:</p><p>BytesASCIIInstruction0x55Upush rbp0x41 0x57AWpush r15 (REX.B + 0x57)0x41 0x56AVpush r14 (REX.B + 0x56)0x41 0x55AUpush r13 (REX.B + 0x55)0x41 0x54ATpush r12 (REX.B + 0x54)0x53Spush rbx0x48HREX.W prefix (start of next instruction, e.g. sub rsp, N)</p><p>All eleven bytes fall in the printable ASCII range (0x41–0x57 are uppercase letters, 0x53–0x55 likewise, 0x48 is H), so Binary Ninja&#39;s hex view renders all of them as characters rather than dots.</p><h4>Why this specific prologue</h4><p>Compilers save callee-preserved registers at function entry when the function needs to use them. The System V AMD64 ABI designates rbx, rbp, r12–r15 as callee-saved. A function that uses all six must push all six on entry. The HumanDuration::fmt function is complex enough (formatting a duration string requires multiple branches and temporaries) that LLVM assigned all six callee-saved registers, producing exactly this push sequence (<a href="https://eklitzke.org/x86-register-encoding">Eklitzke</a>).</p><h4>Why 0x41 renders as A</h4><p>0x41 is the ASCII code for uppercase A. The REX prefix range 0x40–0x4F was chosen by the x86-64 architects precisely because those opcodes were the legacy single-byte INC/DEC instructions, which were retired in 64-bit mode to free the space. They happen to sit in the middle of the uppercase ASCII Latin alphabet. So every REX-prefixed push of an extended register produces an A in the ASCII column followed by the push target letter (<a href="https://wiki.osdev.org/X86-64_Instruction_Encoding">OSDev Wiki</a>).</p><p>The byte sequence is entirely mechanical and deterministic. Any function in any x86–64 ELF that saves rbp, r15, r14, r13, r12, rbx in that order will produce UAWAVAUATSH in a hex viewer.</p><h3>3. Mutex</h3><p>Looking back to (0x4d3c2b--0x4d3c63) we saw:</p><pre>004d3c2b   cmp  qword [rsp+0x48 {var_290}], 0x0<br>004d3c31   lea  r13, [rsp+0x50 {var_288}]<br>004d3c36   je   0x4d4153</pre><p>And the three lock inc atomics immediately before SystemTime::now. The je 0x4d4153 target was never shown in the screenshots, that is where control goes when the count is zero.</p><p>From the figure below, we also see std::thread::scoped::Sco...um_running_threads at 0x4d4062.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*eyrQC5J4OF63ciK0o-DKeA.png" /></figure><p><strong>From </strong><strong>thread/mod.rs</strong> at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/mod.rs">db034cee</a>, the exact lines in spawn_unchecked_:</p><pre>if let Some(scope_data) = &amp;my_packet.scope {<br>    scope_data.increment_num_running_threads();<br>}</pre><p><strong>From </strong><strong>scoped.rs</strong> at <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/thread/scoped.rs">db034cee</a>, increment_num_running_threads is:</p><pre>pub(super) fn increment_num_running_threads(&amp;self) {<br>    if self.num_running_threads.fetch_add(1, Ordering::Relaxed) &gt; usize::MAX / 2 {<br>        self.overflow();<br>    }<br>}</pre><p>And from thread/mod.rs, Packet contains:</p><pre>struct Packet&lt;&#39;scope, T&gt; {<br>    scope: Option&lt;Arc&lt;scoped::ScopeData&gt;&gt;,<br>    ...<br>}</pre><p>ScopeData is in scoped.rs. From the earlier session search result, ScopeData contains:</p><pre>pub(super) struct ScopeData {<br>    num_running_threads: Atomic&lt;usize&gt;,<br>    a_thread_panicked:   Atomic&lt;bool&gt;,<br>    main_thread:         Thread,<br>}</pre><p>And from the scoped.rs source at the pinned commit, scope() blocks until num_running_threads reaches zero using a Condvar:</p><pre>https://github.com/rust-lang/rust/blob/79e9716c980570bfd1f666e3b16ac583f0168962/library/std/src/thread/scoped.rs</pre><h4><strong>The connection is:</strong></h4><p><strong>Mutex + </strong><strong>Condvar is the standard Rust pattern for </strong><strong>scope() to wait for all spawned threads to finish.</strong> The Condvar is used inside ScopeData to park the scope-owning thread until num_running_threads drops to zero. The Mutex guards the condition variable&#39;s predicate check.</p><p>In the disassembly, the Mutex::lock at 0x4d3b40/0x4d3b73 on data_5e7028 and data_5e7040, and the Mutex::lock at 0x4d39e0 on data_5e7080 are the Condvar-associated mutexes inside ScopeData. This is the scope() call blocking after all threads are spawned, waiting for them to complete via decrement_num_running_threads calling notify_all on the Condvar.</p><p>So the connection is:</p><pre>std::thread::scope(|s| {<br>    for path in files {<br>        s.spawn(|| lock_closure(path, ...));<br>    }<br>    // scope() blocks here on Condvar::wait_while(Mutex, num_running == 0)<br>})</pre><blockquote>The Mutex and Condvar pair are from scoped.rs , <strong><em>not Akira&#39;s own code.</em></strong></blockquote><p>The Vec::push at 0x4d39ff question therefore changes: it may be pushing into a Vec inside ScopeData or a related structure managed by the scope machinery, not a user-visible Vec&lt;JoinHandle&gt;.</p><h3>References</h3><p>x86-psABIs project (2024) <em>System V application binary interface: AMD64 architecture processor supplement</em>, version 1.0. GitLab. Available at: <a href="https://gitlab.com/x86-psABIs/x86-64-ABI">https://gitlab.com/x86-psABIs/x86-64-ABI</a> (PDF: <a href="https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf">https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf</a>)</p><p>Herzog, B. (2024) <em>Inside Akira ransomware’s Rust experiment</em>. Check Point Research. Available at: <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/</a></p><p>Klabnik, S. and Nichols, C. (2019) <em>The Rust programming language</em>. San Francisco: No Starch Press.</p><p>RalfJung (2024) <em>PathBuf incorrectly transmutes OsString to Vec — issue #124409</em>. GitHub. Available at: <a href="https://github.com/rust-lang/rust/issues/124409">https://github.com/rust-lang/rust/issues/124409</a></p><p>RalfJung (2024) <em>PathBuf: replace transmuting by accessor functions — PR #124410</em>. GitHub. Available at: <a href="https://github.com/rust-lang/rust/pull/124410">https://github.com/rust-lang/rust/pull/124410</a></p><p>The Linux man-pages project (2024) <em>getpid(2)</em>. Available at: <a href="https://man7.org/linux/man-pages/man2/getpid.2.html">https://man7.org/linux/man-pages/man2/getpid.2.html</a></p><p>Tompkins, W. et al. (2024) <em>Akira ransomware continues to evolve</em>. Cisco Talos Intelligence. Available at: <a href="https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/">https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/</a></p><p>console-rs (2024) <em>indicatif 0.17.7 progress_bar.rs source</em>. Available at: <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/src/progress_bar.rs">https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/src/progress_bar.rs</a></p><p>console-rs (2024) <em>indicatif 0.17.7 style.rs source</em>. Available at: <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/src/style.rs">https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/src/style.rs</a></p><p>console-rs (2024) <em>indicatif 0.17.7</em>. crates.io. Available at: <a href="https://crates.io/crates/indicatif/0.17.7">https://crates.io/crates/indicatif/0.17.7</a></p><p>console-rs (2024) <em>indicatif yarnish.rs example</em>, commit 0c037edc86449d84aa457d7d5db80b4166c18d6b. GitHub. Available at: <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs#L29">https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs#L29</a></p><p>Xiao, C. (2025) <em>Reconstructing Rust types</em>. RE//verse 2025. Available at: <a href="https://recon.cx/2025/schedule/events/reverse.html">https://recon.cx/2025/schedule/events/reverse.html</a></p><p>UAWAVAUATSH</p><ul><li>Linux kernel opcode map (ground truth for opcode assignments): <a href="https://github.com/torvalds/linux/blob/master/arch/x86/lib/x86-opcode-map.txt">https://github.com/torvalds/linux/blob/master/arch/x86/lib/x86-opcode-map.txt</a></li><li>REX prefix encoding: <a href="https://wiki.osdev.org/X86-64_Instruction_Encoding">https://wiki.osdev.org/X86-64_Instruction_Encoding</a></li><li>Push/pop register encoding arithmetic: <a href="https://eklitzke.org/x86-register-encoding">https://eklitzke.org/x86-register-encoding</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oOX5Xk20rKhl21uZiEuRw.png" /><figcaption>Thanks for reading</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=443e3551825a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-3-443e3551825a">Reversing Akira’s Rust Experiment : A Breakdown Part 3</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reversing Akira’s Rust Experiment : A Breakdown Part 2]]></title>
            <link>https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-2-147889a51966?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/147889a51966</guid>
            <category><![CDATA[reverse-engineering-rust]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[akirav2]]></category>
            <category><![CDATA[rust-based-malware]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Wed, 20 May 2026 20:23:57 GMT</pubDate>
            <atom:updated>2026-06-24T21:27:32.342Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This post is a breakdown and commentary on <strong>Ben Herzog’s Check Point Research </strong>(December 2024), <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Inside Akira Ransomware’s Rust Experiment</a> &amp; <a href="https://www.virusbulletin.com/conference/vb2025/abstracts/inside-akira-ransomwares-rust-experiment/">his talk in 2025</a>. All technical claims are grounded in the linked primary sources below. Combined with some methodologies of <strong>Cindy Xiao</strong>’s amazing reports/talks in <a href="https://github.com/cxiao/rust-reversing-workshop-recon-2024">2024</a>, <a href="https://github.com/cxiao/reconstructing-rust-types-talk-re-verse-2025">2025</a> (mainly for reconstructing types).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_A_ZAts_tZ5SZs7NsoGgQ.png" /></figure><blockquote>If you haven’t read<a href="https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-1-937e0388d2c7?postPublishedType=repub"> Part 1</a>, it’s encouraged to read the threat reports at least (see <strong>References - Threat Reports </strong>below), so the activities of the binary are clear alongside the binary analysis, including the latest <strong>Tactics, Techniques, and Procedures (TTPs).</strong></blockquote><h3>Table of Contents</h3><ul><li>Info of the binary in this analysis</li><li>LLVM’s picks on scalar moves</li><li>Section 2: The CLI Framework (seahorse)</li><li>Section 3: The inlining cascade</li><li>Section 4: available_parallelism()</li><li>Section 5: lock and Thread Spawning</li></ul><h4>Further Reading</h4><ul><li>1. SIMD</li><li>2. How aho-corasick uses memchr and SIMD</li></ul><h4>References</h4><h3>Info of the binary in this analysis</h3><h3>Reversing Akira’s Rust Experiment: A Breakdown Part 1</h3><blockquote>This post is a breakdown and commentary on <strong>Ben Herzog’s Check Point Research </strong>(December 2024), <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Inside Akira Ransomware’s Rust Experiment</a> &amp; <a href="https://www.virusbulletin.com/conference/vb2025/abstracts/inside-akira-ransomwares-rust-experiment/">his talk in 2025</a>. All technical claims are grounded in the linked primary sources below. Combined with <strong>Cindy Xiao</strong>’s amazing reports/talks in <a href="https://github.com/cxiao/rust-reversing-workshop-recon-2024">2024</a>, <a href="https://github.com/cxiao/reconstructing-rust-types-talk-re-verse-2025">2025</a> (about reconstructing types and more).</blockquote><p>There will be a part 2 to break down the rest. I separate them so this article won’t be <strong><em>__too_long_</em>_</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpO6uNZPlZqZuD7mlYDsqg.png" /></figure><p>For this analysis, Binary Ninja (v5.3.9434) is used without enabling any plugins. <strong>Binary:</strong> akirav2.elf , SHA25:60ee1d284ed663073872012c7bde7fac5ca1121403f1a5d2d5411317df282796c.</p><h4>A note on source references</h4><blockquote>The commit hash is updated on 10th Jun 2026. <strong><em>79e9716c…</em> is rustc 1.74.0 stable</strong> (released 2023-11-16). Akirav2’s <em>.rodata</em> contains std panic-path strings of the form <em>/rustc/&lt;commit&gt;/library/...</em>.<strong><em>db034cee…</em> is a </strong><strong><em>master</em>/nightly commit from ~1 year later, </strong>which I was mistakenly pinned in the article. If you see any links related to <strong><em>db034cee… , </em></strong><em>please consider it was based on previosu wrong assumption but it works to some degree.</em></blockquote><p>The Rust standard library is under active development and files move between releases. Source links in this post are pinned to commit 79e9716c980570bfd1f666e3b16ac583f0168962 — <a href="https://releases.rs/docs/1.74.0/"><strong>rustc 1.74.0 stable</strong></a>, the toolchain that compiled this Akira v2 binary. This is recoverable directly from the binary: its .rodata embeds /rustc/79e9716c…/library/... panic paths, and it is corroborated by version-pinned FunctionID analysis resolving the sample to 1.74.0.</p><p>This matters because stdlib code is inlined directly into the final binary at compile time: what you see in the disassembly reflects the stdlib at that specific commit, not the current main branch. Following a newer version of the same file risks misidentifying inlined boilerplate or drawing incorrect conclusions about what the malware authors wrote versus what the compiler contributed.</p><blockquote>If a pinned link returns a 404, the file has likely been relocated. Navigate to the <a href="https://github.com/rust-lang/rust/tree/db034cee00570a9b82ea8b9e9e95221dbd745698">repository root</a> and search by filename.</blockquote><h3>LLVM’s picks on scalar moves</h3><blockquote>SIMD stands for <strong>Single Instruction, Multiple Data</strong>. It is a CPU execution model where one instruction operates on multiple data elements in parallel, using wide registers.</blockquote><p>To understand the compiler’s decision, one must examine the specific arithmetic of the LLVM cost model and processor microarchitecture. The compiler does not merely guess; it evaluates the cost of instructions in bytes, micro-operations (<em>uOps</em>), and execution port pressure.</p><p>LLVM’s auto-vectorisation and scalar replacement of aggregates (SROA) pass recognises that zeroing or copying two adjacent 8-byte fields is a 16-byte operation and emits a single XMM store. This is purely a code-generation optimisation, the source code contains no SIMD intrinsics. When you see pxor xmm0, xmm0 followed by movdqu in Rust release builds, it is “likely” (<em>but not absolutely</em>) a struct/array zero-initialisation artefact, not intentional vector computation (<em>more details in the </em><strong><em>Section 3: Inlin</em>ing Cascade</strong>).</p><p>Recognising this code-generation artefact is crucial for reverse engineering, as it cleanly separates genuine mathematical or cryptographic SIMD workloads from routine structural initialisation. At the hardware level, this compiler decision reflects the purest form of systemic leverage: achieving maximal state change with minimal resource expenditure.</p><blockquote><strong>Rust and SIMD.</strong> Rust’s standard library uses SIMD for things like memchr (which backs aho-corasick internally). When you see a tight loop in a Rust binary using pcmpeqb or vpcmpeqb, it is almost certainly memchr or a SIMD-accelerated pattern search, not custom malware logic. Relevant to your Akira analysis: if you see SIMD near the search routines, that is likely the aho-corasick crate doing pattern matching.</blockquote><blockquote>More details can be found in the section <strong>Further Reading </strong>below.</blockquote><h3>Section 2: The CLI Framework (<a href="https://github.com/ksk001100/seahorse">seahorse</a>)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zdNqiWD-JFYkCJTN_lL9g.png" /><figcaption>main function</figcaption></figure><blockquote>xmm0 is a 128-bit register in x86-64 assembly used for SSE/AVX SIMD operations, frequently storing floating-point numbers (single/double precision) or packed integers (<a href="https://www.cs.uaf.edu/courses/cs301/2014-fall/notes/float-asm/index.html">resource</a>).</blockquote><p><strong>What the threat intel establishes</strong></p><p>The complete Akira v2 CLI flag set is:</p><ul><li>--path: Start path. Default value: /vmfs/volumes <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">(Check Point Research</a>)</li><li>--id: Build ID as a run condition, likely password/anti-analysis (<a href="https://unit42.paloaltonetworks.com/threat-assessment-howling-scorpius-akira-ransomware/">Palo Alto Networks</a>)</li><li>--vmonly: encrypt VM files only <a href="https://unit42.paloaltonetworks.com/threat-assessment-howling-scorpius-akira-ransomware/">(Palo Alto Networks</a>).</li><li>--stopvm: turn off running VMs before encryption (<a href="https://unit42.paloaltonetworks.com/threat-assessment-howling-scorpius-akira-ransomware/">Palo Alto Networks</a>)</li></ul><p>Additionally, --fork controls process forking for the stopvm command, and a --threads flag controls thread count (<a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Check Point Research</a>).</p><p>There is also a --logs flag for controlling log verbosity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*FWC2Yozg0yKxQ4vqeayK8g.png" /><figcaption>Default function in akirav2 in Disassembly Pt 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*7CvC3PgazcEa3d2OCcPvjA.png" /><figcaption>Default function in akirav2 in Disassembly Pt 2, you can see another crate `Indicatif` in the following dsiassembly code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*aQ9TKe4TkmIsh_wFSqv8vg.png" /><figcaption>Default function in akirav2 in disassembly in High Level IL</figcaption></figure><p>This single HLIL block does three things simultaneously due to inlining: starts a timer, initialises the <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">indicatif</a> spinner, and as a side effect of that initialisation touching adjacent .rodata, exposes the entire operational string table of default_action in one place. Every log message, error string, shell command, and panic message that default_action can emit is visible here.</p><p><strong>1. Timing initialisation (</strong><strong>0x4dc44a)</strong></p><pre>rax, rdx = std::time::Instant::now::hbcf67d3c6dde57ee()<br>int64_t var_f8 = rax<br>int32_t var_2fc = rdx</pre><p>Records the wall-clock time at the start of default_action. This is used later to calculate elapsed time for the progress spinner display, the {elapsed} or {elapsed_precise} template keys in <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">indicatif</a>. This is pure <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">indicatif</a> boilerplate from <a href="https://github.com/console-rs/indicatif/blob/e84863a94e9d161bff4d7e4f918ead726d481001/examples/yarnish.rs">yarnish.rs</a>.</p><p><strong>2. Progress spinner initialisation (</strong><strong>0x4dc473)</strong></p><pre>int32_t var_278[0x4]<br>indicatif::style::ProgressStyle::with_template::hc10b2fc1f737695f(<br>    &amp;var_278,<br>    &quot;{prefix:.bold.dim} {spinner} {wide_msg}akiranew/src/main.rs ...&quot;<br>    0x27)</pre><p>This calls ProgressStyle::with_template with a template string of length 0x27 = 39 characters. The template itself is {prefix:.bold.dim} {spinner} {wide_msg}, exactly the yarnish.rs spinner template confirmed from the <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">indicatif</a> source. The result lands in var_278, which is the ProgressStyle struct on the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOvMbvVVJkqNa_xQXXE4fQ.png" /><figcaption>From data_5e74e8, it’s clear a template of Indicatif <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">yarnish.rs</a></figcaption></figure><p><strong>The core insight from Check Point (</strong><a href="https://github.com/console-rs/indicatif/blob/e84863a94e9d161bff4d7e4f918ead726d481001/examples/yarnish.rs">Indicatif</a><strong>)</strong></p><p>The malware authors used indicatif to provide an operator-friendly visual representation of what the malware is doing: progress bars and spinners, and the source code they used was directly inspired by <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">yarnish.rs</a>, the canonical indicatif example.</p><p>The puzzle<a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/"> Check Point</a> identified is that default_action begins with dozens of eyebrow-raising basic blocks invoking the C FFI and other low-level functionality, which has nothing to do with encryption. This is entirely explained by indicatif being inlined into default_action by the Rust release compiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*0eOFA7Ey2unmd8tRJ_uZfQ.png" /><figcaption>A truncated overview of the graphs based on `default_action`</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*nts_C31GCnxGiDos5W5OgQ.png" /><figcaption>First lines in `default_action` before jumping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*HfeDH3u7bYaMQHsbZgtlDA.png" /><figcaption>First few functions of `default_action`</figcaption></figure><p>This is directly relevant to the disassembly we have been analysing across this session. The std::time::Instant::now() call at prologue (0x4dc44a), the format string <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">{prefix:.bold.dim} {spinner} {wide_msg}</a> at 0x4dc45e, and the CStr::from_bytes_with_nul / File::open_c calls in the early blocks of default_action are all <strong>inlined </strong><strong>indicatif initialisation code </strong>(<a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">yarnish.rs</a>), not malware logic. The malware logic only starts later in default_action once the spinner is set up.</p><pre>pub fn main() {<br>    let mut rng = rand::rng();<br>    let started = Instant::now();<br>    let spinner_style = ProgressStyle::with_template(&quot;{prefix:.bold.dim} {spinner} {wide_msg}&quot;)<br>        .unwrap()<br>        .tick_chars(&quot;⠁⠂⠄⡀⢀⠠⠐⠈ &quot;);<br><br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*dBR8WBplrX2vYIIYzV_9eQ.png" /><figcaption>Xref — to see the corelation between main and default_action</figcaption></figure><p>After argument collection, the assembly performs many writes to stack memory before calling default_action. The function name itself is the clue: a web search for it leads directly to <a href="https://github.com/ksk001100/seahorse">seahorse</a>, a Rust CLI framework whose <a href="https://github.com/ksk001100/seahorse/blob/master/examples/nested_multiple_app.rs">examples</a> contains exactly this pattern:</p><pre>use seahorse::{App, Context, Command};<br>use std::env;<br><br>fn main() {<br>    let args: Vec&lt;String&gt; = env::args().collect();<br>    let app = App::new(env!(&quot;CARGO_PKG_NAME&quot;))<br>        .description(env!(&quot;CARGO_PKG_DESCRIPTION&quot;))<br>        .author(env!(&quot;CARGO_PKG_AUTHORS&quot;))<br>        .version(env!(&quot;CARGO_PKG_VERSION&quot;))<br>        .usage(&quot;cli [name]&quot;)<br>        .action(default_action)<br>        .command(add_command())<br>        .command(sub_command());<br><br>    app.run(args);<br>}</pre><p>The string &quot;cli [name]&quot; also appears verbatim in the binary, confirming the match.</p><p>The seahorse <a href="https://github.com/ksk001100/seahorse/blob/master/src/app.rs#L9">App struct</a> has ten fields, most of them Option&lt;T&gt;. The stack writes in the assembly are initialising this struct field by field. Once you know the struct layout, each write maps to a named field.</p><pre>/// Multiple action application entry point<br>#[derive(Default)]<br>pub struct App {<br>    /// Application name<br>    pub name: String,<br>    /// Application author<br>    pub author: Option&lt;String&gt;,<br>    /// Application description<br>    pub description: Option&lt;String&gt;,<br>    /// Application usage<br>    pub usage: Option&lt;String&gt;,<br>    /// Application version<br>    pub version: Option&lt;String&gt;,<br>    /// Application commands<br>    pub commands: Option&lt;Vec&lt;Command&gt;&gt;,<br>    /// Application action<br>    pub action: Option&lt;Action&gt;,<br>    /// Alternate application action that returns a Result<br>    pub action_with_result: Option&lt;ActionWithResult&gt;,<br>    /// Application flags<br>    pub flags: Option&lt;Vec&lt;Flag&gt;&gt;,<br>}</pre><p>The flags initialised include:</p><ul><li>--threads &lt;int&gt;: number of encryption threads (1-1000)</li><li>--stopvm: shut down ESXi VMs before encrypting</li><li>Others controlling targeting behaviour</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEVX4pjiv8_edyx-wKAgBA.png" /></figure><blockquote><strong>movdqu</strong></blockquote><blockquote>Move Double Quadword Unaligned. Loads or stores 16 bytes (128 bits) between an XMM register and memory, with no alignment requirement on the memory address. The u suffix distinguishes it from movdqa (aligned, which faults if the address is not 16-byte aligned).</blockquote><ul><li>movdqu xmm0, [rel data_4908f4[0x7c]] loads a 16-byte string literal; the inline annotation resolves it to /proc/self/cgroupcpu/sys/fs/cgroupcgroup.controllers... as a cgroup path read. This is the ESXi/Linux container-escape or resource-limit probe pattern seen in Akira v2.</li><li>core::ffi::c_str::CStr::from_bytes_with_nul is called on the result , confirming a C-string literal being wrapped.</li><li>std::sys::unix::fs::File::open_c opens the resolved path.</li><li>cmp dword [rbx {var_2f8}], 0x0 / je 0x4dc94c: checks whether File::open_c returned Ok or Err (the Result discriminant is at offset 0 of the Result&lt;File, Error&gt; stack slot).</li><li>core::ptr::drop_in_place...ror..Error$GT$$GT$ : the error path drops the io::Error on the branch where open failed.</li><li>The free call at 0x4dc57d via qword [rel free] (PLT slot) is dropping a heap allocation, consistent with an OsString/PathBuf being freed after use.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSMcQG8xeEbsXqbS1khynQ.png" /></figure><ul><li>seahorse::context::Context::string_flag is called at 0x4dc8bd, this is the seahorse API call to retrieve a named string flag from the parsed CLI context. The flag name is loaded from data_439f64[8] which the inline annotation shows as a packed log-level string: &quot;logswarn.logSlimMaskbluecyanboldLANG &lt;= ZeroweekhournextWARNINFOcallhashHash =&gt; FAILQuit...&quot;. That is a seahorse flag-definition table: multiple flag names packed into a single data blob with offsets. The flag being retrieved here is at byte offset 8, which given the prefix &quot;logs&quot; is the --logs flag.</li><li>At 0x4dc8fb (highlighted in red), lea rdx, [rel data_4418a5[0x19]] loads a string annotated as &quot;debugValid values for --logs: trace, debug, error, info, warn\nakiranew_Root path: Starting path: /vmfs/vo...&quot;: this is an error/help string emitted when the --logs value fails validation.</li><li>_$LT$$u5b$A$u5d$$u20$as$...T$B$GT$$GT$::equal is &lt;[A] as PartialEq&lt;[B]&gt;&gt;::eq: slice equality, comparing the user-supplied flag value against known valid strings (&quot;trace&quot;, &quot;debug&quot;, &quot;error&quot;, &quot;info&quot;, &quot;warn&quot;). This is done twice (at 0x4dc8ee and 0x4dc90b) with r12 = 0x4 and r13 = 0x5, i.e. comparing 4-byte and 5-byte slices</li></ul><h4><strong>Why this matters for this research?</strong></h4><p>The Check Point finding reframes the analysis problem entirely. The apparent complexity of default_action is not malware sophistication.</p><blockquote>Instead, it is release-mode inlining of a third-party progress bar library.</blockquote><h3>Section 3: Inlining Cascade</h3><h3>Indicatif</h3><h4>The design motivation</h4><p>The malware authors used indicatif to provide an operator-friendly visual representation of what the malware is doing. In <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">checkpoint</a> report, Ben describe it as &quot;true eye candy for CLI fans&quot;, things like progress bars and spinners declared cheerfully as the ransomware destroys backups, generates a symmetric session key, encrypts VMs, and writes ransom notes.</p><p>The boilerplate source is yarnish.rs from the indicatif example directory. As shown in <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">checkpoint</a> report, it’s observed that yarnish.rs was used as a prototype during the writing of this malware, specifically for the lock function, which was moved to a separate module (lock.rs)</p><p>This code is part of the example <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">yarnish.rs</a> in <a href="https://github.com/console-rs/indicatif/tree/main">Indicatif</a>.</p><pre>let m = MultiProgress::new();<br>    let handles: Vec&lt;_&gt; = (0..4u32)<br>        .map(|i| {<br>            let count = rng.random_range(30..80);<br>            let pb = m.add(ProgressBar::new(count));<br>            pb.set_style(spinner_style.clone());<br>            pb.set_prefix(format!(&quot;[{}/?]&quot;, i + 1));<br>            thread::spawn(move || {<br>                let mut rng = rand::rng();<br>                let pkg = PACKAGES.choose(&amp;mut rng).unwrap();<br>                for _ in 0..count {<br>                    let cmd = COMMANDS.choose(&amp;mut rng).unwrap();<br>                    thread::sleep(Duration::from_millis(rng.random_range(25..200)));<br>                    pb.set_message(format!(&quot;{pkg}: {cmd}&quot;));<br>                    pb.inc(1);<br>                }<br>                pb.finish_with_message(&quot;waiting...&quot;);<br>            })<br>        })<br>        .collect();<br>    for h in handles {<br>        let _ = h.join();<br>    }</pre><p>Let’s focus on rng.random_range... for now. The breakdown of thread spawning can be found in the section “The Inlining Cascade” below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5s5AmBttUXPf0NJiwYHdig.png" /></figure><blockquote><strong>pxor xmm0, xmm0</strong></blockquote><blockquote>XOR a 128-bit SSE register with itself. The result is always zero regardless of the prior contents, identical in intent to xor eax, eax for 32-bit registers, but operating on 16 bytes in one instruction.</blockquote><p><strong>0x4dd16e : thread RNG initialisation and alphabet setup</strong></p><pre>004dd174   call  core::ptr::drop_in_place...Box&lt;str&gt;...::hb14970c17f15bb5a</pre><p>Drops a previous Box&lt;str&gt;, cleanup of a prior string allocation (a log message or progress bar message that was displayed).</p><pre>004dd179   call  rand::rngs::thread::thread_rng::h463d5de9ac748823<br>004dd17e   mov   r14, rax</pre><blockquote>In rand 0.9, fn rand::thread_rng() was renamed to rand::rng() and removed from the prelude.</blockquote><p><a href="https://github.com/rust-random/rand/blob/master/CHANGELOG.md#api-changes-rng-trait-and-top-level-fns">thread_rng()</a> initialises the per-thread <a href="https://github.com/rust-random/rand/blob/master/src/rngs/thread.rs#L137">CSPRNG</a> from the <a href="https://github.com/rust-random/rand/blob/master/src/rngs/thread.rs#L137">rand</a> crate. The return value (ThreadRng handle) is stored in r14. This is the first direct evidence of cryptographic randomness being sourced. Concretely it is rand 0.8.5’s ThreadRng, a ReseedingRng&lt;ChaCha12Core, OsRng&gt; built on rand_chacha 0.3.1, which generates the SOSEMANUK session key later wrapped by X25519 (see Part 3).</p><p>The mangled symbol in the binary is <a href="https://github.com/rust-random/rand/blob/master/CHANGELOG.md#api-changes-rng-trait-and-top-level-fns">rand::rngs::thread::thread_rng</a> , this confirms Akira v2 compiled against rand pre-0.9 (where the function was still named thread_rng), not 0.9+.</p><h4>Randomly-selected characters &amp; Vec&lt;T&gt;</h4><p>Initialises a Vec&lt;T&gt; at var_278 with discriminant 0x1 (non-empty Some), zeroes the data/len/cap fields via xmm0, then reserves capacity for 10 elements (r12 = 0xa). This is building a Vec that will hold randomly-selected characters.</p><pre>004dd1b3   lea   rbx, [rel str.2[0x39]]<br>           {&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/mnt/c/Users/user/.carg...&quot;}</pre><p>Loads a pointer into the alphanumeric character set ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 , which has 62 characters. The /mnt/c/Users/user/.carg... suffix is the adjacent .rodata (a cargo registry path string), the alphabet itself is just the 62 alphanumeric characters. This is the character pool for random ID generation.</p><pre>004dd1ba   mov   rax, qword [r14+0x110]  ; load Vec length counter<br>004dd1c1   cmp   rax, 0x40               ; compare to 64<br>004dd1c5   jb    0x4dd1dc                ; loop while length &lt; 64</pre><p>The loop runs until 64 characters have been appended. This is generating a <strong>64-character random alphanumeric string</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yAYqR8FY270lRnK4oMwTg.png" /></figure><p><strong>0x4dd1c7–</strong><strong>0x4dd23f : the random character selection inner loop</strong></p><pre>004dd1c7   mov   rdi, rbp<br>004dd1ca   mov   rsi, r13<br>004dd1cd   call  _$LT$rand..rngs..adapter...Core$GT$::generate::hd875faf09d425bd0<br>004dd1d2   and   qword [r14+0x110], 0x0   ; clear len field temporarily<br>004dd1da   xor   eax, eax</pre><p>Calls &lt;rand::rngs::adapter::ReseedingRng&lt;Core&gt;&gt;::generate, this is the ThreadRng backend calling the underlying CSPRNG block generator. The result populates a buffer.</p><pre>004dd1dc   mov   ecx, dword [r14+rax*4+0x10]  ; load random dword from buffer<br>004dd1e1   mov   edx, ecx<br>004dd1e3   shr   edx, 0x1b                    ; edx = ecx &gt;&gt; 27<br>004dd1e6   inc   rax<br>004dd1e9   mov   qword [r14+0x110], rax<br>004dd1f0   cmp   edx, 0x1e                    ; compare to 30<br>004dd1f3   ja    0x4dd1c1                     ; reject if edx &gt; 30 (rejection sampling)</pre><blockquote>The pre-0.9 version that matches Akira v2’s compile-time rand version (the binary uses thread_rng, which was renamed to rng() only in 0.9</blockquote><p>This is <a href="https://docs.rs/crate/rand/0.8.5/source/src/distributions/uniform.rs"><strong>rejection sampling</strong></a> to avoid modulo bias. The random dword is right-shifted by 27 bits, leaving 5 bits. If those 5 bits gives 0–31; rejecting &gt; 30 keeps 0–30, which is 31 values. But 62 = 2 × 31, so this is selecting a value in [0, 30] and then using a further bit to select the upper or lower half of the alphabet. The next block confirms this:</p><pre>004dd1f5   shr   ecx, 0x1a               ; ecx &gt;&gt; 26 (6 bits)<br>004dd1f8   mov   r15b, byte [rcx+rbx]    ; index into alphabet[ecx]<br>004dd1fc   test  r15b, r15b<br>004dd1ff   js    0x4dd241               ; sign bit set → handle non-ASCII (encode_utf8 path)</pre><p>After rejection, ecx &gt;&gt; 26 gives a 6-bit index into the 62-character alphabet. Since 62 &lt; 64, the maximum 6-bit value (63) can still exceed the alphabet, the js branch at 0x4dd1ff handles the edge case via core::char::methods::encode_utf8_raw seen later. For ASCII characters (the common case), r15b is directly the selected character byte.</p><pre>004dd201   mov   rsi, qword [rsp+0x220 {var_268}]   ; Vec len<br>004dd209   cmp   rsi, qword [rsp+0x218 {var_278[2].q}]  ; compare len to cap<br>004dd211   jne   0x4dd228                             ; if len &lt; cap, fast path<br>004dd213   lea   rdi, [rsp+0x210 {var_278}]<br>004dd21b   call  alloc::raw_vec::RawVec&lt;...&gt;::reserve_for_push  ; grow if needed</pre><p>Standard Vec::push capacity check, grow if full, otherwise fast-path the byte append.</p><pre>004dd228   mov   rax, qword [rsp+0x210 {var_278[0].q}]  ; Vec data ptr<br>004dd230   mov   byte [rax+rsi], r15b   ; append the character<br>004dd234   inc   rsi<br>004dd237   mov   qword [rsp+0x220 {var_268}], rsi  ; update len<br>004dd23f   jmp   0x4dd26d               ; back to outer loop</pre><p>Appends the selected character to the Vec&lt;u8&gt; and increments length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4zbxMOPWo8-L-IIJ-y-Mw.png" /></figure><p><strong>0x4dd327: </strong><strong>time-0.3.30 struct initialisation and </strong><strong>Display formatting</strong></p><pre>004dd327   __builtin_memcpy(dest: &amp;rax_43[6],<br>               src: &quot;\x05\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01\x00\x&quot;<br>                    &quot;00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00&quot;<br>                    &quot;00\x05\x00\x00\x00\x00\x00\x00\x00\x0b&quot;,<br>               count: 0x31)</pre><p>This is initialising the field layout of a time::PrimitiveDateTime or time::OffsetDateTime struct from the time-0.3.30 crate. The byte values correspond to date/time fields: month=5 (May), day=1, hour=1, minute=0, second=4, etc. This is constructing a fixed or computed datetime value for use in the session record or ransom note timestamp.</p><pre>004dd371   rax_43[0x10] = &quot;/mnt/c/Users/user/.cargo/registry/src/index.crates.&quot;<br>                          &quot;io-6f17d22bba15001f/time-0.3.30/src/date.rsjulian_day&quot;<br>004dd385   rax_43[0x13] = &quot;/mnt/c/Users/user/.cargo/registry/src/index.crates.&quot;<br>                          &quot;io-6f17d22bba15001f/time-0.3.30/src/date.rsjulian_day&quot;</pre><p>These are <strong>panic location strings</strong> from <a href="https://docs.rs/crate/time/0.3.30/source/src/date.rs">time-0.3.30/src/date.rs</a>, leaked into the binary as Rust panic metadata. The developer&#39;s full filesystem path /mnt/c/Users/user/.cargo/registry/... is embedded. The /mnt/c/Users/ prefix confirms the developer compiled on <strong>WSL2</strong> (Windows Subsystem for Linux): C:\Users\... mounted as /mnt/c/Users/....</p><pre>004dd3f1   var_278[0].q = &amp;data_5e7570<br>004dd3f4   var_278[2].q = 2</pre><p>Sets up a &amp;str fat pointer: data pointer + length 2, likely a two-character string used as a separator or suffix in the session ID string being assembled.</p><pre>004dd404   int64_t (* var_2f0_2)(int64_t* arg1) =<br>               _$LT$alloc..string..Stri....Display$GT$::fmt::h9352ad71406cfecb</pre><p>Stores the &lt;String as Display&gt;::fmt vtable function pointer into var_2f0_2. This is setting up a trait object for fmt::Display, the session ID String is about to be formatted for output (to the progress bar, log, or ransom note).</p><h4><strong>What this block does in total</strong></h4><p>(Likely) This is Akira v2’s <strong>session key / encryption ID generation</strong>:</p><pre>// Reconstructed source<br>let mut rng = thread_rng();<br>let charset: &amp;[u8] = b&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&quot;;<br>let session_id: String = (0..64)<br>    .map(|_| {<br>        // rejection-sampled uniform selection from charset<br>        charset[rng.gen_range(0..62)] as char<br>    })<br>    .collect();<br><br>// then: get current datetime via time-0.3.30<br>// then: format session_id for display / note writing</pre><p>The 64-character alphanumeric random string is the per-execution session key identifier, used to name the ransom note, tag encrypted files, or derive the symmetric encryption key depending on where it flows next.</p><p><strong>The WSL2 developer path</strong> (/mnt/c/Users/user/.cargo/) is a OPSEC leak. The developer built this on a Windows machine running WSL2, using the default username user. This is consistent across all three panic strings visible in this session.</p><h3>How is Malware Operatoring Indicatif</h3><p>The operator is shown the elapsed time of the current operation. In yarnish.rs, the relevant indicatif template string uses {elapsed} or {elapsed_precise} . SPARKLE is the static variable (emoji) used in <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs#L29">yarnish.rs</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*KaTcWnh-6ujUssGhA8DjHg.png" /></figure><pre>static LOOKING_GLASS: Emoji&lt;&#39;_, &#39;_&gt; = Emoji(&quot;🔍  &quot;, &quot;&quot;);<br>static TRUCK: Emoji&lt;&#39;_, &#39;_&gt; = Emoji(&quot;🚚  &quot;, &quot;&quot;);<br>static CLIP: Emoji&lt;&#39;_, &#39;_&gt; = Emoji(&quot;🔗  &quot;, &quot;&quot;);<br>static PAPER: Emoji&lt;&#39;_, &#39;_&gt; = Emoji(&quot;📃  &quot;, &quot;&quot;);<br>static SPARKLE: Emoji&lt;&#39;_, &#39;_&gt; = Emoji(&quot;✨ &quot;, &quot;:-)&quot;);</pre><h3>The root cause</h3><p>The upper half of default_action contains dozens of confusing basic blocks that appear to call from_bytes_with_nul, std::fs::buffer_capacity_required, and other unrelated functions. One basic block runs for over 200 instructions. None of this is directly authored by the malware writers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yft6YAEFIv6X1_ztCFfPhw.png" /></figure><p>The Akira authors wanted their thread count to be intelligent. Rather than hardcoding a number, they wrote something equivalent to. The operator-supplied --threads flag has a default: the number of logical CPU cores. This is implemented as:</p><pre>let threads: u32 = match threads_flag_value {<br>    Some(n) =&gt; n,<br>    None =&gt; available_parallelism().unwrap() as u32,<br>};</pre><p><a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/std/src/sys/pal/unix/thread.rs#L344">available_parallelism()</a> is a deceptively simple call. Its Release-mode expansion is not. available_parallelism() may sound trivial, but on Linux, it is not.</p><h4>What the Runtime Actually Has to Do</h4><p>To return a meaningful CPU count on a Linux system, the Rust standard library cannot simply call sysconf(_SC_NPROCESSORS_ONLN) and be done with it. That syscall returns the host&#39;s physical CPU count, which is meaningless inside a container or a VM with a cgroup CPU quota applied. A process limited to 2 CPU-equivalents by cgroup policy on a 64-core host should not spin up 64 threads.</p><h3>Section 4: available_parallelism()</h3><h4>Quick Recap</h4><p>Before diving deeper, Let’s recap what we had found so far:</p><ul><li><strong>Seahorse:</strong> CLI Framework, relevant function default_action</li><li><strong>Indicatif</strong>: Progress in CLI command, relevant file is yarnish.rs</li></ul><h4>What we are going to discover:</h4><ul><li>The <strong>structure of the threading code</strong> in default_action matches yarnish.rs&#39;s pattern: spawning N threads, collecting handles into a Vec, joining them</li><li>yarnish.rs : multithreaded source code, relevant function call available_parallelism</li></ul><h4>Now jump to yarnish.rs — Multithreading part</h4><p>As we saw earlier, the operator-facing UI is built using <a href="https://github.com/console-rs/indicatif">indicatif</a>, a Rust library for terminal progress bars and spinners. The malware displays a progress box with emojis labelled things like “destroying backups”, “generating symmetric session key”, “encrypting VM”, “writing ransom note”.</p><p>The source inspiration <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">yarnish.rs</a>, has an example in the indicatif repository. That example has a multithreaded outline:</p><pre>use std::thread;<br>...<br><br>let handles: Vec&lt;_&gt; = (0..4u32)<br>    .map(|i| thread::spawn(move || { ... }))<br>    .collect();</pre><blockquote>It took me a bit time to realise how to connect yarnish.rs with <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">available_parallelism()</a> . Basically, the function <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">available_parallelism()</a> is the standard function of the <strong>Rust stdlib</strong>, <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">thread.rs</a>.</blockquote><p>The link from yarnish.rs to a<a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">vailable_parallelism</a> is not direct. The chain is:</p><ul><li><a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">yarnish.rs</a> itself does <strong>not</strong> call <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">available_parallelism()</a>.</li><li>You can confirm it hardcodes 0..4u32 with no CPU query at all. The authors added available_parallelism() themselves as a modification.</li></ul><pre>yarnish.rs hardcodes 0..4u32<br>    ↓ authors modify it to be dynamic<br>    ↓ CLI flag --threads added via seahorse<br>    ↓ help text &quot;Default: number of logical CPU cores&quot; visible in binary<br>    ↓ None branch must query CPU count<br>    ↓ idiomatic stdlib call = available_parallelism()</pre><h4>Binary Confirmation: Inlined Call Tree Artefacts</h4><blockquote>For the CPU_COUNT_S bitmask, that lives in the libc crate, not the rust stdlib. You need the correct libc crate commit that corresponds to what db034cee was depending on. Check <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/Cargo.lock">the lockfile</a>, the version is listed below.</blockquote><p>Because of Release + LTO inlining, <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">available_parallelism()</a> leaves these verifiable traces inside default_action:</p><ul><li><a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs#L548">/proc/self/cgroup</a> string</li><li><a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs#L364">sched_getaffinity</a> syscall</li><li><a href="https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/mod.rs">0x5555555555555555</a> bitmask</li><li><a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs#L378">sysconf(_SC_NPROCESSORS_ONLN)</a></li></ul><p>Each of these is individually verifiable by reading the stdlib source and tracing what gets inlined. The bitmask constants are the strongest binary fingerprint because they are unique to the software popcnt expansion of CPU_COUNT_S operating on a cpu_set_t.</p><h4>How to verify bitmask</h4><p><strong>Verify the bitmask with correct </strong><strong>libc version:</strong></p><pre>[[package]]<br>name = &quot;libc&quot;<br>version = &quot;0.2.159&quot;<br>source = &quot;registry+https://github.com/rust-lang/crates.io-index&quot;<br>checksum = &quot;561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5&quot;</pre><p>The libc crate uses git tags matching the version string exactly. The correct pinned URL for CPU_COUNT_S in the Linux GNU module is potentially in the link:</p><pre>https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/gnu/mod.rs</pre><p>However, I couldn’t find CPU_COUNT_S in the link, so I tried another method to find under the same version of libc :</p><pre>https://github.com/rust-lang/libc/search?q=CPU_COUNT&amp;type=code&amp;ref=0.2.159</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*3XHWChFs4i1LjVsDONxeVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*VZTNlWBZwB0dd5ZUVjUaPQ.png" /><figcaption>The most likely files for this inspection, but which one? Or none of them?</figcaption></figure><ul><li>teeos is a completely separate top-level target in the libc crate. It is gated by #[cfg(target_os = &quot;teeos&quot;)]. The Akira binary is an ELF compiled for x86_64-unknown-linux-gnu, which means target_os = &quot;linux&quot;. The teeos module is never compiled for a Linux target; the cfg gates are mutually exclusive.</li><li>linux_l4re_shared.rs by contrast is named and structured as a <strong>shared file</strong> between Linux and L4Re targets, sitting inside src/unix/linux_like/. It is included via the Linux module hierarchy, which is the path taken for x86_64-unknown-linux-gnu.</li></ul><p>But I cannot verify which one is relevant, though their codes did the same thing basically…</p><pre>https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/mod.rs</pre><p>The source code of <a href="https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/mod.rs">mod.rs</a>:</p><pre>pub fn CPU_COUNT_S(size: usize, cpuset: &amp;cpu_set_t) -&gt; ::c_int {<br>        let mut s: u32 = 0;<br>        let size_of_mask = ::mem::size_of_val(&amp;cpuset.bits[0]);<br>        for i in cpuset.bits[..(size / size_of_mask)].iter() {<br>            s += i.count_ones();<br>        };<br>        s as ::c_int<br>    }<br><br>    pub fn CPU_COUNT(cpuset: &amp;cpu_set_t) -&gt; ::c_int {<br>        CPU_COUNT_S(::mem::size_of::&lt;cpu_set_t&gt;(), cpuset)<br>    }</pre><p><a href="https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/mod.rs#L4748"><strong>CPU_COUNT</strong></a><strong> and </strong><a href="https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/mod.rs#L4739"><strong>CPU_COUNT_S</strong></a><strong> are defined directly in </strong><a href="https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/mod.rs"><strong>src/unix/linux_like/linux/mod.rs</strong></a>, inside the f! macro. Not in linux_l4re_shared.rs, orteeos/mod.rs.</p><p>linux_l4re_shared.rs contains a duplicate copy of the same functions, but for the x86_64-unknown-linux-gnu target used by the Akirav2 binary, the code that actually compiles in is from this file.</p><h3>Back to the disassembly…</h3><p>The malware replaces the hardcoded 4u32 with the dynamic thread count from <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/thread.rs">available_parallelism()</a>. That single substitution is what triggers the entire inlining cascade described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*mf1ZdsLxQOTLyZs5Jq0SFA.png" /><figcaption>An immediate puzzl in `default_action`, linear mode in disassembly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*3YZMo2AxJwbFY5suJAa0xg.png" /><figcaption>An immediate puzzl in `default_action`, graph mode in disassembly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*deFvkK1YrROyPF9kPlQXmg.png" /></figure><p>The original <a href="https://github.com/console-rs/indicatif/blob/main/examples/yarnish.rs">yarnish.rs</a> hardcodes 4 threads. The binary does <strong>not</strong> hardcode 4. Instead, default_action begins with a large block of low-level calls.</p><blockquote><em>The malware authors </em><strong><em>“probably”</em></strong><em> have replaced </em><em>0..4u32 with a runtime value. That runtime value requires querying the CPU count. The standard Rust idiom for CPU count is </em><em>available_parallelism().</em></blockquote><p>This is <strong>abductive reasoning</strong> (inference to best explanation), not direct identification. The argument is:</p><ol><li>Template originally had 0..4u32</li><li>Binary has a variable thread count</li><li>CLI flag --threads exists with explicit Default: number of logical CPU cores help text (this string survives in the binary as a literal)</li><li>Therefore the None branch of the match must call something that returns core count</li><li>The idiomatic stdlib call for that is available_parallelism()</li></ol><p>The compiler inlined the following call tree, five levels deep, directly into default_action:</p><pre>available_parallelism()<br>  -&gt; quota()                     [reads /proc/self/cgroup]<br>      -&gt; quota_v1(path)           [cgroup v1 CPU quota]<br>      -&gt; quota_v2(path)           [cgroup v2 CPU quota]<br>  -&gt; libc::CPU_COUNT(&amp;set)<br>      -&gt; CPU_COUNT_S(size, set)<br>          -&gt; count_ones()         [LLVM popcnt intrinsic]<br>              -&gt; BitPopulationCount  [expanded as magic-constant popcount]<br>  -&gt; libc::sched_getaffinity(...)<br>  -&gt; libc::sysconf(_SC_NPROCESSORS_ONLN)</pre><h3>LLVM Instrinsic `popcnt`</h3><p>From the source code of <a href="https://github.com/rust-lang/libc/blob/0.2.159/src/unix/linux_like/linux/mod.rs">mod.rs</a>(src/unix/linux_like/linux/mod.rs):</p><pre>pub fn CPU_COUNT_S(size: usize, cpuset: &amp;cpu_set_t) -&gt; ::c_int {<br>    let mut s: u32 = 0;<br>    let size_of_mask = ::mem::size_of_val(&amp;cpuset.bits[0]);<br>    for i in cpuset.bits[..(size / size_of_mask)].iter() {<br>        s += i.count_ones();<br>    };<br>    s as ::c_int<br>}</pre><p>On x86–64, cpu_set_t.bits is [u64; 16] . Each iteration calls u64::count_ones().</p><h3>Proving the chain: count_ones() to llvm.ctpop.i64</h3><p><strong>A brief summary:</strong></p><ul><li><strong>Step 1.</strong> u64::count_ones() calls intrinsics::ctpop(self). Source-confirmed, from pasted uint_macros.rs at commit db034cee.</li><li><strong>Step 2.</strong> Rust commit db034cee uses LLVM 19.1.3, submodule pinned to b35599b. Source-confirmed, from your screenshot of github.com/rust-lang/rust/tree/db034cee.../src.</li><li><strong>Step 3.</strong> LLVM 19.1.3 registers ISD::CTPOP / MVT::i64 as Custom when Subtarget.hasPOPCNT() is false. Source-confirmed, from pasted X86ISelLowering.cpp at llvmorg-19.1.3.</li><li><strong>Step 4.</strong> The custom handler LowerCTPOP returns SDValue() for a full 64-bit operand with no statically known zero bits, signalling fallback to generic expansion. Source-confirmed, from pasted LowerCTPOP at llvmorg-19.1.3.</li><li><strong>Step 5.</strong> The generic expansion is TargetLowering::expandCTPOP in llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp. It constructs Mask55, Mask33, and Mask0F via APInt::getSplat(64, APInt(8, 0x55/0x33/0x0F)), producing 0x5555555555555555, 0x3333333333333333, and 0x0f0f0f0f0f0f0f0f. The code cites its own source: Sean Anderson&#39;s &quot;Bit Twiddling Hacks&quot;. Source-confirmed, from pasted TargetLowering.cpp at llvmorg-19.1.3.</li><li><strong>Step 6.</strong> The same algorithm, same constants, appears in the Flang runtime header at LLVM commit 521c996. Source-confirmed, from pasted bit-population-count.h. This confirms the constants are a property of LLVM&#39;s target-independent infrastructure, not of the source language.</li></ul><h4>Now let’s breakdown step by step.</h4><p><strong>Layer 1: </strong><strong>count_ones() to </strong><strong>core::intrinsics::ctpop</strong></p><p>At commit 79e9716c980570bfd1f666e3b16ac583f0168962, <a href="https://github.com/rust-lang/rust/blob/79e9716c980570bfd1f666e3b16ac583f0168962/library/core/src/num/uint_macros.rs">library/core/src/num/uint_macros.rs</a> defines count_ones as:</p><pre>#[stable(feature = &quot;rust1&quot;, since = &quot;1.0.0&quot;)]<br>#[rustc_const_stable(feature = &quot;const_math&quot;, since = &quot;1.32.0&quot;)]<br>#[doc(alias = &quot;popcount&quot;)]<br>#[doc(alias = &quot;popcnt&quot;)]<br>#[must_use = &quot;this returns the result of the operation, \<br>              without modifying the original&quot;]<br>#[inline(always)]<br>pub const fn count_ones(self) -&gt; u32 {<br>    return intrinsics::ctpop(self);<br>}</pre><blockquote>For a u64 receiver, intrinsics::ctpop(self) compiles to the LLVM IR call llvm.ctpop.i64.</blockquote><p>Two details from the attributes are significant.</p><ul><li>#[inline(always)] means the call is always inlined at the call site, so no call instruction is ever emitted for it.</li><li>#[doc(alias = &quot;popcnt&quot;)] is a documentation alias that the Rust compiler team added precisely because this function is the stable surface of the hardware popcount concept.</li></ul><p>The body delegates unconditionally to intrinsics::ctpop, a Rust compiler intrinsic with no Rust-level implementation: it is a direct instruction to the compiler backend to emit the LLVM IR node ISD::CTPOP, which for a u64 operand produces llvm.ctpop.i64.</p><p><strong>Layer 2: </strong><strong>llvm.ctpop.i64 to machine instruction, conditional on </strong><strong>+popcnt</strong></p><p>It is very likely commit 79e9716 using <strong>rustc 1.74.0</strong>, LLVM 17.x, pinned to <a href="https://github.com/rust-lang/llvm-project/tree/fef3d7b14ede45d051dc688aae0bb8c8b02a0566">rust-lang/llvm-project </a>at commit <a href="https://github.com/rust-lang/llvm-project/tree/fef3d7b14ede45d051dc688aae0bb8c8b02a0566">fef3d7b14ede45d051dc688aae0bb8c8b02a0566</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFAqs9-1nyvbextB_079ig.png" /></figure><p>The LLVM x86 instruction selection file X86ISelLowering.cpp contains the following logic (<a href="https://raw.githubusercontent.com/llvm/llvm-project/refs/tags/llvmorg-19.1.3/llvm/lib/Target/X86/X86ISelLowering.cpp">llvmorg-19.1.3/llvm/lib/Target/X86/X86ISelLowering.cpp</a>):</p><pre>if (Subtarget.hasPOPCNT()) {<br>    setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);<br>    // popcntw is longer to encode than popcntl and also has a false dependency<br>    // on the dest that popcntl hasn&#39;t had since Cannon Lake.<br>    setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);<br>  } else {<br>    setOperationAction(ISD::CTPOP          , MVT::i8   , Custom);<br>    setOperationAction(ISD::CTPOP          , MVT::i16  , Custom);<br>    setOperationAction(ISD::CTPOP          , MVT::i32  , Custom);<br>    setOperationAction(ISD::CTPOP          , MVT::i64  , Custom);<br>  }</pre><p>This is the registration of how LLVM 19.1.3 will handle ISD::CTPOP for each integer width on x86. When Subtarget.hasPOPCNT() is false, MVT::i64 is marked Custom, meaning LLVM will call a custom lowering function rather than emitting a single popcnt instruction. This is the decision point that determines whether the bitmask sequence appears.</p><h3>Where the constants come from</h3><p>They come from TargetLowering::expandCTPOP in <a href="https://raw.githubusercontent.com/llvm/llvm-project/refs/tags/llvmorg-19.1.3/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp">llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp</a>. This is the <strong>target-independent</strong> generic expansion function in LLVM&#39;s code generation infrastructure.</p><p>The call chain when +popcnt is absent is:</p><pre>LowerCTPOP (X86ISelLowering.cpp)<br>    -&gt; returns SDValue() for full 64-bit operands<br>        -&gt; LegalizeDAG calls TargetLowering::expandCTPOP (TargetLowering.cpp)<br>            -&gt; emits the bitmask sequence</pre><p>The constants appear in expandCTPOP as the Hamming weight algorithm. The Flang header you pasted is a human-readable C++ expression of exactly the same algorithm. The constants are identical because both implement the same mathematical identity: to count set bits, partition the word into 2-bit fields, count each, then sum progressively wider groups.</p><blockquote>The algorithm works by a divide-and-conquer strategy: count bits in groups of 2, then merge groups of 4, then 8, and so on until the whole word is summed. Each step uses a bitmask to isolate the relevant bits.</blockquote><pre>SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &amp;DAG) const {<br>  ...<br><br>  // This is the &quot;best&quot; algorithm from<br>  // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel<br>  SDValue Mask55 =<br>      DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);<br>  SDValue Mask33 =<br>      DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);<br>  SDValue Mask0F =<br>      DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);<br><br>...</pre><h4><strong>What the Akira disassembly tells you</strong></h4><p><a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">The report</a> observes those exact bitmask constants in the Akira assembly. This confirms that akirav2.elf was compiled without the +popcnt target feature, so llvm.ctpop.i64 expanded to the software path rather than a single popcnt instruction.</p><p>u64::count_ones() at commit db034cee unconditionally delegates to core::intrinsics::ctpop, which maps to llvm.ctpop.i64. Whether that IR node produces a single popcnt rax, rdi or a multi-instruction software bitmask sequence depends solely on whether +popcnt is present in the compile-time target feature set. In akirav2.elf, the software path was taken, evidenced by the bitmask constants visible in the disassembly.</p><p>The popcount expansion is what produces the 200-instruction basic block. The standard software-popcount algorithm uses a sequence of bitmasks (0x5555555555555555, 0x3333333333333333, 0x0f0f0f0f0f0f0f0f) that are recognisable once you know what you are looking at:</p><pre>x = (x &amp; 0x5555555555555555) + ((x &gt;&gt; 1) &amp; 0x5555555555555555);<br>x = (x &amp; 0x3333333333333333) + ((x &gt;&gt; 2) &amp; 0x3333333333333333);<br>// ...</pre><p>The appearance of these constants in an otherwise opaque basic block is the forensic fingerprint that tells you the entire block is an inlined CPU_COUNT.</p><blockquote><strong>Note</strong>: in Release-mode Rust binaries, a single innocuous standard library call can expand into hundreds of instructions through aggressive inlining. The correct analysis strategy is to identify the innermost inlined functions by their constants and patterns first, then work outward to reconstruct the call tree.</blockquote><h3>Section 5: VM Shutdown (--stopvm)</h3><blockquote>I have discovered this in the previous article <a href="https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-1-937e0388d2c7">Akirav2 Analysis Part 1</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ns8zbeyXeyL7s-_IxDERPQ.png" /><figcaption>Some interesting strings found in the section of `.rodata`</figcaption></figure><p>If --stopvm is passed, default_action forks a child process and executes:</p><pre>vim-cmd vmsvc/getallvms | tail -n +2 | awk &#39;{system(&quot;vim-cmd vmsvc/power.off &quot; $1)}&#39;</pre><p>This uses ESXi’s built-in vim-cmd management utility to enumerate all registered VMs and power them off sequentially. The ransomware must run with sufficient ESXi privileges for this to succeed. This is a standard pre-encryption step in ESXi-targeting ransomware: powered-on VMs hold file locks that block encryption.</p><p>Looking at the strings section and it contains multiple critical findings:</p><p><strong>ESXi targeting confirmed:</strong></p><pre>/vmfs/volumes<br>vim-cmd vmsvc/getallvms | tail -n +2 | awk &#39;{system(&quot;vim-cmd vmsvc/power.off &quot; $1)}&#39;</pre><p>This is the exact shell command to enumerate and power off all VMs on an ESXi host, confirming the Check Point analysis.</p><blockquote><strong>ESXi</strong> is VMware’s bare-metal hypervisor. It runs directly on server hardware (no host OS underneath) and hosts multiple virtual machines. In enterprise environments it is extremely common: one physical server running ESXi might host dozens of VMs for databases, domain controllers, file servers, etc.</blockquote><h4>Why ransomware authors love targeting it?</h4><ul><li><strong>One infection, massive blast radius.</strong> Encrypt the ESXi host and every VM it manages goes down simultaneously, rather than having to compromise each machine individually.</li><li><strong>Often poorly monitored.</strong> EDR agents are rarely deployed on hypervisor hosts the way they are on Windows endpoints.</li><li><strong>Critical infrastructure.</strong> Organisations are under extreme pressure to pay because their entire virtualised environment is offline.</li><li><strong>NFS/VMFS datastores.</strong> VM disk images (.vmdk files) live on shared storage volumes that ESXi mounts directly, so the ransomware can enumerate and encrypt them efficiently without touching individual guest OSes.</li></ul><p>The --path /vmfs/volumes default you saw in the <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Check Point article </a>is the standard ESXi datastore mount point. That single directory contains the disk images for every hosted VM.</p><h3>RE Methodology Takeaways</h3><p>Check Point’s report is as much about method as it is about this specific binary. The principles that made it possible:</p><ol><li><strong>Do not start by reading assembly top-down.</strong> Identify framework code first (seahorse, indicatif) by searching for function names and strings that appear in the binary.</li><li><strong>Recognise inlining by constants, not call structure.</strong> Magic constants like popcount masks, cgroup path strings (/proc/self/cgroup), and well-known errno values are fingerprints of inlined library functions even when no call instruction is present.</li><li><strong>Know the type layouts.</strong> Understanding that IntoIter&lt;OsString&gt; is a 32-byte header with a 24-byte-strided heap buffer makes the argument-parsing assembly readable. Without that, it is just pointer arithmetic.</li><li><strong>Follow the PAL boundary.</strong> Standard library types like Args and OsString have OS-specific implementations. The assembly reflects the PAL target, not the public API.</li><li><strong>Release vs Debug mode.</strong> The same source code can produce thousands of additional instructions in Release mode due to inlining, loop unrolling, and LLVM intrinsic expansion.</li></ol><h3>Further Reading</h3><h3>1. SIMD</h3><blockquote>SIMD stands for <strong>Single Instruction, Multiple Data</strong>. It is a CPU execution model where one instruction operates on multiple data elements in parallel, using wide registers.</blockquote><h4>What SIMD means in hardware</h4><p>Instead of adding two 32-bit integers, a SIMD instruction can add eight 32-bit integers simultaneously, all in one clock cycle, using a 256-bit register (like ymm0).</p><p>Register families you will encounter:</p><ul><li><strong>MMX</strong> (64-bit, obsolete)</li><li><strong>SSE / SSE2 / SSE4</strong> (xmm0–xmm15, 128-bit)</li><li><strong>AVX / AVX2</strong> (ymm0–ymm15, 256-bit)</li><li><strong>AVX-512</strong> (zmm0–zmm31, 512-bit)</li></ul><h4>Why it matters in RE</h4><ul><li><strong>Compiler auto-vectorisation.</strong> Compilers (LLVM, GCC, MSVC) aggressively auto-vectorise loops. A simple memcpy, memcmp, or string scan in source becomes SIMD instructions in the binary. This makes hot loops look unfamiliar if you are not expecting it.</li><li><strong>Obfuscation and packing.</strong> Packers and obfuscators sometimes use SIMD intentionally to complicate static taint analysis, because most taint engines either do not track xmm/ymm registers at all or do so poorly.</li><li><strong>Rust and SIMD.</strong> Rust’s standard library uses SIMD for things like memchr (which backs aho-corasick internally). When you see a tight loop in a Rust binary using pcmpeqb or vpcmpeqb, it is almost certainly memchr or a SIMD-accelerated pattern search, not custom malware logic. Relevant to your Akira analysis: if you see SIMD near the search routines, that is likely the aho-corasick crate doing pattern matching.</li><li><strong>Cryptography.</strong> AES-NI (aesenc, aesdec) is technically a SIMD-adjacent extension. Much ransomware uses AES, usually via AES-NI (aesenc and friends), so spotting aesenc is normally a strong sign AES is present. This Akira v2 sample instead uses the SOSEMANUK stream cipher, implemented in software with no AES-NI, and indeed no aesenc, aesdec or related opcodes appear anywhere in the 428k-line disassembly. The asymmetry matters: absence of aesenc only rules out AES-NI-accelerated AES (software AES or any stream cipher would also lack it), so it is a useful negative filter, not a positive identification. The positive call rests on the SOSEMANUK constants (the 0x54655307 FSM multiplier with rotate-left-7, and the Serpent key-schedule constant 0x9E3779B9).</li></ul><h4>Common SIMD instructions worth recognising</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*WZn2uNljzyy-vIMMNE0a0g.png" /></figure><p>vzeroupper in particular is a useful marker: it almost always appears at the end of a function that used AVX, so it helps you identify function boundaries in stripped binaries.</p><h3>2. How aho-corasick uses memchr and SIMD</h3><h4>The dependency chain</h4><pre>aho-corasick  →  memchr  →  SIMD intrinsics (platform-dependent)</pre><p>aho-corasick uses memchr as an accelerator for its &quot;teddy&quot; algorithm, which is its SIMD-accelerated literal search backend. The relevant source locations:</p><blockquote><strong>aho-corasick calling </strong><strong>memchr:</strong> <a href="https://github.com/BurntSushi/aho-corasick/blob/master/src/packed/teddy/generic.rs">https://github.com/BurntSushi/aho-corasick/blob/master/src/packed/teddy/generic.rs</a></blockquote><p>The teddy backend uses 128-bit or 256-bit shuffles to match candidate bytes in parallel before running the full automaton. Look specifically at the find_at methods and the Teddy struct.</p><blockquote><strong>memchr SIMD implementation:</strong> <a href="https://github.com/BurntSushi/memchr/blob/master/src/arch/x86_64/sse2/memchr.rs">https://github.com/BurntSushi/memchr/blob/master/src/arch/x86_64/sse2/memchr.rs</a> <a href="https://github.com/BurntSushi/memchr/blob/master/src/arch/x86_64/avx2/memchr.rs">https://github.com/BurntSushi/memchr/blob/master/src/arch/x86_64/avx2/memchr.rs</a></blockquote><p>The SSE2 path uses _mm_cmpeq_epi8 (which compiles to pcmpeqb) and _mm_movemask_epi8 (which compiles to pmovmskb). The Advanced Vector Extensions (AVX2) path uses the ymm equivalents.</p><blockquote><a href="https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html">Advanced Vector Extensions</a>, <strong>AVX,</strong> is Intel’s extension to the x86 ISA that widens SIMD registers from 128-bit (SSE) to 256-bit, and later 512-bit (AVX-512).</blockquote><h3>What this looks like in a stripped binary</h3><p>In Binary Ninja, when you find the aho-corasick search loop (recoverable from your panic strings since you already confirmed crate aho-corasick 1.1.2), expect to see a structure like this:</p><pre>; Outer loop: advance through the haystack in 16 or 32-byte chunks<br>vmovdqu  ymm0, [rsi + rax]       ; load 32 bytes of haystack<br>vpshufb  ymm1, ymm2, ymm0        ; teddy shuffle: match low nibbles<br>vpshufb  ymm3, ymm4, ymm0        ; teddy shuffle: match high nibbles<br>vpand    ymm1, ymm1, ymm3        ; AND the masks together<br>vptest   ymm1, ymm1              ; test if any candidates found<br>jz       .next_chunk             ; no match, advance<br>; ... fallthrough to verification logic</pre><p>vpshufb (SIMD byte shuffle) is the <strong>fingerprint of the teddy algorithm</strong> specifically. If you see vpshufb in a tight loop over a memory region, that is almost certainly teddy, not custom logic.</p><h3>What version 1.1.2 specifically uses</h3><p>The recovered crate version is aho-corasick 1.1.2. At that version:</p><ul><li>Source tag: <a href="https://github.com/BurntSushi/aho-corasick/tree/1.1.2">https://github.com/BurntSushi/aho-corasick/tree/1.1.2</a></li><li>Teddy implementation: src/packed/teddy/ directory</li><li>The Fat (256-bit AVX2) and Slim (128-bit SSE2) variants are both present; which one your binary uses depends on what the compile target supported</li></ul><p>Check src/packed/teddy/generic.rs at that tag for the exact loop structure: <a href="https://github.com/BurntSushi/aho-corasick/blob/1.1.2/src/packed/teddy/generic.rs">https://github.com/BurntSushi/aho-corasick/blob/1.1.2/src/packed/teddy/generic.rs</a></p><h3>How to confirm in the Akira binary</h3><ol><li>In Binary Ninja, search for vpshufb or pcmpeqb instructions in the disassembly</li><li>If found in a loop iterating over a buffer, cross-reference against the panic string offsets you already recovered for aho-corasick</li><li>The function containing this loop is the teddy search kernel; it will be called from the automaton search dispatch</li></ol><blockquote>Though I cannot tell you the exact virtual address or function offset because that requires your specific binary. The panic string Relative Virtual Addresses (RVAs) that have already been recovered are the anchor points for finding the call sites.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dY4C1SRMDqEjltSREbAhdg.png" /><figcaption>Thanks for reading</figcaption></figure><h3>References</h3><p><strong>Source Code &amp; API Documentation</strong></p><p>Rust-lang (no date) <em>core::ffi::c_str — CStr implementation</em>. Available at: <a href="https://github.com/rust-lang/rust/blob/main/library/core/src/ffi/c_str.rs">https://github.com/rust-lang/rust/blob/main/library/core/src/ffi/c_str.rs</a></p><p>Rust-lang (no date) <em>std::ffi::c_str — re-export layer</em>. Available at: <a href="https://github.com/rust-lang/rust/blob/main/library/std/src/ffi/c_str.rs">https://github.com/rust-lang/rust/blob/main/library/std/src/ffi/c_str.rs</a></p><p>Rust-lang (2023) <em>std::sys::unix::fs — historical unix filesystem implementation including open_c</em>. Available at: <a href="https://github.com/rust-lang/rust/blob/5a7834050f3a0ebcd117b4ddf0bc1e8459594309/library/std/src/sys/unix/fs.rs">https://github.com/rust-lang/rust/blob/5a7834050f3a0ebcd117b4ddf0bc1e8459594309/library/std/src/sys/unix/fs.rs</a></p><p>Rust-lang (no date) <em>std::sys::fs::unix — current unix filesystem implementation</em>. Available at: <a href="https://github.com/rust-lang/rust/blob/main/library/std/src/sys/fs/unix.rs">https://github.com/rust-lang/rust/blob/main/library/std/src/sys/fs/unix.rs</a></p><p>Rust-lang (no date) <em>core::ptr::mod — drop_in_place definition</em>. Available at: <a href="https://github.com/rust-lang/rust/blob/main/library/core/src/ptr/mod.rs">https://github.com/rust-lang/rust/blob/main/library/core/src/ptr/mod.rs</a></p><p>Rust-lang (no date) <em>std::fs — public File and OpenOptions API</em>. Available at: <a href="https://github.com/rust-lang/rust/blob/main/library/std/src/fs.rs">https://github.com/rust-lang/rust/blob/main/library/std/src/fs.rs</a></p><p>Rust-lang (no date) <em>core::ptr::drop_in_place — stable API documentation</em>. Available at: <a href="https://doc.rust-lang.org/beta/core/ptr/fn.drop_in_place.html">https://doc.rust-lang.org/beta/core/ptr/fn.drop_in_place.html</a></p><p>ksk001100 (no date) <em>seahorse::app — App struct and run_with_result implementation</em>. Available at: <a href="https://github.com/ksk001100/seahorse/blob/master/src/app.rs">https://github.com/ksk001100/seahorse/blob/master/src/app.rs</a></p><p>console-rs (no date) <em>indicatif — progress bar and spinner library</em>. Available at: <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs</a></p><p><strong>Threat Intelligence &amp; Research Reports</strong></p><p>Check Point Research (2024) <em>Inside Akira Ransomware’s Rust Experiment</em>. Available at: <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/</a></p><p>CISA, FBI, EC3 and NCSC-NL (2024) <em>#StopRansomware: Akira Ransomware</em> [Joint Cybersecurity Advisory AA24–109A]. Available at: <a href="https://www.cisa.gov/news-events/cybersecurity-advisories/aa24-109a">https://www.cisa.gov/news-events/cybersecurity-advisories/aa24-109a</a></p><p>CISA, FBI, EC3 and NCSC-NL (2024) <em>#StopRansomware: Akira Ransomware</em> [PDF version]. Available at: <a href="https://www.ic3.gov/CSA/2024/240418.pdf">https://www.ic3.gov/CSA/2024/240418.pdf</a></p><p>Cisco Talos (2024) <em>Akira Ransomware Continues to Evolve</em>. Available at: <a href="https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/">https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/</a></p><p>Palo Alto Unit 42 (2024) <em>Threat Assessment: Howling Scorpius (Akira Ransomware)</em>. Available at: <a href="https://unit42.paloaltonetworks.com/threat-assessment-howling-scorpius-akira-ransomware/">https://unit42.paloaltonetworks.com/threat-assessment-howling-scorpius-akira-ransomware/</a></p><p>MITRE ATT&amp;CK (no date) <em>Akira_v2, Software S1194</em>. Available at: <a href="https://attack.mitre.org/software/S1194/">https://attack.mitre.org/software/S1194/</a></p><p>Security Online (2024) <em>Akira v2 Emerges: Rust-Based Ransomware Raises the Stakes</em>. Available at: <a href="https://securityonline.info/akira-v2-emerges-rust-based-ransomware-raises-the-stakes/">https://securityonline.info/akira-v2-emerges-rust-based-ransomware-raises-the-stakes/</a></p><p><strong>aho-corasick / Teddy</strong></p><p>Burntsushi (no date) <em>aho-corasick 1.1.2 — packed::teddy::builder</em>. Available at: <a href="https://docs.rs/aho-corasick/1.1.2/src/aho_corasick/packed/teddy/builder.rs.html">https://docs.rs/aho-corasick/1.1.2/src/aho_corasick/packed/teddy/builder.rs.html</a></p><p><strong>Intel ISA and SIMD architecture</strong></p><ul><li>Intel 64 and IA-32 Architectures Software Developer’s Manual: <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html">https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html</a></li><li>Intel Intrinsics Guide (instruction-level reference): <a href="https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html">https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html</a></li></ul><p><strong>SSE / AVX register sets</strong></p><ul><li>Felix Cloutier’s x86 instruction reference (community mirror, widely used): <a href="https://www.felixcloutier.com/x86/">https://www.felixcloutier.com/x86/</a></li></ul><p><strong>Compiler auto-vectorisation</strong></p><ul><li>LLVM auto-vectorisation documentation: <a href="https://llvm.org/docs/Vectorizers.html">https://llvm.org/docs/Vectorizers.html</a></li><li>MSVC auto-vectorisation reference: <a href="https://learn.microsoft.com/en-us/cpp/parallel/auto-parallelization-and-auto-vectorization">https://learn.microsoft.com/en-us/cpp/parallel/auto-parallelization-and-auto-vectorization</a></li></ul><p><strong>Rust memchr and SIMD</strong></p><ul><li>memchr crate (Andrew Gallant): <a href="https://github.com/BurntSushi/memchr">https://github.com/BurntSushi/memchr</a></li><li>aho-corasick crate SIMD internals: <a href="https://github.com/BurntSushi/aho-corasick">https://github.com/BurntSushi/aho-corasick</a></li></ul><p><strong>AES-NI</strong></p><ul><li>Intel AES-NI white paper: <a href="https://www.intel.com/content/dam/doc/white-paper/advanced-encryption-standard-new-instructions-set-paper.pdf">https://www.intel.com/content/dam/doc/white-paper/advanced-encryption-standard-new-instructions-set-paper.pdf</a></li></ul><p><strong>vzeroupper behaviour</strong></p><ul><li>Agner Fog optimisation manuals (function boundary and transition costs): <a href="https://www.agner.org/optimize/">https://www.agner.org/optimize/</a></li></ul><p><strong>AVX</strong></p><ul><li>Intel Intrinsics Guide (AVX/AVX2 filter): <a href="https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html">https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html</a></li><li>Agner Fog: transition penalties and vzeroupper behaviour: <a href="https://www.agner.org/optimize/">https://www.agner.org/optimize/</a></li><li>Felix Cloutier x86 reference (vzeroupper): <a href="https://www.felixcloutier.com/x86/vzeroupper">https://www.felixcloutier.com/x86/vzeroupper</a></li></ul><p><strong>popcnt</strong></p><p>The Rust Project Developers (n.d.) core/num/uint_macros.rs source, <em>Rust Standard Library Source</em>. Available at: <a href="https://doc.rust-lang.org/src/core/num/uint_macros.rs.html">https://doc.rust-lang.org/src/core/num/uint_macros.rs.html</a></p><p>LLVM Project (2024) llvm/lib/Target/X86/X86ISelLowering.cpp at tag llvmorg-19.1.3. Available at: <a href="https://raw.githubusercontent.com/llvm/llvm-project/refs/tags/llvmorg-19.1.3/llvm/lib/Target/X86/X86ISelLowering.cpp">https://raw.githubusercontent.com/llvm/llvm-project/refs/tags/llvmorg-19.1.3/llvm/lib/Target/X86/X86ISelLowering.cpp</a></p><p>LLVM Project (2024) llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp at tag llvmorg-19.1.3, function expandCTPOP. Available at: <a href="https://raw.githubusercontent.com/llvm/llvm-project/refs/tags/llvmorg-19.1.3/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp">https://raw.githubusercontent.com/llvm/llvm-project/refs/tags/llvmorg-19.1.3/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp</a></p><p>LLVM Project (2024) flang/include/flang/Common/bit-population-count.h at commit 521c996. Available at: <a href="https://github.com/llvm/llvm-project/blob/521c99627690e09ba25383c83232f94ff457f00c/flang/include/flang/Common/bit-population-count.h">https://github.com/llvm/llvm-project/blob/521c99627690e09ba25383c83232f94ff457f00c/flang/include/flang/Common/bit-population-count.h</a></p><p>Anderson, S. (n.d.) ‘Bit Twiddling Hacks: Count bits set in parallel’. Available at: <a href="http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel">http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel</a></p><p><strong>lock function reconstruction</strong></p><p>The Rust Project Developers (2024) <em>std::thread::available_parallelism</em>. The Rust Standard Library. Available at: <a href="https://doc.rust-lang.org/std/thread/fn.available_parallelism.html">https://doc.rust-lang.org/std/thread/fn.available_parallelism.html</a></p><p>Tompkins, W. et al. (2024) <em>Akira ransomware continues to evolve</em>. Cisco Talos Intelligence. Available at: <a href="https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/">https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/</a></p><p>console-rs (2024) <em>indicatif yarnish.rs example</em>. GitHub. Available at: <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs</a></p><p>ksk001100 (2024) <em>seahorse CLI framework</em>. GitHub. Available at: <a href="https://github.com/ksk001100/seahorse">https://github.com/ksk001100/seahorse</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=147889a51966" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-2-147889a51966">Reversing Akira’s Rust Experiment : A Breakdown Part 2</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interesting instructions in Rust binary: lock cmpxchg]]></title>
            <link>https://medium.com/re-exploit/interesting-unusal-instructions-in-rust-binary-lock-cmpxchg-17fc2bce7da5?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/17fc2bce7da5</guid>
            <category><![CDATA[reverse-engineering-rust]]></category>
            <category><![CDATA[rust-disassembly]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[lock-cmpxchg]]></category>
            <category><![CDATA[x86-64]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Thu, 14 May 2026 22:11:17 GMT</pubDate>
            <atom:updated>2026-05-15T22:13:18.502Z</atom:updated>
            <content:encoded><![CDATA[<p>The story starts when I reverse engineer a “normal” Rust binary (release build, MCVC x64 PE), also inspected a tab “Tags” in Binary Ninja.</p><p>It says…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*MekF2fi7jRRTxpzA4qb29Q.png" /><figcaption>Tabs — Unresolved Indirect Control Flow (13)</figcaption></figure><p>As we may (or not) know, function boundary identification is notoriously hard in Rust binaries (I think it’s still is in C++ binaries too). Not surprised I saw them. For the Reverse Engineering workflow, <strong>the unresolved indirect jumps</strong> can be the most interesting targets. Each one is a potential trait object dispatch site. To resolve them:</p><ol><li>Navigate to the jmp rax site</li><li>Look backwards for where rax was loaded: typically mov rax, [some_ptr + offset] where some_ptr points into a vtable</li><li>Find the vtable in .data.rel.ro and read the function pointer array</li><li>Cross-reference with panic strings or symbol hashes to identify the trait</li></ol><p>But what attracts me and grabbed my attention is the unusal instruction lock cmpxchg (see the figure below)…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*DwSp6k_G67T6asFtx8eEKQ.png" /><figcaption>Ummm… interesting.</figcaption></figure><p>You can have a look at some disucssion and resources, like:</p><ul><li><a href="https://stackoverflow.com/questions/59020823/how-does-lock-cmpxchg-work-in-assembly">https://stackoverflow.com/questions/59020823/how-does-lock-cmpxchg-work-in-assembly</a></li><li><a href="https://medium.com/@m-ibrahim.research/atomic-moves-lock-free-programming-straight-from-the-cpu-446f0ffe83c6">https://medium.com/@m-ibrahim.research/atomic-moves-lock-free-programming-straight-from-the-cpu-446f0ffe83c6</a></li><li><a href="https://heather.cs.ucdavis.edu/matloff/public_html/50/PLN/lock.pdf">https://heather.cs.ucdavis.edu/matloff/public_html/50/PLN/lock.pdf</a></li></ul><p>As described in <a href="https://heather.cs.ucdavis.edu/matloff/public_html/50/PLN/lock.pdf">this course material</a>:</p><blockquote>Operation of the ‘cmpxchg’ instruction is described (on 3 pages) in<a href="https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html"> Volume 2A</a> of Intel Manual.</blockquote><p>First thing first, this is nothing to do with the source code. It comes entirely from the stdlib’s futex::Once::call, triggered indirectly by println! initialising the stdout singleton on its first call.</p><pre><br>use std::hint::black_box;<br><br>trait Speak {<br>    fn say_hello(&amp;self);<br>}<br><br>struct Human;<br>struct Robot;<br><br>impl Speak for Human {<br>    fn say_hello(&amp;self) {<br>        println!(&quot;Hi!&quot;);<br>    }<br>}<br><br>impl Speak for Robot {<br>    fn say_hello(&amp;self) {<br>        println!(&quot;Beep boop!&quot;);<br>    }<br>}<br><br>#[inline(never)]<br>fn greet(speaker: &amp;dyn Speak) {<br>    speaker.say_hello();<br>}<br><br>fn main() {<br>    let h = Human;<br>    let r = Robot;<br><br>    greet(&amp;h);<br>    greet(&amp;r);<br><br>    black_box(&amp;h);<br>    black_box(&amp;r);<br>}</pre><h3>Lock-Free Programming</h3><p>Let’s have a quick recap before discussing this instruction…</p><h4>The problem it solves</h4><p>In concurrent programming, multiple threads share data. The naive solution is a mutex:</p><pre>let data = Mutex::new(0u64);<br>// Thread A:<br>let mut guard = data.lock().unwrap();  // blocks if Thread B holds it<br>*guard += 1;<br>// lock released on drop</pre><p>Mutexes work, but they have costs:</p><ul><li><strong>Blocking:</strong> a thread that cannot acquire the lock goes to sleep, requiring OS scheduler involvement (syscall, context switch)</li><li><strong>Priority inversion:</strong> a low-priority thread holding the lock blocks a high-priority thread</li><li><strong>Deadlock:</strong> two threads each waiting for a lock the other holds</li><li><strong>Convoying:</strong> threads queue behind the lock holder even if the critical section is trivially short</li></ul><p>Lock-free programming eliminates the lock entirely. Instead of serialising access through mutual exclusion, it uses <strong>hardware atomic operations</strong> that the CPU guarantees are indivisible.</p><h4>The hardware foundation: atomicity</h4><p>On x86–64, certain operations are guaranteed atomic by the ISA:</p><ul><li>Aligned reads and writes up to 64 bits are naturally atomic (no tearing)</li><li>The lock prefix makes a read-modify-write sequence atomic: lock add, lock xchg, lock cmpxchg</li></ul><blockquote>“Atomic” means: no other core can observe the memory location in an intermediate state. The operation either has happened completely or not at all, from every core’s perspective.</blockquote><h4>The key primitive: Compare-and-Swap (CAS)</h4><p>Everything in lock-free programming is built on CAS. In Rust:</p><p>rust</p><pre>use std::sync::atomic::{AtomicU64, Ordering};<br>let counter = AtomicU64::new(0);<br>// CAS: &quot;if counter == expected, set it to desired, return Ok(desired)&quot;<br>//      &quot;if counter != expected, return Err(actual_value)&quot;<br>counter.compare_exchange(expected, desired, success_ord, fail_ord);</pre><p>The canonical lock-free update pattern:</p><pre>loop {<br>    let current = counter.load(Ordering::Acquire);<br>    let next = current + 1;<br>    match counter.compare_exchange(current, next, Ordering::Release, Ordering::Relaxed) {<br>        Ok(_) =&gt; break,       // CAS succeeded, we won the race<br>        Err(_) =&gt; continue,   // another thread changed it first, retry<br>    }<br>}</pre><p>This is exactly the loop you saw earlier in sub_140003b10. No mutex, no OS call, no sleeping.</p><h3>What lock cmpxchg is</h3><p>cmpxchg = <strong>Compare and Exchange</strong>. It is the x86 atomic compare-and-swap primitive.</p><p>The semantics in one line:</p><blockquote><em>If </em><em>[mem] equals </em><em>rax, write </em><em>rdx into </em><em>[mem] and set ZF=1. Otherwise load </em><em>[mem] into </em><em>rax and set ZF=0. Atomically.</em></blockquote><p>The lock prefix makes the entire operation a single atomic bus transaction: it asserts the cache-line lock on the target memory address for the duration, preventing any other core from reading or writing that address between the compare and the exchange.</p><p>Without lock, on a multicore system, another thread could modify [mem] between the compare and the exchange, creating a race. With lock, the entire read-modify-write is indivisible.</p><h3>The full instruction here</h3><pre>lock cmpxchg qword [rel data_140020208], rdx</pre><h4>U<strong>npacked:</strong></h4><p>Component Meaning lock Atomically hold the cache line cmpxchg Compare-and-swap qword 64-bit operation [rel data_140020208] RIP-relative address: a global variable in .data/.bss rdx The new value to write if the compare succeeds (implicit) rax The expected current value (loaded earlier)</p><blockquote>So the operation is: <strong>if </strong><strong>*data_140020208 == rax, then store </strong><strong>rdx there atomically.</strong></blockquote><h3>What the full loop is doing</h3><p>Looking at both images together, the HLIL makes it clear. Let me annotate the disassembly against the HLIL (High Level IL in Binary Ninja):</p><pre>; ── Load current value of the global ──────────────────────────<br>140003b50   mov rax, qword [rel data_140020208]   ; rax_2 = *global<br><br>; ── Spin loop top ─────────────────────────────────────────────<br>140003b60   cmp rax, 0xffffffffffffffff           ; if rax_2 == -1 (sentinel)<br>140003b64   je  0x140003bd3                       ;   → call sub_140016790 (noreturn: panic/abort)<br>140003b66   lea rdx, [rax+0x1]                    ; rdx = rax_2 + 1  (desired new value)<br>140003b6a   lock cmpxchg qword [rel data_140020208], rdx<br>            ; attempt: if *global == rax, write rdx, ZF=1<br>            ; else:    rax = *global (reload), ZF=0<br>140003b73   jne 0x140003b60                       ; if ZF=0 (CAS failed), retry<br>; ── CAS succeeded ─────────────────────────────────────────────<br>140003b75   mov qword [rcx], rdx                  ; *(rax_1 + 0x38) = rdx</pre><blockquote>This is a <strong>compare-and-swap spin loop</strong>: a standard lock-free increment.</blockquote><p>In pseudocode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*JOyVtCnt5LHskLX1OazeUA.png" /><figcaption>HIL in Binary Ninja</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*SjxQP9bqoIMGobldXYoN4A.png" /><figcaption>Pseudo C in Binary Ninja</figcaption></figure><pre>loop {<br>    let current = global.load(Relaxed);   // rax<br>    if current == -1 { panic!(); }        // sentinel: poisoned/uninitialized<br>    let next = current + 1;               // rdx<br>    if global.compare_exchange(current, next).is_ok() {<br>        break;<br>    }<br>    // else: another thread changed global, reload rax and retry<br>}</pre><p>The jne after lock cmpxchg is checking the <strong>zero flag</strong>: if ZF=0, the CAS failed (someone else modified the global between our load and our CAS attempt), so we jump back to reload and retry.</p><h3>What this pattern represents in Rust</h3><p>The context gives it away. Look at what happens after the loop succeeds:</p><pre>140003b78   mov qword [rel data_140020200], rdx   ; store thread count / handle<br>140003b88   call AddVectoredExceptionHandler       ; VEH registration<br>140003b8e   mov dword [rbp-0x38], 0x5000          ; StackSizeInBytes = 0x5000<br>140003b99   call SetThreadStackGuarantee<br>140003b9f   call GetCurrentThread<br>140003bac   lea rdx, [rel data_14001907a]         ; u&quot;main&quot;</pre><p>The TLS access at the top (gs:0x58 → ThreadLocalStoragePointer), the CAS on a global counter, followed by AddVectoredExceptionHandler and stack guarantee setup, and the string u&quot;main&quot; — this is the <strong>Rust runtime initialisation sequence</strong>. Specifically this is std::rt::lang_start or its inner worker, which runs once per thread and uses a CAS-protected counter to track initialisation state.</p><p>The specific pattern (global atomically incremented, sentinel value -1 triggers a noreturn) is Rust&#39;s <strong>once-cell / lazy initialisation</strong> pattern, likely std::sync::Once or the internal lang_start_internal synchronisation that ensures the runtime (panic handler, VEH, stack guarantee) is initialised exactly once even under concurrent entry.</p><p>The HLIL renders it cleanly:</p><pre>rax_2 = data_140020208   // load global<br>do {<br>    if (rax_2 == -1) { sub_140016790(); noreturn }  // sentinel check<br>    rdx = rax_2 + 1<br>    if (rax_2 == data_140020208) {                  // CAS success path<br>        data_140020208 = rdx<br>        z_1 = true<br>    } else {<br>        rax_2 = data_140020208                      // CAS failure: reload<br>        z_1 = false<br>    }<br>} while (not z_1)</pre><p>Binary Ninja’s HLIL has correctly identified the lock cmpxchg + jne as a do-while CAS loop and modelled the success/failure branches.</p><h3>Why this is a release build indicator (supporting evidence)</h3><p>A debug build would not have this pattern here in the same way. In a debug build:</p><ul><li>The std::sync::Once or equivalent would appear as an explicit call to the unoptimised Once::call_once function, not as an inlined CAS loop</li><li>The TLS access would go through several more indirection layers with intervening stack spills</li><li>The whole initialisation sequence would be spread across multiple non-inlined call frames</li></ul><p>The fact that the entire CAS loop, VEH registration, stack guarantee, and thread naming is all inlined into a single flat function body is a strong optimisation signal consistent with a release build at opt-level 2 or 3.</p><blockquote>So, where does it come from…?</blockquote><h3>Where lock cmpxchg comes from in your binary</h3><h4>Step 1: mod.rs routes x86_64-pc-windows-msvc to futex.rs</h4><p>The dispatch table in library/std/src/sys/sync/once/mod.rs uses cfg_select!:</p><pre>cfg_select! {<br>    any(<br>        all(target_os = &quot;windows&quot;, not(target_vendor=&quot;win7&quot;)),  // modern Windows<br>        target_os = &quot;linux&quot;,<br>        ...<br>    ) =&gt; {<br>        mod futex;   // x86_64-pc-windows-msvc lands here<br>    }<br>    any(<br>        windows,     // older/fallback Windows<br>        ...<br>    ) =&gt; {<br>        mod queue;<br>    }<br>}</pre><p>x86_64-pc-windows-msvc has target_os = &quot;windows&quot; and target_vendor = &quot;pc&quot;. Since &quot;pc&quot; != &quot;win7&quot;, the condition not(target_vendor=&quot;win7&quot;) is true, so the first arm matches and the binary links against futex.rs.</p><blockquote>Reference: <a href="https://doc.rust-lang.org/src/std/sys/sync/once/mod.rs.html">https://doc.rust-lang.org/src/std/sys/sync/once/mod.rs.html</a></blockquote><h4>Step 2: futex.rs contains compare_exchange_weak, which compiles to lock cmpxchg</h4><p>Inside futex::Once::call(), the slow path for first initialisation:</p><pre>INCOMPLETE | POISONED =&gt; {<br>    // Try to register the current thread as the one running.<br>    let next = RUNNING + if queued { QUEUED } else { 0 };<br>    if let Err(new) = self.state_and_queued.compare_exchange_weak(<br>        state_and_queued,   // expected: current state (INCOMPLETE = 3)<br>        next,               // desired: RUNNING (= 1)<br>        Acquire,<br>        Acquire,<br>    ) {<br>        state_and_queued = new;<br>        continue;           // CAS failed, retry<br>    }<br>    // ... run the initialiser closure<br>}</pre><p>On x86–64, LLVM lowers compare_exchange_weak on an atomic integer with Acquire ordering to lock cmpxchg. The surrounding retry loop (continue) is the spin you see in the disassembly.</p><blockquote>Reference: <a href="https://doc.rust-lang.org/src/std/sys/sync/once/futex.rs.html">https://doc.rust-lang.org/src/std/sys/sync/once/futex.rs.html</a></blockquote><h4>Step 3: the call chain from your source code</h4><p>The source code has println!(&quot;Hi!&quot;) inside Human::say_hello. That expands to a call to std::io::_print, which calls std::io::stdout(). Inside stdout():</p><pre>// library/std/src/io/stdio.rs<br>static STDOUT: OnceLock&lt;ReentrantLock&lt;RefCell&lt;LineWriter&lt;StdoutRaw&gt;&gt;&gt;&gt; = OnceLock::new();<br><br>pub fn stdout() -&gt; Stdout {<br>    Stdout { inner: STDOUT.get_or_init(|| { ... }) }<br>}</pre><p>OnceLock::get_or_init delegates to Once::call_once, which on x86_64-pc-windows-msvc routes to futex::Once::call. On the very first call to println! in the process, the state is INCOMPLETE (= 3), so the INCOMPLETE | POISONED arm fires and executes compare_exchange_weak, producing the lock cmpxchg at 140003b6a.</p><p>Reference: <a href="https://doc.rust-lang.org/src/std/io/stdio.rs.html">https://doc.rust-lang.org/src/std/io/stdio.rs.html</a></p><h4>What the assembly maps to?</h4><pre>; rax = load of Once state (INCOMPLETE = 0)<br>140003b50   mov rax, [rel data_140020208]<br>; cmp rax, -1 = check for POISONED sentinel<br>140003b60   cmp rax, 0xffffffffffffffff<br>140003b64   je  0x140003bd3            ; → panic (poisoned)<br>; rdx = rax + 1 = RUNNING (0 + 1 = 1)<br>140003b66   lea rdx, [rax+0x1]<br>; compare_exchange(INCOMPLETE, RUNNING, SeqCst)<br>140003b6a   lock cmpxchg [rel data_140020208], rdx<br>; if ZF=0 (CAS failed, state changed), retry<br>140003b73   jne 0x140003b60</pre><p>This can be:</p><pre>// queue.rs<br>let old = self.state.compare_and_swap(state, RUNNING, Ordering::SeqCst);<br>if old != state { state = old; continue }</pre><p>The -1 / 0xffffffffffffffff check is the POISONED sentinel (or a waiter-pointer sentinel in the queue.rs encoding; the upper bits of the AtomicUsize encode the waiter linked list head in the RUNNING state, so values larger than COMPLETE that are not a valid pointer trigger the abort path).</p><h3>Summary of lock cmpxchg mechanics</h3><pre>Before:          rax = expected_value<br>                 rdx = new_value<br>                 mem = some_current_value<br><br>Case A (success): mem == rax<br>                 → mem becomes rdx<br>                 → ZF = 1<br>                 → jne not taken: loop exits<br>Case B (failure): mem != rax<br>                 → rax loaded with actual mem value<br>                 → ZF = 0<br>                 → jne taken: loop retries with fresh rax</pre><p>The loop continues retrying until the CAS succeeds, i.e. until no other thread has modified the global between this thread’s load and its attempted store. Under low contention this succeeds on the first or second attempt. Under high contention it spins. This is the foundation of all lock-free data structures on x86.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17fc2bce7da5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/interesting-unusal-instructions-in-rust-binary-lock-cmpxchg-17fc2bce7da5">Interesting instructions in Rust binary: lock cmpxchg</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assembly Breakdown: x86–64 structure alignment examples]]></title>
            <link>https://medium.com/re-exploit/assembly-breakdown-x86-64-structure-alignment-examples-a40a0ef325e5?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/a40a0ef325e5</guid>
            <category><![CDATA[x86-64]]></category>
            <category><![CDATA[msvc]]></category>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[struct-alignment]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Thu, 07 May 2026 22:01:55 GMT</pubDate>
            <atom:updated>2026-05-07T22:01:55.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*qkUqqEpO-YEFn-72oQQf1A.png" /></figure><h3>x64 Structure Alignment in MSVC: What the Compiler Does to Your Structs</h3><p>When you declare a struct in C, the compiler does not simply pack the members back-to-back in memory. It inserts padding bytes to ensure each member sits at an address that is a multiple of its own size. The x64 ABI formalises this as natural alignment: a short must be 2-byte aligned, an int 4-byte aligned, a double or pointer 8-byte aligned. The struct&#39;s total size is then rounded up to a multiple of its largest member&#39;s alignment, so that arrays of structs remain correctly aligned at every element.</p><p>The Microsoft documentation illustrates this with four concrete examples. A struct containing only a short needs no padding at all -- two bytes, done. Add an int followed by a double followed by a short, and the picture changes: four bytes of padding appear between the int and the double to push the double to an 8-byte boundary, and six bytes of trailing padding follow the short to bring the total to 24. A struct with interleaved char, short, char, and int members accumulates internal padding in two places, wasting 4 bytes out of 12. The union example shows the other side of the coin: all members start at offset 0, the total size is simply the largest member, and smaller members leave the high bytes unused.</p><p>Two practical points follow from this.</p><ul><li>First, member ordering is not neutral. Declaring fields largest-to-smallest eliminates most internal padding; the interleaved-type example shrinks from 12 bytes to 8 if reordered.</li><li>Second, Rust’s default #[repr(Rust)] layout allows the compiler to reorder fields freely to minimise padding, so a Rust struct in a binary will not necessarily match the source declaration order. Only #[repr(C)] guarantees the C-compatible layout described above, which matters when reconstructing types during reverse engineering.</li></ul><p>The four examples demonstrate the two core alignment rules: each member sits at an offset that is a multiple of its own size, and the total struct size is padded to a multiple of the struct’s alignment (which equals the largest member’s alignment).</p><p>Let’s review the examples from Microdoft Doc.</p><blockquote>Part one is based on Microsoft Doc. Check it out: <a href="https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions?view=msvc-170">https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions?view=msvc-170</a></blockquote><h3>Example 1: trivial, no padding</h3><pre>_declspec(align(2)) struct {<br>    short a;      // +0; size = 2 bytes<br>}<br>// Total: 2 bytes, alignment: 2 bytes</pre><p>short requires 2-byte alignment. Placed at offset 0, which satisfies that. Total size 2 is already a multiple of 2. No padding needed anywhere.</p><h3>Example 2 : internal and trailing padding</h3><pre>_declspec(align(8)) struct {<br>    int    a;     // +0;  size = 4 bytes<br>    double b;     // +8;  size = 8 bytes<br>    short  c;     // +16; size = 2 bytes<br>}<br>// Total: 24 bytes, alignment: 8 bytes</pre><p>a is an int (4 bytes, 4-byte aligned) — placed at offset 0, no issue. b is a double (8 bytes, <strong>8-byte aligned</strong>) — the next available offset after a is 4, which is not a multiple of 8, so 4 bytes of padding are inserted at offsets 4–7 to push b to offset 8. c is a short (2 bytes, 2-byte aligned) — placed at offset 16, aligned correctly. That leaves offsets 18–23 as trailing padding: the struct&#39;s alignment is 8 (driven by double b), so total size must be a multiple of 8. 18 rounded up to the next multiple of 8 = 24. Six bytes of trailing padding are added.</p><p>The trailing padding matters when the struct is used in an array: arr[1] must also start at an 8-byte boundary, which requires each element to be 24 bytes.</p><h3>Example 3: interleaved padding from mixed types</h3><pre>_declspec(align(4)) struct {<br>    char  a;      // +0;  size = 1 byte<br>    short b;      // +2;  size = 2 bytes<br>    char  c;      // +4;  size = 1 byte<br>    int   d;      // +8;  size = 4 bytes<br>}<br>// Total: 12 bytes, alignment: 4 bytes</pre><pre>Offset │ 0    1    2    3<br>───────┼────────────────────<br>       │  a   [p]   b    b<br><br>Offset │ 4    5    6    7<br>───────┼────────────────────<br>       │  c   [p]  [p]  [p]<br>Offset │ 8    9   10   11<br>───────┼────────────────────<br>       │  d    d    d    d</pre><ul><li>a is a char at offset 0 : 1-byte aligned, no padding needed.</li><li>b is a short : requires 2-byte alignment; offset 1 is odd, so 1 byte of padding inserted before b, placing it at offset 2.</li><li>c is a char at offset 4 .</li><li>d is an int : requires 4-byte alignment; the next offset after c is 5, which is not a multiple of 4, so 3 bytes of padding inserted before d, placing it at offset 8.</li><li>Total size is 12, which is a multiple of 4 (the struct&#39;s alignment). No trailing padding needed.</li></ul><p>This example illustrates why member ordering matters: reordering to {int d; short b; char a; char c;} would produce a 8-byte struct with no internal padding at all.</p><h3>Example 4: union, all members at offset 0</h3><pre>_declspec(align(8)) union {<br>    char *p;      // +0; size = 8 bytes<br>    short  s;     // +0; size = 2 bytes<br>    long   l;     // +0; size = 4 bytes<br>}<br>// Total: 8 bytes, alignment: 8 bytes</pre><pre>Offset │ 0    1    2    3    4    5    6    7<br>───────┼────────────────────────────────────<br>  p    │  p    p    p    p    p    p    p    p   (all 8 bytes)<br>  s    │  s    s   [p]  [p]  [p]  [p]  [p]  [p] (2 bytes + 6 padding)<br>  l    │  l    l    l    l   [p]  [p]  [p]  [p] (4 bytes + 4 padding)</pre><p>All union members share offset 0 — that is the defining property of a union. The total size is determined by the largest member (char* = 8 bytes on x64), and the alignment is determined by the largest alignment requirement, also 8 (char* is a pointer = quadword). s and l occupy only the low bytes of the 8-byte slot; the remainder is unused padding within the union&#39;s footprint.</p><h3>RE Relevance</h3><p>Struct layout rules are directly relevant to binary analysis of Rust code. Rust’s compiler (via LLVM) applies the same natural alignment rules by default for #[repr(C)] types. For #[repr(Rust)] types, the compiler is free to reorder fields to minimise padding — which means a Rust struct in a malware sample will not necessarily have the same field ordering as the declared source, complicating type reconstruction in Binary Ninja or IDA. Recognising padding bytes versus data bytes is essential when recovering struct layouts from MLIL/HLIL.</p><blockquote>Microsoft Corporation (2023) x64 ABI conventions. Microsoft Learn. Available at: <a href="https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions">https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40a0ef325e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/assembly-breakdown-x86-64-structure-alignment-examples-a40a0ef325e5">Assembly Breakdown: x86–64 structure alignment examples</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reversing Akira’s Rust Experiment: A Breakdown Part 1]]></title>
            <link>https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-1-937e0388d2c7?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/937e0388d2c7</guid>
            <category><![CDATA[elf-analysis]]></category>
            <category><![CDATA[ransomware]]></category>
            <category><![CDATA[rust-malware]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Wed, 06 May 2026 21:58:35 GMT</pubDate>
            <atom:updated>2026-06-25T22:01:34.021Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This post is a breakdown and commentary on <strong>Ben Herzog’s Check Point Research </strong>(December 2024), <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Inside Akira Ransomware’s Rust Experiment</a> &amp; <a href="https://www.virusbulletin.com/conference/vb2025/abstracts/inside-akira-ransomwares-rust-experiment/">his talk in 2025</a>. All technical claims are grounded in the linked primary sources below. Combined with <strong>Cindy Xiao</strong>’s amazing reports/talks in <a href="https://github.com/cxiao/rust-reversing-workshop-recon-2024">2024</a>, <a href="https://github.com/cxiao/reconstructing-rust-types-talk-re-verse-2025">2025</a> (about reconstructing types and more).</blockquote><blockquote>The technique of recovering the rustc compiler version from embedded<br>/rustc/&lt;commit&gt;/strings and recovering third-party crates from<br>registry/src/index.crates.io-…/&lt;crate&gt;-&lt;ver&gt;/ panic paths was<br>independently developed by Juan Andrés Guerrero-Saade and Nicole Fishbein<br>in their Proj-0xA11c toolset, presented at Recon 2024:<br><a href="https://github.com/juanandresgs/Proj-0xA11c">https://github.com/juanandresgs/Proj-0xA11c</a></blockquote><p>There will be a part 2 to break down the rest. I separate them so this article won’t be <strong><em>__too_long_</em>_</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpO6uNZPlZqZuD7mlYDsqg.png" /></figure><p>For this analysis, Binary Ninja (v5.3.9434) is used without enabling any plugins. <strong>Binary:</strong> akirav2.elf , SHA25:60ee1d284ed663073872012c7bde7fac5ca1121403f1a5d2d5411317df282796c.</p><h4><strong>A note on source references</strong></h4><blockquote>The commit hash is updated on 10th Jun 2026. <strong><em>79e9716c…</em> is rustc 1.74.0 stable</strong> (released 2023-11-16). Akirav2’s <em>.rodata</em> contains std panic-path strings of the form <em>/rustc/&lt;commit&gt;/library/...</em>.<strong><em>db034cee…</em> is a </strong><strong><em>master</em>/nightly commit from ~1 year later, </strong>which I was mistakenly pinned in the article. If you see any links related to <strong><em>db034cee… , </em></strong><em>please consider it was based on previosu wrong assumption but it works to some degree.</em></blockquote><p>The Rust standard library is under active development and files move between releases. Source links in this post are pinned to commit 79e9716c980570bfd1f666e3b16ac583f0168962 — <a href="https://releases.rs/docs/1.74.0/"><strong>rustc 1.74.0 stable</strong></a>, the toolchain that compiled this Akira v2 binary. This is recoverable directly from the binary: its .rodata embeds /rustc/79e9716c…/library/... panic paths, and it is corroborated by version-pinned FunctionID analysis resolving the sample to 1.74.0.</p><p>This matters because stdlib code is inlined directly into the final binary at compile time: what you see in the disassembly reflects the stdlib at that specific commit, not the current main branch. Following a newer version of the same file risks misidentifying inlined boilerplate or drawing incorrect conclusions about what the malware authors wrote versus what the compiler contributed.</p><blockquote>If a pinned link returns a 404, the file has likely been relocated. Navigate to the <a href="https://github.com/rust-lang/rust/tree/db034cee00570a9b82ea8b9e9e95221dbd745698">repository root</a> and search by filename.</blockquote><h3>Table of Contents</h3><ul><li>Background</li><li>Summary for Part 1</li><li>VM Setup for malware analysis</li><li>Binja plugins for Rust binary</li><li>Is this a Rust binary?</li><li>(Updated) It’s a release build</li><li>.rodata strings are extraordinarily revealing</li><li>The Control Flow Map</li><li>Section 1: How args().collect() Works</li><li>Further Reading</li><li>References</li></ul><h3>Background</h3><p>In early 2024, Akira ransomware-as-a-service operators circulated a new variant, internally called “Akira v2”, written in Rust and aimed specifically at ESXi bare-metal hypervisor servers. Cisco Talos first documented the variant in their <a href="https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/">ongoing Akira evolution tracking</a>.</p><p><a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Check Point Research</a> published a detailed assembly-level analysis in December 2024. Unlike most ransomware reports that answer only targeted questions (“what encryption is used?”, “what extensions are targeted?”).</p><p><a href="https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/">Talos</a> documented Akira v2 from a March 2024 incident response engagement, where they observed the Rust ESXi variant deployed alongside a Windows encryptor called Megazord. The v2 sample they analysed is version 2024.1.30 and uses rust-crypto 0.2.36 for encryption, replacing the Crypto++ library used in the original C++ variant. Here rust-crypto supplies the SOSEMANUK symmetric stream cipher (not ChaCha20 or AES); the asymmetric key wrapping is X25519 via curve25519-dalek 4.1.1. See the Part 3 correction note for the full pipeline.</p><h3>Summary for Part 1</h3><blockquote>Because this article and following ones in the series will be __fairly_long__, so I put the summary before the in-depth breakdown.</blockquote><h3>Layer 1: Crate/Dependency Recovery via .rodata Panic Strings</h3><p>Every entry here was recovered purely from static string analysis, no execution, no DWARF.</p><p><strong>Recovery mechanism:</strong> Cargo embeds full filesystem paths into panic messages at compile time. Format is always:</p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/&lt;crate-name&gt;-&lt;version&gt;/src/&lt;file&gt;.rs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*UdVG7sq2F9h5yrIGe6VDTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRj1AI4emFbc-g4BrmxYPw.png" /></figure><blockquote>In conclusion, Indicatif version is <a href="https://github.com/console-rs/indicatif/tree/0c037edc86449d84aa457d7d5db80b4166c18d6b">0.17.7</a>.</blockquote><blockquote><strong>Updated 17 May 2026: </strong>I’m still writing the analysis part 2 at the moment, <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">Indicatif</a> version has actually found but I was drown in the piles of strings, so accidentally ignored it.</blockquote><p><strong>Internal workspace crates</strong> (not on crates.io, custom):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*Bud2_D_hDUoWC_C2ybW5SQ.png" /></figure><p>Developer platform also recoverable: WSL on Windows, username user, consistent registry hash 6f17d22bba15001f across all paths confirming single build environment.</p><p><strong>Struct names leaked via aho-corasick SIMD backends</strong> (panic strings referencing internal type names):</p><ul><li>SlimSSSE3 : 128-bit SSSE3 Teddy searcher</li><li>SlimAVX2: slim 256-bit AVX2 variant</li><li>FatAVX2 : fat 256-bit AVX2 Teddy searcher</li></ul><p>These tell you the SIMD capability branch taken at runtime even without executing.</p><h3>Layer 2: Internal Module Map (recovered from panic strings + format literals)</h3><pre>akiranew/<br>├── src/<br>│   ├── main.rs        — CLI parsing, fork/stopvm, interactive prompt<br>│   ├── lock.rs        — encryption logic (akira_v2::lock namespace confirmed)<br>│   ├── path_finder.rs — filesystem enumeration (akira_v2::path_finder confirmed)<br>│   └── prng.rs        — custom PRNG<br>└── Cargo.toml<br>    (workspace member: akira_utils)</pre><p>Top-level call chain confirmed: main → default_action → lock → lock_closure</p><h3>Layer 3: Type Layout Recovery via args().collect() Unwrapping Chain</h3><p>This is another type-unwrapping chain showing how a single source call maps to assembly. The document traces five layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Ybrm7qhCZwlPEQaIXFnbXQ.png" /></figure><p><strong>IntoIter&lt;OsString&gt; concrete layout on x64 Linux (32 bytes):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*fPcNlrK7lBCOSClAIthHyg.png" /></figure><p>phantom (PhantomData) and alloc (Global) are ZSTs: zero bytes in binary.</p><p><strong>OsString on Linux (24 bytes, stride value for heap iteration):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*v7ZRS17K25uwIEonNTRq7g.png" /></figure><p><strong>RE implication directly stated in document:</strong> the confusing pointer arithmetic in the binary is stride-8 (reading argv[]) then stride-24 (OsString iteration). Knowing those two values makes the assembly readable.</p><p><strong>Linux vs Windows </strong><strong>OsString stride difference</strong> (relevant if you ever need cross-platform comparison in the paper):</p><ul><li>Linux: OsString = Vec&lt;u8&gt; internally = 24 bytes</li><li>Windows: OsString = Wtf8Buf = 32 bytes (ptr, len, cap, is_known_utf8 bool padded to 8 bytes)</li></ul><h3>What‘s still uncertain for Part 1</h3><ul><li>rust-crypto 0.2.36 comes from the Talos report reference, not from .rodata recovery in this document.</li><li><a href="https://github.com/console-rs/indicatif/tree/0c037edc86449d84aa457d7d5db80b4166c18d6b">indicatif</a> version is not discovered (in Part 1), only confirmed by format strings, not a panic path.</li><li>Source links in this post are pinned to commit 79e9716c980570bfd1f666e3b16ac583f0168962 — <strong>rustc 1.74.0 stable</strong>, the toolchain that compiled this Akira v2 binary. This is recoverable directly from the binary: its .rodata embeds /rustc/79e9716c…/library/... panic paths, and it is corroborated by version-pinned FunctionID analysis resolving the sample to 1.74.0 <strong>(<em>Updated on 10th Jun 2026</em>)</strong>.</li><li>unicode-width version is unconfirmed (the path is truncated to unicode-wi...</li></ul><p>There will be more to be discovered in Part 2…</p><h3>VM setup for malware analysis</h3><p>To ensure this is an <strong>air-gapped VM </strong>(Windows 10)</p><h4>Step 1: VM network adapter (most important)</h4><p>In whatever hypervisor you are using:</p><p><strong>VMware Workstation/Player:</strong></p><ul><li>VM Settings &gt; Network Adapter &gt; set to <strong>“Host-only”</strong> first, then ideally <strong>“No network connection”</strong> (disconnect entirely)</li><li>Tick <strong>“Connected”</strong> checkbox OFF</li></ul><p><strong>VirtualBox:</strong></p><ul><li>Settings &gt; Network &gt; Adapter 1 &gt; untick <strong>“Enable Network Adapter”</strong> entirely</li><li>Do this for all adapters (check Adapter 2, 3, 4 tabs too)</li></ul><p><strong>Hyper-V:</strong></p><ul><li>VM Settings &gt; Network Adapter &gt; set to <strong>“Not Connected”</strong></li></ul><h4>Step 2: Disable network inside the guest OS</h4><p>Even with the adapter disconnected at hypervisor level, do this inside the VM as defence in depth:</p><pre># In PowerShell as Administrator<br>Disable-NetAdapter -Name &quot;*&quot; -Confirm:$false</pre><p>Or via GUI: Device Manager &gt; Network Adapters &gt; right-click each &gt; Disable.</p><h4>Step 3: Shared folders and clipboard</h4><p>These are your biggest risk vectors for accidental data movement:</p><p><strong>VMware:</strong> VM Settings &gt; Options &gt; Shared Folders &gt; <strong>Disabled</strong>; Guest Isolation &gt; untick both clipboard and drag-and-drop</p><p><strong>VirtualBox:</strong> Devices &gt; Shared Folders &gt; remove all; Devices &gt; Shared Clipboard &gt; <strong>Disabled</strong>; Devices &gt; Drag and Drop &gt; <strong>Disabled</strong></p><h4>Step 4: Snapshot before touching the sample</h4><p>Take a clean snapshot <strong>now</strong>, before the sample is on the VM, labelled something like clean-pre-analysis. This is your recovery point if anything goes wrong.</p><pre># VMware CLI alternative<br>vmrun snapshot &quot;path/to/vm.vmx&quot; &quot;clean-pre-analysis&quot;</pre><h4>Step 5: Transfer the sample safely</h4><p>Since shared folders should be off, transfer via:</p><ul><li><strong>ISO mounting:</strong> package the sample into an ISO on the host, mount it read-only in the VM. The sample cannot write back through a mounted ISO.</li><li>Password-protected zip (password: infected is the malware research convention) mounted or copied in, then extracted inside the VM only.</li></ul><blockquote>Do <strong>not</strong> re-enable shared folders or clipboard to transfer the file.</blockquote><h4>Step 6: Strip execute permissions immediately on arrival</h4><p>Once inside the VM, in PowerShell:</p><pre># Confirm it is an ELF, not a PE - it should not execute on Windows anyway<br># but strip any accidental execute association<br>$file = &quot;akira_sample&quot;<br># Rename with a safe extension to prevent accidental double-click<br>Rename-Item $file &quot;$file.bin&quot;</pre><p>Renaming to .bin prevents Windows from accidentally associating it with anything executable.</p><h4>Verify your air-gap</h4><p>Inside the VM after setup:</p><pre># Should show no active connections<br>Get-NetAdapter | Select Name, Status<br>ping 8.8.8.8  # Should time out with no response</pre><p>If ping times out and adapters show as Disabled or Disconnected, you are properly isolated.</p><blockquote>For the analysis involving debuggers/execution like dynamic analysis, you can also install <a href="https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;opi=89978449&amp;url=https://blog.christophetd.fr/malware-analysis-lab-with-virtualbox-inetsim-and-burp/">inetSim</a>. It’s recommended to check the book <a href="https://www.oreilly.com/library/view/practical-malware-analysis/9781593272906/ch04s08.html">Practical Malware Analysis</a>.</blockquote><h4>Find the sample</h4><p>It’s encouraged to check out <a href="https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/">the CISCO Talos threat report</a> and discover the details and the hashes.</p><h3>Binja plugins for Rust binary &amp; Some useful links</h3><p>According to Cindy Xiao’s talk/report in <a href="https://github.com/cxiao/rust-reversing-workshop-recon-2024">2024</a>, when you discover some clues of Rust types, considering the links:</p><ul><li><a href="https://cheats.rs/#owned-strings">https://cheats.rs/#owned-strings</a></li><li><a href="https://doc.rust-lang.org/std/primitive.str.html">https://doc.rust-lang.org/std/primitive.str.html</a></li></ul><p>I would certainly recommend readers to enable those plugins before the binary analysis/REing (I didn’t enable them this time, and you can still work through it manually).</p><ul><li><a href="https://github.com/cxiao/rust_string_slicer"><strong>Rust String Slicer (by Cindy Xiao)</strong></a></li><li><a href="https://github.com/inspier/BinjaRustDemangler"><strong>Rust Demangler (by inspier)</strong></a></li><li><a href="https://github.com/cxiao/rust_type_layout_helper_bn"><strong>Rust Type Layout Helper (by Cindy Xiao)</strong></a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLcT05wTCTCiU3gYMAA_fg.png" /></figure><p><strong>rust_string_slicer: the string problem</strong></p><p>The core issue it solves is that Rust strings are not null-terminated. A &amp;str is a fat pointer: a (pointer, length) pair. Binary Ninja&#39;s default string scanner looks for null terminators, so it systematically misses Rust string literals or truncates them at the first zero byte in the data. This means your strings view in a naive analysis of Akira v2 will be incomplete or misleading.</p><p>The plugin runs two heuristics:</p><p><em>Recover from readonly data</em>: it scans .rodata for cross-referenced addresses and checks whether the cross-reference site has the pattern QWORD ptr_to_string_data followed immediately by QWORD length. This recovers string slice structs laid out statically in read-only data, which is where Rust places string literals used in static contexts.</p><p><em>Recover from code</em>: it follows cross-references into code sections and looks for the idiom:</p><pre>lea rax, &lt;string_data_addr&gt;<br>mov [rsp+var.ptr], rax<br>mov [rsp+var.len], &lt;immediate_length&gt;</pre><p>The immediate value after the lea is the length the plugin extracts. This catches strings constructed on the stack at runtime, which the data-section heuristic cannot see.</p><p>Once recovered, the plugin defines a &amp;str type in Binary Ninja&#39;s type system with fields char* address and int64_t length, then annotates every recovered instance. The practical payoff is that you get cross-references to the &amp;str type, which means you can enumerate all recovered string literals and their usage sites in one pass. For Akira v2, this would surface file extension lists, ransom note content, C2 strings, and any additional developer path leaks that the naive string scanner missed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peF0pwa8mTvE0N2IQa91rA.png" /></figure><p><strong>Rust symbol mangling:</strong><a href="https://doc.rust-lang.org/rustc/symbol-mangling/v0.html"><strong> v0 scheme</strong></a></p><p>Rust has had two mangling schemes.<a href="https://blog.rust-lang.org/2025/11/20/switching-to-v0-mangling-on-nightly/"> The legacy scheme</a> was borrowed loosely from C++ Itanium ABI and was never formally specified. The <a href="https://doc.rust-lang.org/rustc/symbol-mangling/v0.html">v0 scheme</a> was stabilised in Rust 1.37 (2019) and is now the default. It is designed to be unambiguous, fully encode Rust’s type system, and be demangleable without compiler knowledge.</p><p>Every v0 symbol begins with the prefix _R. After that, the symbol encodes a path followed optionally by a generic argument list and a disambiguator. The grammar is roughly:</p><pre>_R &lt;path&gt; [&lt;generic-args&gt;] [&lt;instantiating-crate&gt;]</pre><p>A concrete example:</p><pre>_RNvCs6XXXXXXX_5akira8compress</pre><p>Breaking this down:</p><ul><li>_R — v0 prefix</li><li>N — indicates a nested path follows</li><li>v — item type: function (v = value namespace)</li><li>Cs6XXXXXXX_ — crate disambiguator (a hash derived from crate metadata, ensuring uniqueness across crates with the same name)</li><li>5akira — crate name, length-prefixed (5 characters: akira)</li><li>8compress — function name, length-prefixed (8 characters: compress)</li></ul><p>For a method on a type, the path nests further:</p><pre>_RNvNtCs..._5akira9Encryptor8run_pass</pre><p>Where Nt indicates a type namespace and the path encodes akira::Encryptor::run_pass.</p><p><strong>Generic instantiations</strong></p><p>Monomorphised generics encode their type arguments inline. For example, a function fn process&lt;T&gt; instantiated with u64 encodes the concrete type in the symbol. This means every monomorphisation of a generic function has a distinct, demangleable symbol that tells you exactly what type it was instantiated with. In a non-stripped binary this is extremely informative for RE. In a stripped binary the symbols are gone, but if any survive (e.g. in a partially stripped binary or in exported symbols), the type information is recoverable directly from the name.</p><p><strong>Crate disambiguator</strong></p><p>The hash component (Cs6XXXXXXX_) is derived from the crate&#39;s metadata hash at compile time. This means two builds of the same crate with different dependencies or compiler flags will produce different disambiguators. It is not useful for version fingerprinting directly, but it does mean you can cluster functions by crate of origin even in a mixed binary, since all functions from the same crate share the same disambiguator hash.</p><p><strong>Why enabling the Rust demangler in Binary Ninja matters</strong></p><p>Without demangling, every Rust symbol in the function list appears as raw _RNvCs... garbage. With demangling enabled, Binary Ninja resolves these to human-readable akira::Encryptor::run_pass style names, which gives you several concrete advantages in your workflow:</p><ul><li><strong>Crate boundary recovery</strong>: the demangled name includes the crate component, so you can immediately see which functions belong to akira, which belong to akira_utils, and which belong to std or third-party dependencies. This is directly relevant to your akira_utils finding: if any symbols survived stripping, demangling would confirm the crate attribution rather than requiring you to infer it from panic strings alone.</li><li><strong>Type information from generics</strong>: monomorphised function names encode their concrete type arguments. alloc::vec::Vec&lt;u8&gt;::push tells you the vector element type. This is information you would otherwise have to recover through data flow analysis.</li><li><strong>Call graph legibility</strong>: Binary Ninja’s call graph and cross-reference views become significantly more readable. Instead of a graph of hashes, you see a graph of akira::encrypt::* functions calling into akira_utils::*, which immediately surfaces the module structure the developer intended.</li></ul><p><strong>Caveat for stripped binaries</strong></p><p>For a fully stripped release build like Akira v2, most symbols are gone and the demangler has nothing to work with for internal functions. However it still applies to: any exported symbols (ELF binaries sometimes retain a small export table), any symbols recovered by Binary Ninja’s analysis heuristics, and any strings in .rodata that happen to contain mangled names (uncommon but not impossible). The demangler costs nothing to enable and pays off immediately if any symbols surface during analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eb3eOQ-cuEnw0NZVQWzY1g.png" /></figure><p><strong>rust_type_layout_helper_bn: the type layout problem</strong></p><p>This addresses a different but equally serious problem. Rust’s type system allows the compiler to reorder struct fields for optimal alignment, and enum discriminants use niche optimisation (for example, Option&lt;Box&lt;T&gt;&gt; has no discriminant byte because a null pointer represents None). You cannot safely assume a struct&#39;s field order in the binary matches its source order. Without knowing the actual layout, every memory access in HLIL is ambiguous.</p><p>The plugin works by ingesting the output of rustc&#39;s -Zprint-type-sizes flag, which emits the exact field offsets, sizes, alignment padding, and enum variant layouts for every type in a compilation. The plugin parses that output and imports it directly into Binary Ninja&#39;s type library as proper struct and enum definitions, including padding bytes, packed variants, and discriminant fields.</p><p>The workflow requires you to compile a version of the target code (or a close proxy) with -Zprint-type-sizes on a nightly toolchain and redirect the output to a file, then load that file via the plugin. For malware analysis where you do not have source, you would compile the closest available open-source equivalent, or reconstruct a proxy crate that uses the same dependencies at the same versions, then import the resulting type layout.</p><p>The caveat the author flags is that layout is <strong>not stable</strong> across compilations: different compiler versions, different optimisation flags, or different target platforms can change field ordering and padding. So the imported types are a strong approximation, not a guarantee. For Akira v2, given that you have aho-corasick 1.1.2 and can narrow the rustc version window via the .rustc section, you could construct a fairly tight proxy.</p><h3>Is this a Rust binary?</h3><p>Rust binaries have a distinctive fingerprint across multiple analysis layers. The confidence of identification increases as more signals converge.</p><p><strong>Panic infrastructure</strong> is the strongest single indicator. Every Rust binary compiled with std embeds panic handling machinery. Look for strings matching src/ paths with .rs extensions, often referencing crate names or Rust standard library internals. The string called Option::unwrap() on a None value or similar is essentially a Rust signature. Akira v2&#39;s TODO: panic message you found is directly in this family.</p><p><strong>Crate name recovery from panic strings</strong> is your second tier. The panic formatting system preserves file paths at compile time. You can recover internal crate names, sometimes even dependency crate names (you found aho-corasick 1.1.2 this way), and frequently leaked workspace paths such as the WSL dev path in your Akira sample.</p><p><strong>Symbol and section naming</strong> gives structural confirmation. Even in stripped release builds, section names like .rustc, __rustc_debug_gdb_scripts_section__ (on ELF), or the presence of Rust-specific metadata embedded in the binary give it away. On Windows PE, look for .rdata strings referencing core::panicking or alloc::.</p><p><strong>Monomorphisation artefacts</strong> are visible in the function count. Rust generics are monomorphised at compile time, so a Rust binary typically has an unusually large number of small, similar functions relative to its feature surface. This is measurable in Binary Ninja by comparing function count to code size.</p><p><strong>Trait vtable layout</strong> is distinguishable from C++ vtables. Rust vtable entries for a trait object are: size, alignment, destructor pointer, then method pointers in trait-definition order. No RTTI string, no virtual inheritance complexity. C++ vtables typically have a RTTI pointer at offset -8.</p><p><strong>Standard allocator fingerprint</strong>: Rust’s default global allocator calls through __rust_alloc, __rust_dealloc, __rust_realloc. These names survive in the import table or as internal symbols even after stripping.</p><p><strong>Absence of C++ indicators</strong> is a useful negative signal: no _ZN Itanium mangled names, no type_info strings, no exception handling personality routine (__gxx_personality_v0).</p><h3>(Updated 10 Jun 2026) It’s A Release Build</h3><blockquote>The std-DWARF leak is <strong>conditional on linking the backtrace machinery</strong>, which substantial std use pulls in.</blockquote><p><strong>Akirav2 is an optimised Release build: </strong><strong>debug = 0, overflow-checks OFF.</strong> The .debug_* sections present are <strong>leaked precompiled-</strong><strong>libstd DWARF</strong>; the attacker&#39;s own code and its application dependencies carry <strong>no DWARF</strong>. &quot;Debug&quot; is true only colloquially (DWARF sections exist); the consequential point stands, there is no user-code debug information.</p><pre>AK=$(ls ~/samples_elf_v2/Akira_v2_0ee1d284*4625664 | grep -v STRIPPED | head -1)<br>readelf -S &quot;$AK&quot; | grep -iE &#39;\.debug&#39;                 # are .debug_* sections present?<br>objdump --dwarf=info &quot;$AK&quot; 2&gt;/dev/null | grep -ic &#39;akira&#39;   # does DWARF name attacker code?<br>objdump --dwarf=info &quot;$AK&quot; 2&gt;/dev/null | grep -i &#39;DW_AT_name&#39; | grep -iE &#39;lock|encrypt|prng&#39; | head  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*OSOFfCvIjzChIWoeogP64g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzjoFFU6yXCAFTDPgtC_zg.png" /><figcaption>Triage summary in Binary Ninja</figcaption></figure><p><strong>No </strong><strong>.debug_* sections anywhere in the list of Binary Ninja though.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*jYOVqLNlGE-rL4XZkdVIAQ.png" /></figure><ul><li>.eh_frame and .eh_frame_hdr: these are unwind tables for exception handling, present in both debug and release Rust builds, but they are not DWARF debug info</li><li>.gcc_except_table: exception handling landing pads, again not debug info</li><li>.rodata (0x438540-0x49700b): this is large at ~370KB, which is where all the Rust panic strings, format strings, and string literals live. This is your goldmine for understanding program behaviour without symbols.</li><li>.text (0x4c8030-0x5e529c): code segment, approximately 1.2MB of actual executable code</li><li>.dynsym and .dynstr: dynamic symbol table, minimal since most code is statically linked</li></ul><blockquote>Though to be honest, it’s not 100% confirming this is a release build, especially &gt; Rust 1.77 release, the way Rust binary stored debug info changed.</blockquote><p>To be more confident, you might want to investigate</p><h3>.rodata strings are extraordinarily revealing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7ZxoMyphnvBD9eLs6CO5g.png" /><figcaption>Summary info graph of sections for this analysis</figcaption></figure><blockquote>In addition to the infograph above, it’s not 100% confirmed when the .debugxxx sections are absent.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gYhRIgRy2dyiJbpCjaViA.png" /><figcaption>Search result of `panic` in the string panel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ns8zbeyXeyL7s-_IxDERPQ.png" /><figcaption>Some interesting strings found in the section of `.rodata`</figcaption></figure><p>Looking at the strings section and it contains multiple critical findings:</p><p><strong>ESXi targeting confirmed:</strong></p><pre>/vmfs/volumes<br>vim-cmd vmsvc/getallvms | tail -n +2 | awk &#39;{system(&quot;vim-cmd vmsvc/power.off &quot; $1)}&#39;</pre><p>This is the exact shell command to enumerate and power off all VMs on an ESXi host, confirming the Check Point analysis.</p><blockquote><strong>ESXi</strong> is VMware’s bare-metal hypervisor. It runs directly on server hardware (no host OS underneath) and hosts multiple virtual machines. In enterprise environments it is extremely common: one physical server running ESXi might host dozens of VMs for databases, domain controllers, file servers, etc.</blockquote><h4>Why ransomware authors love targeting it?</h4><ul><li><strong>One infection, massive blast radius.</strong> Encrypt the ESXi host and every VM it manages goes down simultaneously, rather than having to compromise each machine individually.</li><li><strong>Often poorly monitored.</strong> EDR agents are rarely deployed on hypervisor hosts the way they are on Windows endpoints.</li><li><strong>Critical infrastructure.</strong> Organisations are under extreme pressure to pay because their entire virtualised environment is offline.</li><li><strong>NFS/VMFS datastores.</strong> VM disk images (.vmdk files) live on shared storage volumes that ESXi mounts directly, so the ransomware can enumerate and encrypt them efficiently without touching individual guest OSes.</li></ul><p>The --path /vmfs/volumes default you saw in the <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">Check Point article </a>is the standard ESXi datastore mount point. That single directory contains the disk images for every hosted VM.</p><p><strong>CLI argument strings:</strong></p><pre>akiranew/src/main.rs<br>Valid values for --logs: trace, debug, error, info, warn<br>Root path: Starting path: /vmfs/volumes<br>Exclude expression: Wrong regexp provided: No exclude expression</pre><p>This reveals the seahorse CLI parser argument names directly from the source path embedded in panic strings.</p><p><strong>Build ID string:</strong></p><pre>Build ID not provided.</pre><p><strong>Build ID detail useful for the analysis:</strong> The build ID for v2 (version 2024.1.30) is located at offset 0x41970 for 10 bytes. The ransomware requires either the /vmfs/volumes/ path to exist or a path to be explicitly specified, otherwise it will fail to execute entirely. This matches what Talos documented about the build ID check.</p><p><strong>Crate paths leaking source structure:</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aho-corasick-1.1.2/src/automaton.rs</pre><p>This is extraordinarily useful. It reveals:</p><ul><li>The developer compiled on <strong>WSL</strong> (/mnt/c/Users/user/) on a Windows host</li><li>The exact crate version: aho-corasick-1.1.2</li><li>The Cargo registry path, confirming this is a standard Cargo build</li></ul><p><strong>TODO comment leaked into binary (</strong>0x4419ce)<strong>:</strong></p><pre>char const data_4419ce[0xb2] = &quot;Continuing execution in parent process, new child has pid: New child processshFailed to stop vms: TODO: panic messageFork stopvm failed&quot;</pre><p>The string TODO: panic message appears embedded within a stopvm error handling path in .rodata, suggesting the VM shutdown error branch uses a todo!() macro or placeholder panic rather than a proper error message, indicating incomplete error handling in that specific code path.</p><p>The full string at 0x4419ce is:</p><pre>Continuing execution in parent process, new child has pid: <br>New child processsh<br>Failed to stop vms: TODO: panic message<br>Fork stopvm failed</pre><p>These are <strong>not</strong> separate panic messages concatenated by the Rust runtime. They are <strong>multiple </strong><strong>&amp;str literals that LLVM merged into a single </strong><strong>.rodata entry</strong> at compile time. Here is why.</p><h4>How Rust panic strings reach .rodata</h4><p>Every panic!(), eprintln!(), or string literal in Rust source becomes a &amp;&#39;static str pointing into .rodata. The Rust compiler lowers panic!(&quot;some message&quot;) roughly to:</p><pre>core::panicking::panic_fmt(format_args!(&quot;some message&quot;))</pre><p>The format_args! macro constructs a fmt::Arguments struct at compile time. For simple string literals with no format arguments, LLVM sees these as adjacent static string data and, during its <strong>string merging</strong> optimisation pass (-O2/-O3), physically concatenates adjacent string literals that share no null terminator dependency into a single .rodata blob. The individual strings are then referenced by pointer and length pairs into offsets within that blob.</p><h4>What you are seeing at 0x4419ce</h4><p>Binja is showing you a single 178-byte (0xb2) merged blob containing what were originally <strong>four separate string literals</strong> in the source:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*9J5DxOTW8VvWC1wpy2jdZg.png" /></figure><h4>Why LLVM merges them</h4><p>With --release and LTO enabled, LLVM&#39;s MergeGlobals and ConstantMerge passes fold adjacent read-only string data into contiguous blobs. Binja then displays the entire blob as one char const array from the start address to the end of the last string in the merged region. The individual strings are still referenced separately in the code via (ptr, len) fat pointer pairs pointing into offsets within the blob.</p><h4>Verifying this in Binja</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*gtJiXwH-FgjBKztS3dbYtg.png" /><figcaption>Cross Ref of 0x4419ce</figcaption></figure><p>To confirm the individual string boundaries, look at the cross-references to 0x4419ce. Each xref will use a different offset into the blob with a different length, corresponding to one of the original source strings. For example:</p><ul><li>0x4419ce + 0x00, len=0x3c = &quot;Continuing execution...&quot;</li><li>0x4419ce + 0x3c, len=0x12 = &quot;New child process...&quot;</li><li>0x4419ce + 0x4e, len=0x27 = &quot;Failed to stop vms: TODO: panic message&quot;</li><li>0x4419ce + 0x75, len=0x12 = &quot;Fork stopvm failed&quot;</li></ul><blockquote>In Binja: right-click on data_4419ce &gt; Cross References, and you will see each reference using a different offset, confirming the individual string boundaries.</blockquote><p><strong>Windows version regex in </strong><strong>.rodata:</strong></p><pre>win10-3(.*)(.*)|win10-4(.*)(.*)|win10-5(.*)(.*)</pre><blockquote><strong>Interesting: </strong>Windows version detection strings in a Linux ELF. This likely comes from a dependency that includes cross-platform compatibility checks.</blockquote><p><strong>aho-corasick crate confirmed:</strong> This is a string searching library, used here likely for file extension matching when deciding which files to encrypt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9KZsGK8zShvpePwnZ2oMQ.png" /></figure><p><strong>Additional crate paths confirmed:</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aho-corasick-1.1.2/src/util/alphabet.rs<br>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aho-corasick-1.1.2/src/util/debug.rs<br>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aho-corasick-1.1.2/src/util/remapper.rs<br>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aho-corasick-1.1.2/src/util/primitives.rs</pre><p><strong>Standard library paths:</strong></p><pre>library/alloc/src/raw_vec.rs<br>library/alloc/src/ffi/c_str.rs<br>library/alloc/src/sync.rs<br>library/alloc/src/vec/mod.rs<br>library/alloc/src/fmt.rs</pre><p><strong>lazy_st crate (truncated):</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lazy_st...</pre><p>This is almost certainly lazy_static or once_cell, used for global state initialisation. Common in Rust malware for initialising encryption keys or configuration once at startup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wi9WZpqflpPvGLAAmv0YKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*5Ehc2EUbvfggSEEiM6k-Nw.png" /><figcaption>Xref</figcaption></figure><p>This is the cross-reference panel for the lazy_st blob, not the next address. But the code reference is extremely revealing:</p><pre>_$LT$alloc..string..FromUtf8Error$u20$as$u20$core..fmt..Debug$GT$::fmt::h510500198db9042f</pre><p>And the instruction:</p><pre>lea rsi, [rel 0x442525]</pre><p>This tells you the code is loading a pointer into the middle of the blob at 0x442525, which is an offset within data_4424b7. The mangled symbol name FromUtf8Error confirms this blob is primarily about the alloc::string::FromUtf8Error Debug implementation, and lazy_st is simply the tail end of an adjacent panic path that got merged into the same blob.</p><p>Navigate to 0x442525 directly in Binja to see what the string looks like from that offset. But more importantly, to find the continuation of lazy_st, go to:</p><pre>g -&gt; 0x442580</pre><p>That is 0x4424b7 + 0xc9, the first byte after this blob ends. What Binja shows there will either be a new char const entry starting with atic or a completely unrelated string. Share that screenshot and we will know definitively.</p><p>Now confirmed. Look at address 0x500ba0:</p><pre>lea rsi, [rel data_4424b7[0x6e]]</pre><p>And Binja’s inline comment shows the full string at that offset:</p><pre>&quot;FromUtf8Error/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lazy_static-1.4.0/src/inline_lazy.rs/mnt/c/Users/user/.c</pre><p><strong>Confirmed: </strong><strong>lazy_static-1.4.0</strong></p><p>The exact version is 1.4.0, not unknown. The source file is inline_lazy.rs, which is the internal implementation file for lazy_static&#39;s hidden static guarding mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G66Gnd47Irh-4cMBSu1ogQ.png" /></figure><pre>.../lazy_static-1.4.0/src/inline_lazy.rs/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-wi</pre><p><strong>New crate partially confirmed: </strong><strong>unicode-wi...</strong></p><p>This is almost certainly unicode-width, a standard Rust crate for determining the display width of Unicode characters. It is a very common dependency pulled in by terminal/CLI output crates. Given Akira v2 uses <a href="https://github.com/console-rs/indicatif/tree/0c037edc86449d84aa457d7d5db80b4166c18d6b">indicatif</a> for progress bars and simplelog for logging, unicode-width as a transitive dependency makes complete sense.</p><p>To confirm the full name and version, navigate to the next address after this blob ends in Binja. The continuation should show dth-x.x.x completing unicode-width.</p><p><strong>Rust struct names leaking:</strong></p><p>FatAVX2, SlimSSSE3, SlimAVX2 are <strong>Rust struct names</strong> defined inside <a href="https://docs.rs/aho-corasick/1.1.2/src/aho_corasick/packed/teddy/builder.rs.html">aho-corasick</a>&#39;s <a href="https://github.com/BurntSushi/aho-corasick/tree/master/src/packed/teddy">Teddy packed search engine</a>. They are not algorithm names in the abstract sense. Specifically for SIMD backend implementations of the Teddy packed search algorithm.:</p><ul><li>SlimSSSE3 is a struct wrapping a 128-bit SSSE3 Teddy searcher</li><li>FatAVX2 is a 256-bit AVX2 fat Teddy searcher.</li><li>These are selected at runtime based on CPU feature detection: SlimSSSE3 is chosen when AVX2 is unavailable, FatAVX2 when AVX2 is available and the fat variant is preferred.</li></ul><pre>FatAVX2fat256teddymasksFatInvalidInputAnchoredInvalidInputUnanchoredUnsupportedStreamgotUnsupportedOverlappingPackedRareByteOffsetRa...<br>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aho-corasick-1.1.2/src/util/remapper.rsLeftmostLongestRabinKarpsearch_kindby_idordertotal_pattern_bytesbucketsimpmemory_usageSlimSSSE3slim128sl</pre><p><strong>akira_utils/src/lib.rs:</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/...akira_utils/src/lib.rs</pre><p>Look carefully at line 004423e0: a_utils/src/lib.rs. Combined with the prefix on the line above ending in akir, this reads as akira_utils/src/lib.rs. This is a <strong>custom internal crate</strong> named akira_utils, not a public crates.io dependency. This means the malware authors structured their code as a Cargo workspace with at least one internal library crate.</p><h3>What this tells you about the binary structure</h3><p>You can now reconstruct a partial Cargo.toml dependency tree purely from .rodata:</p><pre>[dependencies]<br>aho-corasick = &quot;1.1.2&quot;      # confirmed, multiple source files<br>lazy_static = &quot;1.4.0&quot;       # Confirmed<br><br>[workspace]<br>members = [<br>    &quot;akira_utils&quot;,           # internal crate confirmed<br>]</pre><p>The crates.io registry hash 6f17d22bba15001f is consistent across all paths, confirming these all came from the same Cargo build environment and the same registry snapshot.</p><h3>Panic String Analysis</h3><blockquote>This is a strong methodological point: <strong>panic string analysis recovers the internal crate architecture of a stripped Rust binary without any symbol information.</strong> Specifically:</blockquote><ul><li>Internal workspace crate names (akira_utils) recoverable</li><li>Exact third-party crate versions (aho-corasick-1.1.2) recoverable</li><li>Developer platform (WSL on Windows, same username user throughout) recoverable</li><li>SIMD feature flags (AVX2, SSSE3) inferable from algorithm variant names</li></ul><blockquote>None of this requires DWARF, symbol tables, or dynamic analysis. It is purely static .rodata recovery</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPRzmnv6vRuENXbuoIKNvQ.png" /><figcaption>Additional crates and internal paths</figcaption></figure><h3>Additional crates and internal paths</h3><p><strong>New crate confirmed: </strong><strong>block-buffer-0.10.4</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/block-buffer-0.10.4/src/lib.rs</pre><p>This is a cryptography support crate used by digest algorithm implementations. Confirms the crypto pipeline more precisely.</p><p><strong>New crate confirmed: </strong><strong>sha3-0.10.8</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/sha3-0.10.8/src</pre><p>SHA-3 hashing, likely used for key derivation or integrity checking.</p><p><strong>New crate confirmed: </strong><strong>simplelog-0.12.1</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/simplelog-0.12.1/src/loggers/writelog.rs</pre><p>This is the logging crate. Confirms the --logs trace/debug/error/info/warn CLI argument you saw earlier.</p><p><strong>New crate confirmed: </strong><strong>seahorse-2.2.0</strong></p><pre>/mnt/c/Users/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/seahorse-2.2.0/src/flag.rs</pre><p>The CLI argument parser, version now precisely pinned.</p><p><strong>Internal source paths:</strong></p><pre>akiranew/src/path_finder.rs<br>akira_v2::path_finder</pre><p>Confirms a dedicated path_finder module for filesystem enumeration.</p><pre>akiranew/src/lock.rs</pre><p>The encryption locking module, source path directly visible.</p><p><strong>ESXi path exclusions visible:</strong></p><pre>/proc/sbin/lib64/locker/productLocker/lost+found/bootbank/altbootbank/tardisks/vmfs/volumes/BOOTBANK1/vmfs/volumes/BOOTBANK2/vmfs/devices/vmimages/vmupgrade/bootpart.gz/local.tgz/local.tgzlog</pre><p>These are ESXi-specific paths that the ransomware skips during encryption. Directly recoverable from static analysis.</p><p><strong>ThreadPool::execute error string:</strong></p><pre>ThreadPool::execute unable to send job into queue.</pre><p>Confirms a custom thread pool implementation with explicit error handling.</p><p><a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs"><strong>indicatif</strong></a><strong> spinner format strings:</strong></p><pre>{spinner:.green} [{elapsed_precise}] {msg} [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})</pre><p>The progress bar format string from the <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">indicatif</a> crate, directly confirming its use for operator-facing encryption progress display.</p><p><strong>mpmc/mod.rs path:</strong></p><pre>/mpmc/mod.rs</pre><p>Multi-producer multi-consumer channel, part of the threading architecture for parallel encryption workers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4m-19BJwCSJFDapj47GwGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KIleI_BRIVklu5213zH8w.png" /></figure><h3>The ransom note is embedded directly in .rodata</h3><p>This is a significant finding. The entire akiranew.txt ransom note text is stored as a static string literal in .rodata starting around 0x440da0. Visible fragments include:</p><ul><li>Decryptor offer and negotiation text</li><li>.3. The security report or the exclusive first-hand information</li><li>Reference to darkmarket sale threat</li><li>Onion address: akiral2iz6a7qgd3ayp3l6yub7xx2uep76idk3u2kollpj5z3z636bad[.]onion</li><li>TOR browser instructions</li><li>Chat link: <a href="https://akiralkzxzq2dsrzsrvbr2xgbbu2wgsmxryd4csgfameg52n7efvr2id[.]onion">https://akiralkzxzq2dsrzsrvbr2xgbbu2wgsmxryd4csgfameg52n7efvr2id[.]onion</a></li><li>Code: 7818-NX-VVGG-FSFV</li></ul><p>This is the complete ransom note hardcoded as a single static string, not generated dynamically at runtime, it is a compile-time constant embedded verbatim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcqAgJpSbU86XzVa7nfVpw.png" /></figure><h3>Encryption operational strings</h3><p><strong>prng.rs internal source path:</strong></p><pre>akiranew/src/prng.rs</pre><p>A first-party PRNG module (akiranew/src/prng.rs) in the malware’s own source tree. Correction (24 June 2026): an earlier version suggested the authors hand-rolled a generator instead of using a crate. The binary shows otherwise. It links rand 0.8.5, rand_chacha 0.3.1 and getrandom 0.2.10, and the demangled symbols expose ThreadRng as ReseedingRng&lt;ChaCha12Core, OsRng&gt;, that is, the standard ChaCha12 CSPRNG reseeded from OsRng. No hand-rolled LCG or xorshift constants are present. So prng.rs is best read as a thin first-party wrapper over the rand crate (used for key material and random IDs), not a bespoke generator.</p><p><strong>Threading and file locking strings:</strong></p><pre>num_threads: <br>Free threads available: <br>/akiranew.txt<br>note write fail<br>File crypting<br>File crypted<br>Thread crashed.<br>File doesn&#39;t locked.<br>Error: Count of locking attempts for file is exceeded<br>Done</pre><p>These are all operator-facing runtime status messages. Crucially akiranew/src/prng.rs is the source file for the PRNG, and the locking attempt counter confirms a retry mechanism for file locking during encryption.</p><p><strong>Encryption progress format strings:</strong></p><pre>; stepsize  MB was read from the file<br>Unable to seek to position<br>Seek position of file : [] MB, buffer size is , block counter = Current buffer for<br>] MB is filled of zeros, skipping...{prefix:.bold.dim} {spinner} {wide_msg} {bytes_per_sec}</pre><p>These reveal the chunked encryption algorithm: the binary reads files in blocks (stepsize MB), seeks to positions, skips zero-filled blocks, and reports bytes per second to the operator.</p><p><strong>akira_v2::lock namespace confirmed:</strong></p><pre>akira_v2::lock6edd23fc19cbb91fa5574afbcfc81fb0e368be2b42f825e3e9f48dcbc38a0525</pre><p>This mangled symbol name contains what appears to be a hash suffix, consistent with Rust’s symbol mangling scheme for disambiguating generic instantiations.</p><p><strong>Wrong secret key format error:</strong></p><pre>Wrong secret key format. A hex string of 64 chars is expected</pre><p>Reveals the encryption key is passed as a 64-character hex string (32 bytes), consistent with a 256-bit key.</p><h3>Updated Cargo dependency table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*nBKWhUKUJfBaynwua6FcaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcqAgJpSbU86XzVa7nfVpw.png" /></figure><p><strong>Internal modules recovered:</strong> akira_utils, path_finder, lock, prng</p><p>All of this is recoverable purely from .rodata static analysis without executing the binary, without DWARF, and without symbols. That is your core thesis demonstrated in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TBJ6VaGJ02ZRei-zW-mYw.png" /></figure><h3>The full CLI help string recovered at 0x441603</h3><p>This is the most valuable string in the screenshot. The complete help text is visible:</p><pre>Start path. Default value: /vmfs/volumes<br>idstopvm<br>vmonlyCrypt only .vmdk, .vmem, .vmx, .log, .vswp, .vmsd, .vmsn files<br>threadsNumber of threads (1-1000). Default: number of logical CPU cores<br>epPercent of crypt. Default - 15%<br>Work in background<br>Print logs. Valid values for: trace, debug, error, info, warn. Default: off<br>excludeSkip files by &quot;regular&quot; extension. Example: --exclude=&quot;startf&quot;</pre><p>This reconstructs the <strong>complete CLI interface</strong> of Akira v2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*_ANwCN3XQpagePKikGSKVA.png" /></figure><p>The --ep 15% default is particularly significant: Akira v2 only encrypts <strong>15% of each file by default</strong>, which is a deliberate speed optimisation. Enough to corrupt the file but fast enough to maximise the number of files encrypted before detection.</p><h3>Regex exclusion pattern at 0x441780</h3><pre>ilename(.*)(.*)&quot; using this regular expression will skip all files <br>starting with startfilename and having any extensions. <br>Multiple regular expressions using &quot;|&quot; can also be processed: <br>--exclude=&quot;(win10-3(.*)(.*))|(win10-4(.*)(.*))|(win10-5(.*)(.*))</pre><p>This is the help text for --exclude, and the example regex win10-3|win10-4|win10-5 is revealing: it shows the operators were using Windows version strings as exclusion patterns, suggesting they selectively avoided encrypting certain Windows VM guests while targeting others.</p><h3>akiranew/src/main.rs source path confirmed at 0x4418a5</h3><pre>akiranew/src/main.rstraced</pre><p>The source file name akiranew/src/main.rs is directly embedded, confirming the project root crate name is akiranew, not akira_v2. The v2 designation is a researcher label, not the developer&#39;s own naming.</p><h3>The 0x4419ce string context now fully clear</h3><p>With this screenshot you can see the string immediately above 0x4419ce:</p><pre>d vmsvc/getallvms | tail -n +2 |<br>awk &#39;{system(&quot;vim-cmd vmsvc/power.off &quot; $1)}&#39;</pre><p>Then at 0x4419ce:</p><pre>Continuing execution in parent process, new child has pid: <br>New child processsh<br>Failed to stop vms: TODO: panic message<br>Fork stopvm failed<br>Logical CPUs:  Threads are set: EP values</pre><p>This gives you the full <strong>operational sequence</strong> of the --stopvm and --fork flow:</p><ol><li>Execute shell command to power off all VMs</li><li>Fork child process for encryption</li><li>Report child PID to operator</li><li>If stopvm fails: emit the TODO: panic message placeholder error</li><li>Report thread and EP configuration</li></ol><p>The TODO: panic message is definitively the stopvm failure error handler, confirming it is a developer placeholder left in the stopvm error branch specifically.</p><h3>Interactive prompt strings at 0x441a80</h3><pre>is 0 to 100. EP are set: %[1/2]<br>Do you want to continue? (y/n).</pre><p>And at 0x441abe:</p><pre>Failed to read line<br>Invalid input. Please enter &#39;y&#39; or &#39;n&#39;.<br>Exiting...<br>Continuing...</pre><p>This reveals Akira v2 has an <strong>interactive confirmation prompt</strong> before beginning encryption, where the operator confirms the EP percentage and thread settings. This is an operator safety check, not something visible in prior published analyses.</p><h3>Updated internal module map</h3><p>You can now reconstruct the project structure almost completely from .rodata alone:</p><pre>akiranew/<br>├── src/<br>│   ├── main.rs          (CLI parsing, interactive prompt, fork/stopvm)<br>│   ├── lock.rs          (encryption logic)<br>│   ├── path_finder.rs   (filesystem enumeration)<br>│   └── prng.rs          (custom PRNG)<br>└── Cargo.toml<br>    (workspace member: akira_utils)</pre><p>All recovered without symbols, without DWARF, purely from panic strings and format literals in .rodata. This is now a very strong empirical demonstration of your thesis.</p><h3>Updated dependency table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*P8wD84U9wtyRJ3kziF6R9w.png" /></figure><h3>The Control Flow Map</h3><p>The top-level call chain is:</p><pre>main  -&gt;  default_action  -&gt;  lock  -&gt;  lock_closure</pre><ul><li>main: collects CLI arguments, initialises the seahorse App struct, calls app.run(args).</li><li>default_action: the seahorse callback; reads flag values, optionally shuts down VMs, then calls lock.</li><li>lock: launches worker threads.</li><li>lock_closure: the actual encryption logic, running per thread.</li></ul><h3>Section 1: How args().collect() Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*9hqMRJrYjbM52GhzOdQzEA.png" /></figure><p>The malware’s first action is:</p><pre>let program_args: Vec&lt;String&gt; = args().collect();</pre><p>Tracing what this produces in memory requires following a four-layer type unwrapping chain.</p><h3>The unwrapping chain</h3><p>The article traces the type system from the public API down to bytes. Each step is a wrapper that hides the real representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uE_KVI6-vxpLM7HsVCimcw.png" /></figure><pre>std::env::args()<br>  -&gt; returns Args<br>      -&gt; wraps ArgsOs<br>          -&gt; wraps sys::args::Args  (PAL type, OS-specific)<br>              -&gt; on Unix: Vec&lt;OsString&gt;.into_iter()<br>                  -&gt; IntoIter&lt;OsString&gt;</pre><blockquote><strong>The key insight: </strong>the <em>public</em> type Args and its iterator wrapper are thin newtypes. By the time you reach the PAL implementation, the real data is a Vec&lt;OsString&gt; that was built by reading argc/argv from C FFI, then converted to OsString entries.</blockquote><p>The <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/env.rs#L756">std::env::args()</a> function returns Args, which wraps ArgsOs, which wraps sys::args::Args. Both outer wrappers are zero-overhead newtypes. The real work happens in <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L18">sys/pal/unix/args.rs</a>, the PAL (Platform Abstraction Layer) implementation for Unix targets.</p><p>This file does not live in the main std source tree. It is swapped in at compile time based on the target OS, which is why you cannot find sys::args::args by grepping the standard library directly.</p><h3>Step 1: The Public API</h3><p>From <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/env.rs#L756">env.rs</a> (line ~756):</p><pre>pub struct Args {<br>    inner: ArgsOs,<br>}<br><br>pub struct ArgsOs {<br>    inner: sys::args::Args,<br>}<br><br>pub fn args() -&gt; Args {<br>    Args { inner: args_os() }<br>}<br><br>pub fn args_os() -&gt; ArgsOs {<br>    ArgsOs { inner: sys::args::args() }<br>}</pre><p>Args and ArgsOs are pure newtypes. They add zero bytes of overhead. The only real data lives in sys::args::Args, which is a PAL type.</p><p><a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L61">sys::args::Args</a> is a PAL type because its concrete definition lives inside one of those OS-specific directories, not in a shared location. On Unix (which includes ESXi/Linux), it is defined in <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L61">sys/pal/unix/args.rs</a>(line ~61) as:</p><pre>pub struct Args {<br>    iter: vec::IntoIter&lt;OsString&gt;,<br>}</pre><p>On Windows it would be defined differently, potentially with a different internal representation. I will list them in the section of Further Reading below.</p><blockquote><strong><em>Note: </em></strong><em>The practical consequence for RE is that if you look for </em><em>sys::args::Args in the main standard library source you will not find it, because there is no single canonical definition. You have to know which PAL branch was compiled in, which is determined by the binary&#39;s target OS. For Akira v2 targeting ESXi, that means the Unix branch, and therefore the </em><em>vec::IntoIter&lt;OsString&gt; layout we traced through.</em></blockquote><h3>Step 2: The PAL Implementation (Unix)</h3><blockquote>PAL stands for <strong>Platform Abstraction Layer</strong>. It is a pattern in the Rust standard library where OS-specific implementations are swapped in at compile time based on the target platform.</blockquote><p>The way it works structurally is that std has a module sys::pal with subdirectories for each supported OS:</p><pre>std/src/sys/pal/<br>    unix/<br>    windows/<br>    wasi/<br>    ...</pre><p>Each subdirectory implements the same interface, but with platform-native code inside. The compiler selects the correct one via #[cfg(target_os = &quot;...&quot;)] attributes. The rest of std calls into sys::pal without knowing or caring which OS is underneath.</p><p>Because Akira v2 targeted ESXi (Linux-based), the relevant PAL is <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L18">sys/pal/unix/args.rs</a>. The article quotes the full function:</p><pre>/// Returns the command line arguments<br>pub fn args() -&gt; Args {<br>    let (argc, argv) = imp::argc_argv();          // (1)<br>    let mut vec = Vec::with_capacity(argc as usize);<br>    for i in 0..argc {<br>        let ptr = unsafe { argv.offset(i).read() }; // (2)<br>        if ptr.is_null() { break; }<br>        let cstr = unsafe { CStr::from_ptr(ptr) };  // (3)<br>        vec.push(OsStringExt::from_vec(cstr.to_bytes().to_vec())); // (4)<br>    }<br>    Args { iter: vec.into_iter() }                 // (5)<br>}</pre><p>What each line does:</p><p><strong>(1) </strong><strong>argc_argv()</strong> calls into the C runtime via FFI. On Linux, argc and argv are passed into the process by the kernel via the ELF aux vector and made available through glibc&#39;s .init_array mechanism. This gives you the classic C int argc, char** argv pair.</p><p><strong>(2) </strong><strong>argv.offset(i).read()</strong> is raw pointer arithmetic. argv is a *const *const c_char. .offset(i) moves the pointer by i * 8 bytes (on x64), then .read() dereferences it, giving you a *const c_char pointing to the i-th argument string.</p><p><strong>(3) </strong><strong>CStr::from_ptr(ptr)</strong> wraps that pointer as a null-terminated C string, no copy yet.</p><p><strong>(4) </strong><strong>cstr.to_bytes().to_vec()</strong> copies the raw bytes (excluding the null terminator) into a Vec&lt;u8&gt;, then OsStringExt::from_vec wraps that as an OsString. On Linux, OsString is literally just a Vec&lt;u8&gt; (three words: ptr, len, cap).</p><p><strong>(5) </strong><strong>vec.into_iter()</strong> is the key transformation. It consumes the Vec&lt;OsString&gt; and produces a vec::IntoIter&lt;OsString&gt;. This is what sys::args::Args actually stores.</p><h3>Step 3: The Concrete Memory Layout</h3><p>The definitionof <a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/alloc/src/vec/into_iter.rs#L45">IntoIter</a> in the current compiler source (lines 45–61 of <a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/alloc/src/vec/into_iter.rs#L45">into_iter.rs</a>) is:</p><pre>pub struct IntoIter&lt;T, A: Allocator = Global&gt; {<br>    pub(super) buf:     NonNull&lt;T&gt;,       // pointer to start of heap allocation<br>    pub(super) phantom: PhantomData&lt;T&gt;,   // zero-size, no bytes<br>    pub(super) cap:     usize,            // total capacity<br>    pub(super) alloc:   ManuallyDrop&lt;A&gt;,  // allocator (Global = zero-size)<br>    pub(super) ptr:     NonNull&lt;T&gt;,       // pointer to next element to yield<br>    pub(super) end:     *const T,         // pointer one-past last remaining element<br>}</pre><p>With the default Global allocator (which is zero-sized), the in-memory layout on x64 is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*GKpIw0gRIDyXbkWroz8Gxg.png" /></figure><p>Total: <strong>32 bytes</strong> on x64. phantom and alloc (Global) contribute zero bytes.</p><blockquote>The actual <a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/std/src/ffi/os_str.rs#L91">OsString</a> objects live on the heap at the address buf points to.</blockquote><p>Each <a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/std/src/ffi/os_str.rs#L91">OsString</a> on that heap is, on Linux, a <a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/alloc/src/vec/mod.rs#L397">Vec&lt;u8&gt;</a> internally:</p><pre>[ ptr: 8 bytes ][ len: 8 bytes ][ cap: 8 bytes ]</pre><h4><a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/alloc/src/raw_vec.rs#L76"><strong>RawVec&lt;T&gt;</strong></a><strong> struct definition</strong></h4><p>PhantomData is zero-sized. Global allocator is zero-sized. Cap is #[repr(transparent)] over usize. Unique&lt;u8&gt; is a non-null pointer, 8 bytes on x64.</p><pre>pub(crate) struct RawVec&lt;T, A: Allocator = Global&gt; {<br>    inner: RawVecInner&lt;A&gt;,<br>    _marker: PhantomData&lt;T&gt;,<br>}<br><br>struct RawVecInner&lt;A: Allocator = Global&gt; {<br>    ptr: Unique&lt;u8&gt;,<br>    cap: Cap,<br>    alloc: A,<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*mCpzVqRGg-O3xtUMzlgxxA.png" /></figure><p>So if you ran the binary with three arguments, the heap buffer at buf would contain three consecutive 24-byte structs, each pointing to its own heap allocation holding the raw argument bytes.</p><h3>Quick recap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awTpNo6JG-BOYmWEBN3W7w.png" /><figcaption>We still have a long road to go from here…</figcaption></figure><h4>1. Entry point</h4><pre>pub fn args() -&gt; Args {<br>    Args { inner: args_os() }<br>}<br>pub fn args_os() -&gt; ArgsOs {<br>    ArgsOs { inner: sys::args::args() }   // calls into PAL<br>}</pre><p>Both Args and ArgsOs are newtypes. Zero overhead.</p><h4>2. PAL for Linux ( sys/pal/unix/args.rs)</h4><p>The imp module for Linux stores argc/argv as two atomics set during process init (<a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L129">link</a> here, line 129–130):</p><pre>static ARGC: AtomicIsize = AtomicIsize::new(0);<br>static ARGV: AtomicPtr&lt;*const u8&gt; = AtomicPtr::new(ptr::null_mut());</pre><p>These are populated via .<a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L150">init_array.00099</a> (on glibc Linux) before main runs. The function <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L168">argc_argv()</a> simply reads them with <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L176">Ordering::Relaxed</a>.</p><p>Then <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L18">args()</a> builds the <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L58">Vec&lt;OsString&gt;</a>:</p><pre>pub fn args() -&gt; Args {<br>    let (argc, argv) = imp::argc_argv();<br>    let mut vec = Vec::with_capacity(argc as usize);<br>    for i in 0..argc {<br>        let ptr = unsafe { argv.offset(i).read() };<br>        if ptr.is_null() { break; }<br>        let cstr = unsafe { CStr::from_ptr(ptr) };<br>        vec.push(OsStringExt::from_vec(cstr.to_bytes().to_vec()));<br>    }<br>    Args { iter: vec.into_iter() }<br>}</pre><p>And <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L61">sys::args::Args</a> is defined immediately below in the same file:</p><pre>pub struct Args {<br>    iter: vec::IntoIter&lt;OsString&gt;,<br>}</pre><p>So sys::args::Args is just a newtype over vec::IntoIter&lt;OsString&gt;. Nothing more.</p><h4>3. Concrete memory layout</h4><p>After vec.into_iter(), on x64 Linux with <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L129">Global</a> allocator:</p><pre>IntoIter&lt;OsString&gt; (32 bytes on stack or in parent struct):<br>  +0x00  buf  (NonNull&lt;OsString&gt;)  = pointer to heap buffer<br>  +0x08  cap  (usize)              = total allocated slots<br>  +0x10  ptr  (NonNull&lt;OsString&gt;)  = next element to yield<br>  +0x18  end  (*const OsString)    = one past last element</pre><p>Each OsString on the heap is a <a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/alloc/src/vec/mod.rs#L397">Vec&lt;u8&gt;</a> (on Linux), so each slot in the buffer is 24 bytes:</p><pre>OsString (24 bytes):<br>  +0x00  ptr  (*mut u8)  = pointer to the argument string bytes<br>  +0x08  len  (usize)    = length of the string<br>  +0x10  cap  (usize)    = capacity</pre><h4>4. What next() looks like in assembly</h4><p>Each call to next() does:</p><ol><li>Compare ptr against end. If equal, return None.</li><li>Read the OsString at ptr (24 bytes).</li><li>Increment ptr by 24 (size_of::&lt;OsString&gt;() on Linux).</li><li>Return Some(osstring).</li></ol><p>When the outer Args::next() in env.rs is called, it additionally calls .into_string().unwrap() on the OsString, which validates UTF-8 and either reuses the allocation or panics.</p><h3>The Key RE Insight</h3><p>When you see the assembly for args().collect() in the Akira v2 binary, the confusing pointer arithmetic is exactly this: reading the ARGC/ARGV globals, looping over argv with stride-8 pointer arithmetic, copying each C string into a heap Vec&lt;u8&gt;, and building the IntoIter header. The collect() on top then walks ptr..end with stride-24 arithmetic, converting each OsString to String. Once you know those two stride values (8 for *const c_char, 24 for OsString on Linux), the assembly becomes readable.</p><h4>What argc_argv() does on Linux</h4><p>The PAL’s argc_argv() function reads two atomics, <a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L168">ARGC and </a><a href="https://github.com/rust-lang/rust/blob/db034cee00570a9b82ea8b9e9e95221dbd745698/library/std/src/sys/pal/unix/args.rs#L168">ARGV</a>, that were written during process initialisation. On glibc Linux, a function registered in .init_array.00099 receives (argc, argv, envp) from glibc before main runs and stores them in these atomics. Reading them back is a single Ordering::Relaxed load on each.</p><h4>Building the Vec&lt;OsString&gt;</h4><p>The args() function then:</p><ol><li>Calls Vec::with_capacity(argc as usize) to pre-allocate.</li><li>Iterates 0..argc, using raw pointer arithmetic (argv.offset(i).read()) to read each *const c_char.</li><li>Wraps each pointer as a CStr, copies the bytes into a Vec&lt;u8&gt; via to_bytes().to_vec(), and pushes it as an OsString via OsStringExt::from_vec.</li><li>Calls vec.into_iter(), producing a vec::IntoIter&lt;OsString&gt;.</li></ol><p>On Linux, OsString is a Vec&lt;u8&gt; internally: a 24-byte (ptr, len, cap) triple.</p><h4>The concrete memory layout</h4><p>The <a href="https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#45-48">vec::IntoIter&lt;T&gt;</a> struct (actual source, not the simplified nomicon version) has these fields:</p><pre>buf:     NonNull&lt;T&gt;       // 8 bytes: pointer   to heap allocation<br>cap:     usize            // 8 bytes: total capacity<br>alloc:   ManuallyDrop&lt;A&gt;  // 0 bytes: Global allocator is ZST<br>ptr:     NonNull&lt;T&gt;       // 8 bytes: next element to yield<br>end:     *const T         // 8 bytes: one-past-last element</pre><p>Total header: <strong>32 bytes</strong> on x64. The heap buffer at buf holds argc consecutive 24-byte OsString values. Iteration advances ptr by 24 bytes per call to next() and stops when ptr == end.</p><p>When collect() runs on the outer Args iterator, each OsString is validated as UTF-8 and converted to String. The final result is a Vec&lt;String&gt;, itself a 24-byte (ptr, len, cap) on the stack.</p><p><strong>RE implication</strong>: the confusing pointer arithmetic around args().collect() in the binary is stride-8 (reading argv[]) followed by string copies followed by stride-24 iteration. Once you know those two stride values, the assembly becomes readable.</p><h3>Further Reading</h3><h4>1. Some useful crates for CLI development</h4><p>There are several established approaches in Rust:</p><p><strong>Full-featured crates:</strong></p><ul><li><a href="https://github.com/clap-rs/clap">clap</a> : the dominant choice, supports derive macros, subcommands, validation, shell completions</li><li><a href="https://github.com/google/argh">argh</a> : Google’s crate, derive-based, optimised for binary size</li></ul><p><strong>Minimal/lightweight crates:</strong></p><ul><li><a href="https://github.com/RazrFalcon/pico-args">pico-args</a> : zero dependencies, manual parsing, very small</li><li><a href="https://github.com/blyxxyz/lexopt">lexopt</a>: low-level, explicit, good for when you want full control</li><li><a href="https://github.com/ksk001100/seahorse">seahorse</a> : what Akira used, builder pattern, minimal</li></ul><p><strong>Manual approaches:</strong></p><ul><li>std::env::args() directly: no dependency, just iterate and match strings yourself</li><li>std::env::args_os(): same but keeps OsString, useful when arguments may not be valid UTF-8</li></ul><p><strong>Other:</strong></p><ul><li><a href="https://github.com/TeXitoi/structopt">structopt</a>: older derive-based approach, now largely superseded by clap v3+</li></ul><p>For malware authors, the interesting trade-off is binary size and recognisability. clap produces very identifiable strings and patterns in the binary. seahorse or pico-args leave a much smaller and less distinctive footprint, which may be part of why it was chosen here.</p><h3>2. Windows vs Linux: Building the Vec&lt;OsString&gt;</h3><p>The two implementations are fundamentally different because Windows and Unix have different models for how arguments reach a process.</p><h4>The core difference</h4><p>On Linux, the kernel passes arguments as a char** argv array: each argument is already a separate null-terminated byte string. The PAL just reads them one by one.</p><p>On Windows, there is no argv array. The Win32 API delivers the entire command line as a <strong>single UTF-16 string</strong> via GetCommandLineW(). The PAL has to parse that string itself to split it into individual arguments.</p><h4>What the Windows args() does</h4><blockquote><em>Source code is </em><a href="https://github.com/rust-lang/rust/blob/ae4c6b66402cdbda8daa626216efd94e2dbe94b2/library/std/src/sys/pal/windows/args.rs#L21"><em>here</em></a><em> (line 21), path is</em> Rust/library/std/src/sys/pal/windows/args.rs#L21</blockquote><pre>pub fn args() -&gt; Args {<br>    // SAFETY: `GetCommandLineW` returns a pointer to a null terminated UTF-16<br>    // string so it&#39;s safe for `WStrUnits` to use.<br>    unsafe {<br>        let lp_cmd_line = c::GetCommandLineW();           // (1)<br>        let parsed_args_list = parse_lp_cmd_line(         // (2)<br>            WStrUnits::new(lp_cmd_line),<br>            || current_exe()...<br>        );<br>        Args { parsed_args_list: parsed_args_list.into_iter() }<br>    }<br>}</pre><p><strong>(1)</strong> GetCommandLineW() is a Win32 API call returning a pointer to a null-terminated UTF-16 string. The entire command line is one blob, e.g. myapp.exe --threads 8 --stopvm.</p><p><strong>(2)</strong> parse_lp_cmd_line is a hand-written parser implementing the <a href="https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args">Microsoft C/C++ argument parsing rules</a>. It handles:</p><ul><li>Whitespace as argument separators</li><li>Quoted strings (space inside quotes is literal)</li><li>Backslash escaping before quotes (odd number of backslashes escapes the quote)</li><li>Double-quote escaping inside a quoted string</li></ul><p>Each parsed token is pushed as OsString::from_wide(&amp;cur[..]), converting UTF-16 code units into a <a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/std/src/sys_common/wtf8.rs#L133">WTF-8</a> encoded OsString.</p><blockquote><a href="https://github.com/rust-lang/rust/blob/bd0826a4521a845f36cce1b00e1dd2918ba09e90/library/std/src/sys_common/wtf8.rs#L133">Wtf8Buf</a> has exactly two fields: bytes (a Vec&lt;u8&gt;, which is 24 bytes on x64: ptr, len, cap) and is_known_utf8 (a bool, 1 byte, padded to 8 bytes by alignment). So Wtf8Buf is <strong>32 bytes</strong> on x64.</blockquote><pre>pub struct Wtf8Buf {<br>    bytes: Vec&lt;u8&gt;,<br>    is_known_utf8: bool,<br>}</pre><h4>Step-by-step comparison table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*fk_sFDVnz6mhd4CRn9PiUQ.png" /></figure><h4>RE implication</h4><p>The final Args struct on both platforms is identically vec::IntoIter&lt;OsString&gt;, so the iteration pattern in assembly looks the same. The difference is everything before that: on Windows you will see a call to GetCommandLineW followed by a parsing loop with quote and backslash handling, where on Linux you will see atomic loads and a simple copy loop. The 32-byte vs 24-byte OsString stride difference also means the heap buffer iteration uses stride-32 on Windows vs stride-24 on Linux.</p><h3><strong>References</strong></h3><p>Check Point Research (2023) <em>Rust Binary Analysis Feature by Feature</em>. Available at: <a href="https://research.checkpoint.com/2023/rust-binary-analysis-feature-by-feature/">https://research.checkpoint.com/2023/rust-binary-analysis-feature-by-feature/</a></p><p>Check Point Research (2024) <em>Inside Akira Ransomware’s Rust Experiment</em>. Available at: <a href="https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/">https://research.checkpoint.com/2024/inside-akira-ransomwares-rust-experiment/</a></p><p>Cisco Talos (2024) <em>Akira Ransomware Continues to Evolve</em>. Available at: <a href="https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/">https://blog.talosintelligence.com/akira-ransomware-continues-to-evolve/</a></p><p>console-rs (no date) <em>indicatif</em>. Available at: <a href="https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs">https://github.com/console-rs/indicatif/blob/0c037edc86449d84aa457d7d5db80b4166c18d6b/examples/yarnish.rs</a>.</p><p>ksk001100 (no date) <em>seahorse</em>. Available at: <a href="https://github.com/ksk001100/seahorse">https://github.com/ksk001100/seahorse</a></p><p>Rust Project (no date) <em>std::vec::IntoIter source</em>. Available at: <a href="https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#45-48">https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#45-48</a></p><p>Rust Project (no date) <em>sys/pal/unix/args.rs</em>. Available at:<a href="https://github.com/rust-lang/rust/blob/79e9716c980570bfd1f666e3b16ac583f0168962/library/std/src/sys/unix/args.rs"> </a><a href="https://github.com/rust-lang/rust/blob/79e9716c980570bfd1f666e3b16ac583f0168962/library/std/src/sys/unix/args.rs">https://github.com/rust-lang/rust/blob/79e9716c980570bfd1f666e3b16ac583f0168962/library/std/src/sys/unix/args.rs</a></p><p>Sapin, S. (no date) <em>WTF-8: A superset of UTF-8</em>. Available at: <a href="https://simonsapin.github.io/wtf-8/">https://simonsapin.github.io/wtf-8/</a></p><p>Wikipedia (no date) <em>cgroups</em>. Available at: <a href="https://en.wikipedia.org/wiki/Cgroups">https://en.wikipedia.org/wiki/Cgroups</a></p><p>Vector 35 (no date) <em>Signature libraries</em>. Binary Ninja. Available at: <a href="https://binary.ninja/2020/03/11/signature-libraries.html">https://binary.ninja/2020/03/11/signature-libraries.html</a></p><p>Microsoft Security (no date) <em>Unveiling RIFT: Enhancing Rust malware analysis through pattern matching</em>. Microsoft Security Blog. Available at: <a href="https://www.microsoft.com/en-us/security/blog/2025/06/27/unveiling-rift-enhancing-rust-malware-analysis-through-pattern-matching/">https://www.microsoft.com/en-us/security/blog/2025/06/27/unveiling-rift-enhancing-rust-malware-analysis-through-pattern-matching/</a></p><p>Vector 35 (no date) <em>binaryninja.demangle — Binary Ninja API documentation</em>. Binary Ninja. Available at: <a href="https://api.binary.ninja/_modules/binaryninja/demangle.html">https://api.binary.ninja/_modules/binaryninja/demangle.html</a></p><p>Vector 35 (no date) <em>binaryninja::demangle — Binary Ninja Rust API</em>. Binary Ninja. Available at: <a href="https://rust.binary.ninja/binaryninja/demangle/index.html">https://rust.binary.ninja/binaryninja/demangle/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=937e0388d2c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/reversing-akiras-rust-experiment-a-breakdown-part-1-937e0388d2c7">Reversing Akira’s Rust Experiment: A Breakdown Part 1</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[x86–64 Assembly Breakdown: rep stos in 2 examples]]></title>
            <link>https://medium.com/re-exploit/x86-64-assembly-breakdown-rep-stos-in-2-examples-2344187a962e?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/2344187a962e</guid>
            <category><![CDATA[x86-64]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[x64-assembly]]></category>
            <category><![CDATA[assembly-debugging]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 17:15:29 GMT</pubDate>
            <atom:updated>2026-04-20T17:15:29.389Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The content is the note based on the practices from an amazing online course <a href="https://apps.p.ost2.fyi/learning/course/course-v1:OpenSecurityTraining2+Arch1001_x86-64_Asm+2021_v1/"><strong>OST2:Architecture 1001: x86–64 Assembly</strong> </a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*ocs_UROAxiPmHHa1hW0Ahw.png" /></figure><h3>Table of Contents</h3><ul><li>Part 1. REP STOS (Repeat Store String)</li><li>Part 2. Example 1: Array Variable</li><li>Part 3. Example 2: Corrupted Array</li></ul><p><em>Before you start…</em></p><blockquote><strong>Note:</strong> The examples are debig build using <strong>Visual Studio 2019.</strong> You might have different results using different version or other disassemblers.</blockquote><h3>Part 1. REP STOS (Repeat Store String)</h3><h3>Mechanics</h3><p>REP STOSB/STOSW/STOSD/STOSQ is a memory-fill primitive. The three registers involved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*NZ2X5gP3R8y16Y2KLUKWLA.png" /></figure><p>Each iteration: write *ax to [RDI], decrement RCX, increment RDI. Repeat until RCX hits zero.</p><p>Three setup steps must complete before the instruction executes: load RDI with the start address, load RAX/AL with the fill value, load RCX with the count.</p><p>The slide caption clarifies the register naming: *cx means CL/CX/ECX/RCX depending on mode; *di means DI/EDI/RDI. The 64-bit form uses RCX and RDI exclusively.</p><h3>MSVC Debug Use: Array Initialisation</h3><p>MSVC debug builds emit REP STOSD or REP STOSQ to zero-initialise local arrays before assigning values. This is the primary reason you encounter it in debug-mode RE. A typical prologue sequence for a local int arr[5]:</p><pre>lea     rdi, [rsp+20h]    ; destination = array base on stack<br>xor     eax, eax          ; fill value = 0<br>mov     ecx, 5            ; count = 5 dwords<br>rep stosd                 ; zero 5 × 4 = 20 bytes</pre><p>In release builds this is usually replaced by xorps/movaps or eliminated entirely as a dead store. Seeing REP STOSD in a binary is therefore a moderate debug-build indicator.</p><h3>Caller/Callee-save Divergence (Image 1)</h3><p>The highlighted cells show where MSVC’s Windows x64 ABI and System V AMD64 ABI <strong>disagree</strong> on RSI/RDI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*Q-HINkRdYWCAH-4UeFbJfQ.png" /></figure><p>This is directly relevant to REP STOS: because RDI is <strong>callee-saved under Windows</strong>, any function that uses REP STOS must push RDI on entry and restore it on exit. MSVC debug builds do exactly this. Under System V, RDI is caller-saved so no preservation is required.</p><p>RE implication: a Windows binary that saves/restores RDI around a REP STOS block is following the ABI correctly. A Linux binary doing the same is redundant (benign but sometimes a compiler artefact or hand-written asm). Seeing PUSH RDI / REP STOS / POP RDI in a Windows PE is a recognisable idiom worth flagging in YARA or BinNinja pattern scripts.</p><h3>Malware Detection Relevance</h3><p>REP STOS appears in malicious binaries in two contexts: stack/heap zeroing before shellcode placement (anti-forensics), and buffer initialisation in memory allocation wrappers. In Rust binaries, core::ptr::write_bytes (which underlies mem::zeroed and MaybeUninit initialisation) can lower to REP STOSD/Q at the LLVM codegen stage, though LLVM more commonly emits xorps/vmovdqu for small counts. A REP STOSQ in a Rust PE is less common than in MSVC C++ and worth noting as a possible inline assembly or FFI boundary artefact.</p><h3>Part 2. Example 1</h3><pre>// This Source Code is from<br>// https://gitlab.com/opensecuritytraining/arch1001_x86-64_asm_code_for_class/-/tree/master/ThereWillBe0xb100d?ref_type=heads<br><br>int main(){<br>	char buf[40];<br>	buf[39] = 42;<br>	return 0xb100d;<br>}</pre><p>Because this is an <strong>MSVC debug build</strong>.</p><p>The C source does not initialise buf, it only writes to buf[39]. In a release build, the compiler would either emit a single mov byte ptr [rsp+offset], 2Ah and nothing else, or eliminate the array entirely as a dead store.</p><p>In a debug build, MSVC deliberately fills the entire stack frame with 0xCC before any user code runs. The purpose is determinism: any read from an uninitialised local will produce 0xCCCCCCCC (or 0xCC for a byte), which is recognisable in the debugger rather than being whatever garbage happened to be on the stack from a previous call. 0xCC also doubles as the int 3 breakpoint opcode, so an accidental jump into uninitialised data triggers a trap rather than silent corruption.</p><p>REP STOSD is simply the mechanism MSVC chooses to perform that bulk fill efficiently, which set RDI to the frame base, EAX to 0xCCCCCCCC, ECX to the frame size in dwords, and let the hardware loop do the rest.</p><p>In a release build (/O2), this entire initialisation block vanishes. The REP STOS is not semantically required by the C, meaning it is a <strong>debug instrumentation artefact</strong>, not a language obligation.</p><h3>Part 3. Example 2: Corrupted Array</h3><p>Change the array index from 39 to 41 (out of the buf ).</p><pre>int main(){<br> char buf[40];<br> buf[41] = 42;<br> return 0xb100d;<br>}</pre><p>Assembly code:</p><pre>0000000140001000  push    rdi<br>0000000140001002  sub     rsp, 60h<br>0000000140001006  lea     rdi, [rsp+20h]<br>000000014000100B  mov     ecx, 10h<br>0000000140001010  mov     eax, 0CCCCCCCCh<br>0000000140001015  rep stos dword ptr [rdi]<br>0000000140001017  lea     rcx, [0000000140009000h]<br>000000014000101E  call    0000000140012D0<br>          char buf[40];<br>          buf[41] = 42;<br>0000000140001023  mov     eax, 1<br>0000000140001028  imul    rax, rax, 29h<br>000000014000102C  mov     byte ptr [rsp+rax+28h], 2Ah<br>          return 0xb100d;<br>0000000140001031  mov     eax, 0B100Dh<br>0000000140001036  mov     edi, eax<br>0000000140001038  mov     rcx, rsp<br>000000014000103B  lea     rdx, [0000000140005310h]<br>0000000140001042  call    000000014000010A0<br>0000000140001047  mov     eax, edi<br>0000000140001049  add     rsp, 60h<br>000000014000104D  pop     rdi<br>000000014000104E  ret</pre><h3>buf[41] = 42 : Precise Corruption Analysis</h3><h3>Frame Layout</h3><p>The prologue allocates 0x60 = 96 bytes via sub rsp, 60h. The frame contents from RSP upward:</p><pre>Offset from RSP  │ Size     │ Contents<br>──────────────────┼──────────┼──────────────────────────────────<br> +00h             │ 8 bytes  │ (alignment / compiler padding)<br> +08h             │ 8 bytes  │ (alignment / compiler padding)<br> +10h             │ 8 bytes  │ (alignment / compiler padding)<br> +18h             │ 8 bytes  │ (alignment / compiler padding)<br> +20h             │ 8 bytes  │ shadow space / RTC guard prefix<br> +28h             │ 40 bytes │ buf[0..39]  ← base of array<br> +28h .. +4Fh     │          │ buf[0] at +28h, buf[39] at +4Fh<br> +50h             │ 8 bytes  │ RTC guard suffix / padding<br> +58h             │ 8 bytes  │ saved RDI (pushed before sub rsp)<br>──────────────────┼──────────┼──────────────────────────────────<br> +60h             │          │ return address  ← above frame</pre><p>buf base is at [rsp+28h]. Last valid byte is buf[39] at [rsp+4Fh].</p><h3>REP STOS Fill Range</h3><pre>lea  rdi, [rsp+20h]    ; fill starts at rsp+20h, NOT rsp+0<br>mov  ecx, 10h          ; 16 dwords × 4 = 64 bytes<br>rep stos dword ptr [rdi]</pre><p>Fill covers [rsp+20h] through [rsp+5Fh] which is 64 bytes. This includes the 8-byte RTC prefix guard at [rsp+20h], all 40 bytes of buf, and the 8-byte RTC suffix guard at [rsp+50h]. Everything in that range is stamped 0xCC.</p><p>Note the fill does NOT start at RSP+0 that the bottom 32 bytes ([rsp+0] to [rsp+1Fh]) are left as-is. Those are shadow space slots, not sentinel-filled here.</p><h3>The Out-of-Bounds Write</h3><pre>mov  eax, 1<br>imul rax, rax, 29h      ; RAX = 41 (0x29)<br>mov  byte ptr [rsp+rax+28h], 2Ah</pre><p>Effective address: rsp + 0x28 + 0x29 = rsp + 0x51</p><p>buf[39] (last valid byte) is at rsp+0x4F.<br> buf[40] would be at rsp+0x50.<br> buf[41] lands at <strong>rsp+0x51</strong> — one byte into the RTC suffix guard region.</p><p>The guard region starting at [rsp+50h] was filled with 0xCCCCCCCC by REP STOS. The write deposits 0x2A at +0x51, corrupting the second byte of that guard dword. The guard dword at [rsp+50h] therefore reads 0xCC2ACCCCh rather than 0xCCCCCCCCh after the write.</p><h3>Why _RTC_CheckStackVars Fires</h3><pre>mov  rcx, rsp<br>lea  rdx, [0000000140005310h]   ; → RTC variable descriptor table<br>call 000000014000010A0           ; _RTC_CheckStackVars</pre><p>_RTC_CheckStackVars walks the descriptor table, which encodes the expected guard pattern at known offsets around each local variable. It reads the dword at [rsp+50h], finds 0xCC2ACCCCh instead of 0xCCCCCCCCh, and raises a runtime error:</p><blockquote><strong><em>Stack around the variable ‘buf’ was corrupted.</em></strong></blockquote><p>This fires before the epilogue, so the return value is preserved in EDI across the check call and restored to EAX at 140001047 — but in practice the RTC handler terminates the process before ret is ever reached.</p><h3>Comparison: index 39 vs 41</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*8ufkZRlLXY_21OdHJMHR6Q.png" /></figure><p>The hardware never faultsrsp+51h is within the allocated frame. The corruption is detectable only because MSVC deliberately placed a sentinel-filled guard region adjacent to buf and then verified it before returning.</p><h3>References</h3><p>Fog, A. (2023) <em>Calling conventions for different C++ compilers and operating systems</em>. Technical University of Denmark. Available at: <a href="https://www.agner.org/optimize/calling_conventions.pdf">https://www.agner.org/optimize/calling_conventions.pdf</a></p><p>Intel Corporation (2024) <em>Intel® 64 and IA-32 architectures software developer’s manual, combined volumes 2A, 2B, 2C and 2D: Instruction set reference, A–Z</em>. Santa Clara: Intel Corporation. Available at: <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html">https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html</a></p><p>Kovah, X. (2023) <em>Architecture 1001: x86–64 assembly, lecture 11 — RepStos / ArrayLocalVariable2</em>. OpenSecurityTraining2. Available at: <a href="https://opensecuritytraining.info/IntroX86-64_files/IntroductionToIntelx86-64-11_RepStos-Done.pdf">https://opensecuritytraining.info/IntroX86-64_files/IntroductionToIntelx86-64-11_RepStos-Done.pdf</a></p><p>Microsoft Corporation (2023) <em>x64 calling convention</em>. Microsoft Learn. Available at: <a href="https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention">https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention</a></p><p>Microsoft Corporation (2023) <em>x64 ABI conventions</em>. Microsoft Learn. Available at: <a href="https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions">https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2344187a962e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/x86-64-assembly-breakdown-rep-stos-in-2-examples-2344187a962e">x86–64 Assembly Breakdown: rep stos in 2 examples</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Engineering: mul, imul, div and idiv]]></title>
            <link>https://medium.com/re-exploit/reverse-engineering-mul-imul-div-and-idiv-1864d6d3c3ea?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/1864d6d3c3ea</guid>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[ost2]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[x86-64]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 19:51:48 GMT</pubDate>
            <atom:updated>2026-04-17T19:51:48.120Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The content is the note based on the practices from an amazing online course <a href="https://apps.p.ost2.fyi/learning/course/course-v1:OpenSecurityTraining2+Arch1001_x86-64_Asm+2021_v1/"><strong>OST2:Architecture 1001: x86–64 Assembly</strong> </a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg22XCm3e8pTCQyrGgyGwA.png" /></figure><h3>Table of Contents</h3><ul><li>Part 1. mul and imul</li><li>Part 2. Two’s Complement in Python</li><li>Part 3. Complete Code of imul_calculator.py</li><li>Part 4. div and idiv</li></ul><blockquote><strong>Source code</strong> can be found in my <a href="https://github.com/cxiao/reconstructing-rust-types-talk-re-verse-2025">GitHub Repo</a>. This is also an ongoing research, feel free to reach out to me. Always happy to have a chat about it.</blockquote><p><em>Before you start…</em></p><p>You might want to have <a href="https://ost2images.s3.amazonaws.com/Arch101_x86-64_Asm/CheatSheet_x86-64_Registers.pdf">the cheat sheet for registers</a>.</p><h3>Part 1. mul and imul</h3><h4>Python code as the template</h4><p>The key is how mul ebp selects its implicit operand. According to the <a href="https://apps.p.ost2.fyi/learning/course/course-v1:OpenSecurityTraining2+Arch1001_x86-64_Asm+2021_v1/block-v1:OpenSecurityTraining2+Arch1001_x86-64_Asm+2021_v1+type@sequential+block@fac4ee1079304c2eb2c936e61c8998fb">course material — <strong>Multiply and Divide</strong></a>:</p><blockquote>Python math string for debugging: ((i64 % 2**32) * (i32)) % 2**64</blockquote><p>mul ebp is a 32-bit multiply, so the CPU uses EAX as the implicit source, not RAX. EAX is the low 32 bits of RAX, which is exactly what % 2**32 captures, as it masks off the upper 32 bits that would live in the high half of RAX.</p><p>The % 2**64 on the outside models the fact that EDX:EAX together hold exactly 64 bits of result. In practice for a 32x32 multiply the product can be at most ~64 bits wide, so the modulo rarely clips anything, but it correctly represents the architectural constraint that the result is split across two 32-bit registers with no overflow beyond that.</p><p>So the Python maps directly to the hardware behaviour:</p><ul><li>% 2**32 -- take only EAX, discarding the upper half of RAX</li><li>* 0x2E17A276 -- unsigned multiply by EBP</li><li>% 2**64 -- result fits in EDX:EAX, 64 bits total</li></ul><h3>Example 1 — mul</h3><pre>mov rax, 0x72BC91288B268301 <br>mov ebp, 0x3ECF3022 <br>mul ebp<br><br>What value is in edx:eax after this code executes?</pre><pre>result = ((0x72BC91288B268301 % 2**32) * 0x3ECF3022) % 2**64<br>print(hex(result))<br># 0x2223f207df7c9622</pre><h3>Example 2-mul</h3><pre>mov rax, 0x01F2CB7F98D302C2<br>mov r11w, 0xF295mul r11w<br><br>What value is in dx:ax after this code executes?</pre><p>r11w is 16-bit, so this is the DX:AX = AX * r/m16 form.</p><p>AX = low 16 bits of RAX = 0x02C2.</p><pre>r1 = ((0x01F2CB7F98D302C2 % 2**16) * 0xF295) % 2**32<br>print(hex(r1))<br># 0x29cfeea</pre><p>0x02C2 * 0xF295 = 0x02BF_028A</p><p>DX = 0x02BF, AX = 0x028A</p><h3>Example 3 - imul</h3><pre>mov rax, 0xFDDA19C78185B97C <br>mov r9w, 0x8035 <br>imul r9w</pre><pre>import ctypes<br><br>rax = 0xFDDA19C78185B97C<br>r9w = 0x8035<br><br>ax = rax &amp; 0xFFFF  # low 16 bits of RAX<br><br># signed 16-bit interpretation<br>ax_signed = ctypes.c_int16(ax).value<br>r9w_signed = ctypes.c_int16(r9w).value<br><br>result = ax_signed * r9w_signed  # signed 32-bit result in DX:AX<br><br>dx = (result &gt;&gt; 16) &amp; 0xFFFF<br>ax_out = result &amp; 0xFFFF<br><br>print(hex(result &amp; 0xFFFFFFFF))<br>print(f&quot;DX = {hex(dx)}, AX = {hex(ax_out)}&quot;)</pre><p><strong>Step 1: Set up the register values</strong></p><pre>rax = 0xFDDA19C78185B97C<br>r9w = 0x8035</pre><p>These are just Python integers holding the raw bit patterns of RAX and R9W before the instruction executes.</p><p><strong>Step 2: Extract </strong><strong>AX from </strong><strong>RAX</strong></p><pre>ax = rax &amp; 0xFFFF</pre><p>imul r9w is a 16-bit multiply, so the CPU uses AX as the implicit operand, not RAX. &amp; 0xFFFF masks off everything above bit 15, leaving only the low 16 bits. ax = 0xB97C.</p><p><strong>Step 3: Reinterpret both values as signed 16-bit</strong></p><pre>ax_signed = ctypes.c_int16(ax).value<br>r9w_signed = ctypes.c_int16(r9w).value</pre><p>ctypes.c_int16 forces Python to reinterpret the bit pattern as a signed 16-bit integer using two&#39;s complement. This is what distinguishes imul from mul -- both operands are treated as signed before multiplication. 0xB97C becomes -18052, 0x8035 becomes -32715.</p><p><strong>Step 4: Multiply</strong></p><pre>result = ax_signed * r9w_signed</pre><p>Python multiplies two signed integers. The result fits within 32 bits and maps to DX:AX.</p><p><strong>Step 5: Split result into </strong><strong>DX and </strong><strong>AX</strong></p><pre>dx = (result &gt;&gt; 16) &amp; 0xFFFF<br>ax_out = result &amp; 0xFFFF</pre><p>result &gt;&gt; 16 shifts the high 16 bits down to extract DX. &amp; 0xFFFF isolates the low 16 bits for AX.</p><p><strong>Step 6: Print</strong></p><pre>print(hex(result &amp; 0xFFFFFFFF))<br>print(f&quot;DX = {hex(dx)}, AX = {hex(ax_out)}&quot;)</pre><p>&amp; 0xFFFFFFFF masks the full result to 32 bits for display. Without this, if result is negative Python prints a minus sign rather than the two&#39;s complement hex representation that the CPU would show in DX:AX.</p><h4>Another method</h4><p>This code manually implements signed 16-bit multiplication without using ctypes, following the exact algorithm the course described: convert to signed, take absolutes, multiply, then apply sign.</p><pre>def signedMul16by16(a_u16, b_u16):<br>    # Interpret as signed 16-bit<br>    a_s = a_u16 if a_u16 &lt; 0x8000 else a_u16 - 0x10000<br>    b_s = b_u16 if b_u16 &lt; 0x8000 else b_u16 - 0x10000<br><br>    a_neg = a_s &lt; 0<br>    b_neg = b_s &lt; 0<br><br>    a_abs = -a_s if a_neg else a_s<br>    b_abs = -b_s if b_neg else b_s<br><br>    result = a_abs * b_abs<br><br>    if a_neg ^ b_neg:<br>        result = (-result) &amp; 0xFFFFFFFF<br><br>    return result<br><br><br>i64 = 0xFDDA19C78185B97C<br>si16 = 0x8035<br><br>a_u16 = i64 % 2**16<br>b_u16 = si16 &amp; 0xFFFF<br><br>result = signedMul16by16(a_u16, b_u16)<br><br>dx = (result &gt;&gt; 16) &amp; 0xFFFF<br>ax = result &amp; 0xFFFF<br><br>print(f&quot;Input ax (low 16 of rax): {a_u16:#06x}&quot;)<br>print(f&quot;Input r9w:                {b_u16:#06x}&quot;)<br>print(f&quot;Result (dx:ax):           {result:#010x}&quot;)<br>print(f&quot;  dx = {dx:#06x}&quot;)<br>print(f&quot;  ax = {ax:#06x}&quot;)<br>print(f&quot;Expected: 0x233366AC&quot;)<br>print(f&quot;Match: {result == 0x233366AC}&quot;)</pre><p><strong>Step 1: Convert unsigned 16-bit inputs to signed</strong></p><pre>a_s = a_u16 if a_u16 &lt; 0x8000 else a_u16 - 0x10000<br>b_s = b_u16 if b_u16 &lt; 0x8000 else b_u16 - 0x10000</pre><p>If the value is below 0x8000 (32768), the sign bit is 0 -- it is already positive. If it is 0x8000 or above, the sign bit is 1 -- subtract 0x10000 (65536) to get the negative two&#39;s complement value. This is the manual equivalent of what ctypes.c_int16 does automatically.</p><p><strong>Step 2: Record signs and take absolute values</strong></p><pre>a_neg = a_s &lt; 0<br>b_neg = b_s &lt; 0<br>a_abs = -a_s if a_neg else a_s<br>b_abs = -b_s if b_neg else b_s</pre><p>Separates the sign from the magnitude so the multiplication itself is always between two positive integers.</p><p><strong>Step 3: Multiply the absolute values</strong></p><pre>result = a_abs * b_abs</pre><p>Plain unsigned multiplication of two positive integers.</p><p><strong>Step 4: Apply the sign</strong></p><pre>if a_neg ^ b_neg:<br>    result = (-result) &amp; 0xFFFFFFFF</pre><p>XOR of the two sign flags: if exactly one operand was negative, the result is negative. Two’s complement negation is applied with &amp; 0xFFFFFFFF to keep it within 32 bits and produce the correct unsigned hex representation. If both were negative or both positive, the result stays positive.</p><p><em>The XOR truth table for sign determination:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*h54wmhRrcUhmdtISwt5zSg.png" /><figcaption><em>The XOR truth table for sign determination:</em></figcaption></figure><p>This is the standard sign rule from arithmetic: negative times positive is negative, negative times negative is positive.</p><p>When the result needs to be negative, this line executes:</p><pre>result = (-result) &amp; 0xFFFFFFFF</pre><p>Two things happen here.</p><ul><li>-result negates the positive product in Python&#39;s arbitrary-precision integers, producing a negative Python integer, for example -590123.</li><li>&amp; 0xFFFFFFFF then masks it to 32 bits. Python represents negative integers with infinite-precision two&#39;s complement internally, so ANDing with 0xFFFFFFFF extracts the low 32 bits, which is exactly the two&#39;s complement 32-bit representation of that negative number. This is what the CPU would store across EDX:EAX, that’s, no minus sign, just a bit pattern.</li></ul><p>For example, -1 becomes 0xFFFFFFFF. -590123 becomes whatever 32-bit pattern represents that value in two&#39;s complement. The &amp; 0xFFFFFFFF is doing the same work as the CPU&#39;s fixed-width registers do automatically by having a finite bit width.</p><p><strong>Step 5: Extract </strong><strong>DX and </strong><strong>AX and print</strong></p><p>Same as the ctypes version -- high 16 bits to DX, low 16 bits to AX. The Match line verifies against the known correct answer 0x233366AC.</p><p>The reason your earlier simpler if a &gt;= 2**15: a -= 2**16 version produced the wrong answer is likely a scoping issue -- a and b were being modified inside the function but the XOR sign logic was missing, so negative results were not being correctly two&#39;s complement masked back to 32 bits.</p><h3>Example 4 - imul</h3><pre>mov rax, 0xF76A868F750B1B7C<br>mov ebx, 0xE7E0E34D<br>imul ebx</pre><pre>Input eax (low 32 of rax): 0x750b1b7c<br>Input ebx:                 0xe7e0e34d<br>Result (edx:eax):          0xf4f8bbf4fe36384c<br>  edx = 0xf4f8bbf4<br>  eax = 0xfe36384c</pre><pre>  def signedMul32by32(a_u32, b_u32):<br>    a_s = a_u32 if a_u32 &lt; 0x80000000 else a_u32 - 0x100000000<br>    b_s = b_u32 if b_u32 &lt; 0x80000000 else b_u32 - 0x100000000<br><br>    a_neg = a_s &lt; 0<br>    b_neg = b_s &lt; 0<br><br>    a_abs = -a_s if a_neg else a_s<br>    b_abs = -b_s if b_neg else b_s<br><br>    result = a_abs * b_abs<br><br>    if a_neg ^ b_neg:<br>        result = (-result) &amp; 0xFFFFFFFFFFFFFFFF<br><br>    return result<br><br><br>i64 = 0xF76A868F750B1B7C<br>si32 = 0xE7E0E34D<br><br>a_u32 = i64 % 2**32<br>b_u32 = si32 &amp; 0xFFFFFFFF<br><br>result = signedMul32by32(a_u32, b_u32)<br><br>edx = (result &gt;&gt; 32) &amp; 0xFFFFFFFF<br>eax = result &amp; 0xFFFFFFFF<br><br>print(f&quot;Input eax (low 32 of rax): {a_u32:#010x}&quot;)<br>print(f&quot;Input ebx:                 {b_u32:#010x}&quot;)<br>print(f&quot;Result (edx:eax):          {result:#018x}&quot;)<br>print(f&quot;  edx = {edx:#010x}&quot;)<br>print(f&quot;  eax = {eax:#010x}&quot;)</pre><h3>Example 5mul</h3><pre>mov rax, 0xFD956DB0E406E370<br>mov bl, 0x05<br>mul bl</pre><pre>al = 0xFD956DB0E406E370 &amp; 0xFF  # 0x70<br>bl = 0x05<br><br>ax = al * bl  # 0x70 * 0x05 = 0x230<br>print(f&quot;{ax:#06x}&quot;) # hexadecimal 0x230<br>print(f&quot;{ax}&quot;) # decimal 560</pre><h3>Example 7 — imul</h3><pre>mov rax, 0xFDC902B993BB5A85 <br>mov r13d, 0xA638B3A0 <br>imul r13d<br><br>### --------------------------------------------------------<br>Input eax (low 32 of rax): 0x93bb5a85<br>Input r13d:                0xa638b3a0<br>Result (edx:eax):          0x25f82731607b9220<br>  edx = 0x25f82731<br>  eax = 0x607b9220<br><br></pre><pre>def signedMul32by32(a_u32, b_u32):<br>    a_s = a_u32 if a_u32 &lt; 0x80000000 else a_u32 - 0x100000000<br>    b_s = b_u32 if b_u32 &lt; 0x80000000 else b_u32 - 0x100000000<br><br>    a_neg = a_s &lt; 0<br>    b_neg = b_s &lt; 0<br><br>    a_abs = -a_s if a_neg else a_s<br>    b_abs = -b_s if b_neg else b_s<br><br>    result = a_abs * b_abs<br><br>    if a_neg ^ b_neg:<br>        result = (-result) &amp; 0xFFFFFFFFFFFFFFFF<br><br>    return result<br><br><br>i64 = 0xFDC902B993BB5A85<br>si32 = 0xA638B3A0<br><br>a_u32 = i64 % 2**32<br>b_u32 = si32 &amp; 0xFFFFFFFF<br><br>result = signedMul32by32(a_u32, b_u32)<br><br>edx = (result &gt;&gt; 32) &amp; 0xFFFFFFFF<br>eax = result &amp; 0xFFFFFFFF<br><br>print(f&quot;Input eax (low 32 of rax): {a_u32:#010x}&quot;)<br>print(f&quot;Input r13d:                {b_u32:#010x}&quot;)<br>print(f&quot;Result (edx:eax):          {result:#018x}&quot;)<br>print(f&quot;  edx = {edx:#010x}&quot;)<br>print(f&quot;  eax = {eax:#010x}&quot;)</pre><h3>Part 2. Two’s Complement in Python</h3><p>Because Python’s integers are already two’s complement under the hood, with infinite precision, so -result is already the mathematically correct negative number.</p><p>The “flip all bits and add one” procedure is only needed when you are working within a fixed bit width and need to manually convert a positive bit pattern to its negative equivalent. On the CPU, to negate 0x00000005 you flip to 0xFFFFFFFA and add one to get 0xFFFFFFFB.</p><p>Python skips that because -590123 in Python is -590123 exactly, with no bit width constraint forcing a different representation. The &amp; 0xFFFFFFFF at the end is the only step that imposes a fixed width, and at that point Python&#39;s internal two&#39;s complement representation naturally produces the same bit pattern the CPU would, without manually flipping and adding one.</p><blockquote><strong>In short:</strong> flip-and-add-one is a procedure for computing two’s complement negation within a fixed-width register. Python’s <em>-</em> operator gives you the correct signed value directly, and <em>&amp; 0xFFFFFFFF</em> then extracts the fixed-width bit pattern from it.</blockquote><h3>Part 3. Complete Code of imul_calculator.py</h3><h4>The whole code</h4><pre>REGISTER_BITS = {<br>    # 64-bit<br>    &#39;rax&#39;: 64, &#39;rbx&#39;: 64, &#39;rcx&#39;: 64, &#39;rdx&#39;: 64,<br>    &#39;rsi&#39;: 64, &#39;rdi&#39;: 64, &#39;rsp&#39;: 64, &#39;rbp&#39;: 64,<br>    &#39;r8&#39;: 64, &#39;r9&#39;: 64, &#39;r10&#39;: 64, &#39;r11&#39;: 64,<br>    &#39;r12&#39;: 64, &#39;r13&#39;: 64, &#39;r14&#39;: 64, &#39;r15&#39;: 64,<br>    # 32-bit<br>    &#39;eax&#39;: 32, &#39;ebx&#39;: 32, &#39;ecx&#39;: 32, &#39;edx&#39;: 32,<br>    &#39;esi&#39;: 32, &#39;edi&#39;: 32, &#39;esp&#39;: 32, &#39;ebp&#39;: 32,<br>    &#39;r8d&#39;: 32, &#39;r9d&#39;: 32, &#39;r10d&#39;: 32, &#39;r11d&#39;: 32,<br>    &#39;r12d&#39;: 32, &#39;r13d&#39;: 32, &#39;r14d&#39;: 32, &#39;r15d&#39;: 32,<br>    # 16-bit<br>    &#39;ax&#39;: 16, &#39;bx&#39;: 16, &#39;cx&#39;: 16, &#39;dx&#39;: 16,<br>    &#39;si&#39;: 16, &#39;di&#39;: 16, &#39;sp&#39;: 16, &#39;bp&#39;: 16,<br>    &#39;r8w&#39;: 16, &#39;r9w&#39;: 16, &#39;r10w&#39;: 16, &#39;r11w&#39;: 16,<br>    &#39;r12w&#39;: 16, &#39;r13w&#39;: 16, &#39;r14w&#39;: 16, &#39;r15w&#39;: 16,<br>    # 8-bit<br>    &#39;al&#39;: 8, &#39;bl&#39;: 8, &#39;cl&#39;: 8, &#39;dl&#39;: 8,<br>    &#39;ah&#39;: 8, &#39;bh&#39;: 8, &#39;ch&#39;: 8, &#39;dh&#39;: 8,<br>    &#39;sil&#39;: 8, &#39;dil&#39;: 8, &#39;spl&#39;: 8, &#39;bpl&#39;: 8,<br>    &#39;r8b&#39;: 8, &#39;r9b&#39;: 8, &#39;r10b&#39;: 8, &#39;r11b&#39;: 8,<br>    &#39;r12b&#39;: 8, &#39;r13b&#39;: 8, &#39;r14b&#39;: 8, &#39;r15b&#39;: 8,<br>}<br><br><br>def signedMul(a_u, b_u, bits):<br>    sign_threshold = 1 &lt;&lt; (bits - 1)<br>    modulus        = 1 &lt;&lt; bits<br><br>    a_s = a_u if a_u &lt; sign_threshold else a_u - modulus<br>    b_s = b_u if b_u &lt; sign_threshold else b_u - modulus<br><br>    a_neg = a_s &lt; 0<br>    b_neg = b_s &lt; 0<br><br>    a_abs = -a_s if a_neg else a_s<br>    b_abs = -b_s if b_neg else b_s<br><br>    result = a_abs * b_abs<br><br>    if a_neg ^ b_neg:<br>        result = (-result) &amp; 0xFFFFFFFFFFFFFFFF<br><br>    return result<br><br><br>def imul(reg_a, val_a, reg_b, val_b):<br>    bits_a = REGISTER_BITS[reg_a.lower()]<br>    bits_b = REGISTER_BITS[reg_b.lower()]<br><br>    if bits_a != bits_b:<br>        raise ValueError(f&quot;Operand size mismatch: {reg_a} ({bits_a}-bit) vs {reg_b} ({bits_b}-bit)&quot;)<br><br>    mask   = (1 &lt;&lt; bits_a) - 1<br>    a_u    = val_a &amp; mask<br>    b_u    = val_b &amp; mask<br><br>    result = signedMul(a_u, b_u, bits_a)<br>    dest   = result &amp; mask<br><br>    print(f&quot;Register size:  {bits_a}-bit&quot;)<br>    print(f&quot;Input {reg_a}:  {a_u:#x}&quot;)<br>    print(f&quot;Input {reg_b}:  {b_u:#x}&quot;)<br>    print(f&quot;Full result:    {result:#018x}&quot;)<br>    print(f&quot;  {reg_a} = {dest:#x}&quot;)<br><br><br><br>imul(&#39;r11w&#39;, 0xFC3C0994B40B81FC, &#39;bp&#39;, 0x6E68)</pre><h3>Breakdown</h3><p>This code simulates the x64 imul instruction in Python, handling the signed-multiplication semantics that the CPU implements natively. Walk through it bottom-up.</p><h3>REGISTER_BITS</h3><p>A lookup table mapping every x64 general-purpose register name to its width in bits. The four tiers (64/32/16/8) match the physical aliasing hierarchy on the CPU: rax/eax/ax/al all refer to overlapping storage, but this dict just records width -- it does not model aliasing.</p><p>The 8-bit entries include both low-byte aliases (al, bl, ...) and the high-byte aliases (ah, bh, ch, dh), plus the REX-prefixed low-byte aliases for the extended registers (sil, dil, r8b, ...).</p><h3>signedMul(a_u, b_u, bits)</h3><p>The CPU stores operands as unsigned bit patterns; signed interpretation happens at execution time. This function replicates that behaviour in Python.</p><p><strong>Setup:</strong></p><ul><li>sign_threshold = 1 &lt;&lt; (bits - 1) -- the boundary between non-negative and negative in two&#39;s complement. For 8-bit: 0x80 (128).</li><li>modulus = 1 &lt;&lt; bits -- the full unsigned range, i.e. 2^bits. For 8-bit: 0x100 (256).</li></ul><p><strong>Two’s-complement decode (</strong><strong>a_s, </strong><strong>b_s):</strong></p><ul><li>If the value is below sign_threshold, it is already a non-negative signed integer -- no change.</li><li>If it meets or exceeds sign_threshold, subtract modulus to wrap it into the negative half.</li><li>Example: 0xCA = 202, 202 &gt;= 128, so a_s = 202 - 256 = -54.</li></ul><p><strong>Multiplication:</strong></p><ul><li>a_neg / b_neg record the sign of each decoded operand.</li><li>a_abs / b_abs take absolute values so the product is computed on positive magnitudes.</li><li>result = a_abs * b_abs -- unbounded Python integer multiplication, no truncation yet.</li></ul><p><strong>Sign restoration:</strong></p><ul><li>a_neg ^ b_neg -- if exactly one operand was negative, the product is negative.</li><li>(-result) &amp; 0xFFFFFFFFFFFFFFFF -- negates, then masks to 64 bits, converting the Python negative integer back to an unsigned two&#39;s-complement representation.</li><li>This mask is always 64 bits regardless of operand width, so the full result is always returned as a 64-bit unsigned value. Real hardware produces a 2 * bits-wide result (e.g. AX for 8-bit imul), which matters if you extend this to the one-operand form.</li></ul><h3>imul(reg_a, val_a, reg_b, val_b)</h3><p>Simulates the two-operand imul dst, src form, where reg_a is both source and destination.</p><p><strong>Width resolution:</strong></p><ul><li>REGISTER_BITS[reg_a.lower()] -- normalises to lowercase and looks up the bit width. Accepts &quot;R14B&quot; or &quot;r14b&quot; interchangeably.</li><li>Raises ValueError immediately if the two registers differ in width -- real imul requires matched operand sizes.</li></ul><p><strong>Input masking:</strong></p><ul><li>mask = (1 &lt;&lt; bits_a) - 1 -- operand-width bitmask. For 8-bit: 0xFF.</li><li>val_a &amp; mask and val_b &amp; mask clamp the Python integers to the register width before passing them to signedMul. This is why passing 0xF6793DCBEC94E4C8 to an 8-bit register is harmless -- everything above bit 7 is discarded, leaving 0xC8.</li></ul><p><strong>Result truncation:</strong></p><ul><li>dest = result &amp; mask -- truncates the full product back to the operand width, matching what the CPU writes to the destination register.</li><li>Overflow is silently dropped. OF and CF would be set on real hardware; this simulator does not model flags.</li></ul><h3>The call: imul(&#39;r14b&#39;, 0xCA, &#39;r8b&#39;, 0xF6793DCBEC94E4C8)</h3><p>Both registers are 8-bit, so mask = 0xFF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*sDoro5Ent5KQNG14a5KznQ.png" /></figure><p>Expected output:</p><pre>Register size:  8-bit<br>Input r14b:  0xca<br>Input r8b:  0xc8<br>Full result:    0x0000000000000bd0<br>  r14b = 0xd0</pre><h3>Part 4. div and idiv</h3><h3>Example 4.1</h3><pre>mov ax, 0x7783<br>mov r11b, 0xD3i<br>div r11b</pre><p>The operand is r11b (8-bit), so this is the AX ÷ r/m8 form: AL = quotient, AH = remainder.</p><p>idiv is signed, so interpret both operands as signed values.</p><p>AX = 0x7783 → signed 16-bit = <strong>+30595</strong></p><p>r11b = 0xD3 → signed 8-bit = <strong>-45</strong> (since 0xD3 = 211, and 211 - 256 = -45)</p><pre>quotient  = trunc(-30595 / 45) = trunc(-679.888...) = -679<br>remainder = -30595 - (-679 * -45) = -30595 - 30555 = -40</pre><p>-679 in hex: 679 = 0x2A7, so -679 two’s complement 16-bit = 0xFD59, but AL holds only the low 8 bits → 0x59... wait, let me be precise.</p><p>AL = quotient truncated to 8-bit signed. -679 does <strong>not</strong> fit in a signed 8-bit (-128 to +127), which would normally raise a #DE fault. But the question asks us to compute it, so let’s verify with Python:</p><pre>ax = 0x7783          # = 30595 unsigned, +30595 signed<br>dividend = 0x7783<br>if dividend &gt;= 0x8000:<br>    dividend -= 0x10000   # sign-extend to signed 16-bit<br># dividend = +30595<br><br>divisor = 0xD3<br>if divisor &gt;= 0x80:<br>    divisor -= 0x100      # sign-extend to signed 8-bit<br># divisor = -45<br>import math<br>quotient  = int(30595 / -45)   # truncate toward zero = -679<br>remainder = 30595 - (quotient * -45)<br>al = quotient &amp; 0xFF</pre><p>Quotient = -679 → 0xFFFFFD59 → low byte = <strong>0x59</strong></p><p>However: -679 overflows a signed byte, so real hardware raises #DE. If the exercise expects you to just take the low byte anyway:</p><p><strong>AL = </strong><strong>0x59</strong></p><h3>Example 2</h3><pre>mov ax, 0x1B9C<br>mov dil, 0x72<br>idiv dil</pre><p>AX ÷ r/m8 form again: AL = quotient, AH = remainder.</p><p>AX = 0x1B9C → signed 16-bit = <strong>+7068</strong></p><p>dil = 0x72 → signed 8-bit = <strong>+114</strong> (0x72 = 114, well within 0–127 so no sign flip)</p><pre>quotient  = trunc(7068 / 114) = trunc(62.0) = 62<br>remainder = 7068 - (62 * 114) = 7068 - 7068 = 0</pre><p>This divides exactly. 62 = <strong>0x3E</strong>, which fits comfortably in a signed byte, so no #DE fault.</p><p><strong>AL = </strong><strong>0x3E</strong></p><h3>Part 5. Complete code of idiv_calculator.py</h3><pre>import math<br><br>def idiv(dividend_reg, divisor_reg):<br>    &quot;&quot;&quot;<br>    Simulate Intel idiv for all four forms:<br>      r/m8  : AX       ÷ r/m8  → AL=quotient, AH=remainder<br>      r/m16 : DX:AX    ÷ r/m16 → AX=quotient, DX=remainder<br>      r/m32 : EDX:EAX  ÷ r/m32 → EAX=quotient, EDX=remainder<br>      r/m64 : RDX:RAX  ÷ r/m64 → RAX=quotient, RDX=remainder<br><br>    dividend_reg: dict with relevant register values (unsigned)<br>      r/m8  → {&#39;ax&#39;: ...}<br>      r/m16 → {&#39;dx&#39;: ..., &#39;ax&#39;: ...}<br>      r/m32 → {&#39;edx&#39;: ..., &#39;eax&#39;: ...}<br>      r/m64 → {&#39;rdx&#39;: ..., &#39;rax&#39;: ...}<br>    divisor_reg: unsigned integer value of the divisor operand<br>    &quot;&quot;&quot;<br><br>    if &#39;ax&#39; in dividend_reg and len(dividend_reg) == 1:<br>        # --- r/m8 form: AX ÷ r/m8 ---<br>        ax = dividend_reg[&#39;ax&#39;]<br>        dividend = ax if ax &lt; 0x8000 else ax - 0x10000<br>        divisor  = divisor_reg if divisor_reg &lt; 0x80 else divisor_reg - 0x100<br>        q_bits, r_bits = 8, 8<br>        q_range  = (-128, 127)<br>        q_mask, r_mask = 0xFF, 0xFF<br>        label_q, label_r = &#39;AL&#39;, &#39;AH&#39;<br>        print(f&quot;  Form     : AX ÷ r/m8&quot;)<br>        print(f&quot;  AX       : {ax:#06x}  → dividend {dividend}&quot;)<br><br>    elif &#39;dx&#39; in dividend_reg and &#39;ax&#39; in dividend_reg:<br>        # --- r/m16 form: DX:AX ÷ r/m16 ---<br>        dx = dividend_reg[&#39;dx&#39;]<br>        ax = dividend_reg[&#39;ax&#39;]<br>        combined = (dx &lt;&lt; 16) | ax          # unsigned 32-bit DX:AX<br>        dividend = combined if combined &lt; 0x80000000 else combined - 0x100000000<br>        divisor  = divisor_reg if divisor_reg &lt; 0x8000 else divisor_reg - 0x10000<br>        q_range  = (-32768, 32767)<br>        q_mask, r_mask = 0xFFFF, 0xFFFF<br>        label_q, label_r = &#39;AX&#39;, &#39;DX&#39;<br>        print(f&quot;  Form     : DX:AX ÷ r/m16&quot;)<br>        print(f&quot;  DX:AX    : {dx:#06x}:{ax:#06x}  → dividend {dividend}&quot;)<br><br>    elif &#39;edx&#39; in dividend_reg and &#39;eax&#39; in dividend_reg:<br>        # --- r/m32 form: EDX:EAX ÷ r/m32 ---<br>        edx = dividend_reg[&#39;edx&#39;]<br>        eax = dividend_reg[&#39;eax&#39;]<br>        combined = (edx &lt;&lt; 32) | eax        # unsigned 64-bit EDX:EAX<br>        dividend = combined if combined &lt; 0x8000000000000000 else combined - 0x10000000000000000<br>        divisor  = divisor_reg if divisor_reg &lt; 0x80000000 else divisor_reg - 0x100000000<br>        q_range  = (-2147483648, 2147483647)<br>        q_mask, r_mask = 0xFFFFFFFF, 0xFFFFFFFF<br>        label_q, label_r = &#39;EAX&#39;, &#39;EDX&#39;<br>        print(f&quot;  Form     : EDX:EAX ÷ r/m32&quot;)<br>        print(f&quot;  EDX:EAX  : {edx:#010x}:{eax:#010x}  → dividend {dividend}&quot;)<br><br>    elif &#39;rdx&#39; in dividend_reg and &#39;rax&#39; in dividend_reg:<br>        # --- r/m64 form: RDX:RAX ÷ r/m64 ---<br>        rdx = dividend_reg[&#39;rdx&#39;]<br>        rax = dividend_reg[&#39;rax&#39;]<br>        combined = (rdx &lt;&lt; 64) | rax        # unsigned 128-bit RDX:RAX<br>        half = 1 &lt;&lt; 127<br>        dividend = combined if combined &lt; half else combined - (1 &lt;&lt; 128)<br>        divisor  = divisor_reg if divisor_reg &lt; 0x8000000000000000 else divisor_reg - 0x10000000000000000<br>        q_range  = (-(1 &lt;&lt; 63), (1 &lt;&lt; 63) - 1)<br>        q_mask, r_mask = 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF<br>        label_q, label_r = &#39;RAX&#39;, &#39;RDX&#39;<br>        print(f&quot;  Form     : RDX:RAX ÷ r/m64&quot;)<br>        print(f&quot;  RDX:RAX  : {rdx:#018x}:{rax:#018x}  → dividend {dividend}&quot;)<br><br>    else:<br>        raise ValueError(&quot;Unrecognised dividend_reg keys. Expected ax | (dx,ax) | (edx,eax) | (rdx,rax)&quot;)<br><br>    # Truncate toward zero — matches Intel idiv behaviour<br>    quotient  = math.trunc(dividend / divisor)<br>    remainder = dividend - quotient * divisor<br><br>    q_out = quotient  &amp; q_mask<br>    r_out = remainder &amp; r_mask<br><br>    print(f&quot;  divisor  : {divisor} ({divisor_reg:#x})&quot;)<br>    print(f&quot;  quotient : {quotient}  →  {label_q} = {q_out:#x}&quot;)<br>    print(f&quot;  remainder: {remainder}  →  {label_r} = {r_out:#x}&quot;)<br><br>    if not (q_range[0] &lt;= quotient &lt;= q_range[1]):<br>        print(f&quot;  WARNING: quotient {quotient} overflows {label_q} range {q_range} — #DE fault on real hardware&quot;)<br><br>    return q_out, r_out<br><br><br># --- Examples ---<br><br>print(&quot;=== r/m8: AX ÷ r11b ===&quot;)<br>idiv({&#39;ax&#39;: 0x7783}, 0xD3)<br><br>print(&quot;\n=== r/m8: AX ÷ dil ===&quot;)<br>idiv({&#39;ax&#39;: 0x1B9C}, 0x72)<br><br>print(&quot;\n=== r/m8: AX ÷ r11b ===&quot;)<br>idiv({&#39;ax&#39;: 0x2545}, 0xCB)<br><br>print(&quot;\n=== r/m8: AX ÷ r8b ===&quot;)<br>idiv({&#39;ax&#39;: 0x1086}, 0x5A)<br><br>print(&quot;\n=== r/m16: DX:AX ÷ r/m16 ===&quot;)<br>idiv({&#39;dx&#39;: 0x0000, &#39;ax&#39;: 0x1B9C}, 0x0072)<br><br>print(&quot;\n=== r/m32: EDX:EAX ÷ r/m32 ===&quot;)<br>idiv({&#39;edx&#39;: 0x00000000, &#39;eax&#39;: 0x12345678}, 0x00001234)<br><br>print(&quot;\n=== r/m64: RDX:RAX ÷ r/m64 ===&quot;)<br>idiv({&#39;rdx&#39;: 0x0000000000000000, &#39;rax&#39;: 0xDEADBEEFCAFEBABE}, 0x00000000CAFEBABE)<br><br>print(&quot;&quot;)<br>idiv({&#39;ax&#39;: 0x1086}, 0x5A)<br><br></pre><h3>Design Thinking &amp; Code Walkthrough</h3><h3>Step 1: What problem are we actually modelling?</h3><p>Before writing anything, the question is: what does idiv actually do at the hardware level?</p><p>Intel’s manual gives four forms, differentiated purely by the width of the divisor operand:</p><p>Divisor width Dividend source Quotient Remainder r/m8 AX (16-bit) AL AH r/m16 DX:AX (32-bit) AX DX r/m32 EDX:EAX (64-bit) EAX EDX r/m64 RDX:RAX (128-bit) RAX RDX</p><p>The divisor width is the only input you need to determine everything else. That is the core design insight: <strong>one function, dispatch on width</strong>.</p><h3>Step 2: What are the tricky parts before writing a single line?</h3><p>Three problems need solving before touching code:</p><p><strong>Problem 1: Sign extension.</strong> The registers hold raw unsigned bit patterns. idiv treats them as signed. So 0xD3 in an 8-bit register is not 211 — it is -45. The code must reinterpret unsigned inputs as signed before doing arithmetic.</p><p><strong>Problem 2: Wide dividends.</strong> For r/m16 and above, the dividend is not a single register — it is a concatenated pair. DX:AX means DX is the high half and AX is the low half, forming a single 32-bit value. The code must reconstruct that combined value first, then sign-extend the whole thing.</p><p><strong>Problem 3: Truncation direction.</strong> Python’s // operator floors toward negative infinity. Intel idiv truncates toward zero. These differ for negative results:</p><pre>-7 // 2  = -4   (Python floor)<br>trunc(-7 / 2) = -3   (Intel idiv)</pre><p>So math.trunc is mandatory, not //.</p><h3>Step 3: First draft — r/m8 only</h3><p>Start with just the 8-bit case to get the pattern right:</p><pre>def idiv_r8(ax, r8):<br>    dividend = ax if ax &lt; 0x8000 else ax - 0x10000<br>    divisor  = r8 if r8 &lt; 0x80  else r8 - 0x100<br>    quotient  = math.trunc(dividend / divisor)<br>    remainder = dividend - quotient * divisor<br>    return quotient &amp; 0xFF, remainder &amp; 0xFF</pre><p>This works but only handles one form. The structure is right: sign-extend inputs, divide with truncation, mask output to register width.</p><h3>Step 4: Generalise — how to dispatch?</h3><p>The divisor width determines the form. But the function receives a raw integer for the divisor, not a typed register. So how does the function know which form to use?</p><p>The answer is to use the <strong>dividend register dict</strong> as the discriminator. The keys tell you which registers are loaded:</p><pre>{&#39;ax&#39;: ...}              → r/m8  (AX is the full dividend)<br>{&#39;dx&#39;: ..., &#39;ax&#39;: ...}   → r/m16 (DX:AX concatenated)<br>{&#39;edx&#39;: ..., &#39;eax&#39;: ...} → r/m32<br>{&#39;rdx&#39;: ..., &#39;rax&#39;: ...} → r/m64</pre><p>This mirrors how you would write the assembly: the registers you load before calling idiv define the form. The dict keys are just a Python-level encoding of that.</p><h3>Step 5: Wide dividend reconstruction</h3><p>For r/m16, DX:AX is a 32-bit value where DX is the upper 16 bits:</p><pre>combined = (dx &lt;&lt; 16) | ax</pre><p>Then sign-extend the combined value as a 32-bit integer:</p><pre>dividend = combined if combined &lt; 0x80000000 else combined - 0x100000000</pre><p>The same pattern scales to r/m32 (shift by 32, threshold 0x8000000000000000) and r/m64 (shift by 64, threshold 1 &lt;&lt; 127). The r/m64 case uses Python&#39;s arbitrary-precision integers — no overflow risk.</p><h3>Step 6: Output masking</h3><p>After division, the quotient may be a large negative Python integer. We need the bit pattern as it would appear in the destination register. &amp; 0xFF gives the low 8 bits regardless of sign:</p><pre>-679 &amp; 0xFF  = 0x59</pre><p>This is correct — it is exactly what the CPU does when it writes the low byte of a two’s complement value into AL.</p><h3>Step 7: Overflow detection</h3><p>Real hardware raises #DE if the quotient does not fit in the destination register. The check is just a range test against the signed range of the output register:</p><pre>r/m8  → (-128, 127)<br>r/m16 → (-32768, 32767)<br>r/m32 → (-2147483648, 2147483647)<br>r/m64 → (-(1 &lt;&lt; 63), (1 &lt;&lt; 63) - 1)</pre><p>This is checked on the <strong>unmasked</strong> quotient — before the &amp; mask — because masking discards the overflow information.</p><h3>Step 8: Final structure</h3><p>Putting it together, each branch of the dispatch does the same five things:</p><ol><li>Extract register values from the dict</li><li>Reconstruct the combined dividend (concatenate for wide forms)</li><li>Sign-extend dividend and divisor</li><li>Set form-specific constants (range, masks, output register labels)</li><li>Fall through to shared division, masking, printing, and overflow check</li></ol><p>The division logic itself is not repeated — it lives once after all the branches:</p><pre>quotient  = math.trunc(dividend / divisor)<br>remainder = dividend - quotient * divisor<br>q_out = quotient  &amp; q_mask<br>r_out = remainder &amp; r_mask</pre><p>This is the correct factoring: the branching sets up parameters, the shared tail does the arithmetic.</p><h3>What would be improved in a next iteration</h3><p>The math.trunc(dividend / divisor) line has a subtle risk for very large 128-bit values: Python float division loses precision beyond ~53 bits. The correct fix for r/m64 is integer truncating division:</p><pre>import math<br>quotient = math.trunc(dividend / divisor)   # risky for 128-bit<br># safer:<br>sign = -1 if (dividend &lt; 0) != (divisor &lt; 0) else 1<br>quotient = sign * (abs(dividend) // abs(divisor))</pre><p>This uses integer arithmetic throughout and applies the sign rule explicitly, eliminating floating-point precision loss entirely. It should replace the float division in all branches, not just r/m64.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1864d6d3c3ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/reverse-engineering-mul-imul-div-and-idiv-1864d6d3c3ea">Reverse Engineering: mul, imul, div and idiv</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unsigned and signed JMP, ASLR, condition in assmebly]]></title>
            <link>https://medium.com/re-exploit/unsigned-and-signed-jmp-aslr-condition-in-assmebly-e0d0a1358ac1?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/e0d0a1358ac1</guid>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[jmp-pattern]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[aslr]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 21:48:19 GMT</pubDate>
            <atom:updated>2026-03-25T21:48:19.341Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1. (Un)signed Jump Pattern — if</h3><h4>1.1 IfExample2.c</h4><pre>// This Source Code is from<br>// https://gitlab.com/opensecuritytraining/arch1001_x86-64_asm_code_for_class/-/blob/master/IfExample2/IfExample2.c?ref_type=heads<br><br>int main() {<br> unsigned int a = -1, b = 2;<br> if (a == b) {<br>  return 1;<br> }<br> if (a &gt; b) {<br>  return 2;<br> }<br> if (a &lt; b) {<br>  return 3;<br> }<br> return 0xdefea7ed;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-yOiBSW8wxtl0LUtEf44A.png" /></figure><p><strong>Condition → Jump pattern</strong></p><p>Every if block in the disassembly follows the same two-instruction idiom:</p><pre>cmp  dst, src       ; sets flags based on dst - src<br>jcc  &lt;skip target&gt;  ; jumps OVER the body if condition is FALSE</pre><p>The jump is always the <em>inverse</em> of the source-level condition. If the C says if (a == b), the compiler emits jne — jump away if <em>not</em> equal, skipping the body. The body only executes when the jump is <em>not</em> taken.</p><p><strong>Why inverse?</strong></p><p>The compiler generates fall-through code. The “happy path” body sits immediately after the cmp/jcc pair. The jump exists only to escape it. So the emitted condition is always the negation of what the source says.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*ezLuEu4aaQ032_I-2FF23w.png" /></figure><p><strong>The full pattern in IfExample2</strong></p><p>Each branch follows the same skeleton:</p><pre>mov   eax, [rsp]          ; load one operand into register<br>cmp   [rsp+4], eax        ; compare against the other<br>jcc   &lt;next_block&gt;        ; skip body if condition false<br>mov   eax, &lt;return val&gt;   ; body: set return value<br>jmp   &lt;epilogue&gt;          ; exit function</pre><p>The final jmp to the epilogue is the compiled form of return — once a branch is taken, the remaining if blocks must be bypassed.</p><p><strong>Key RE takeaway</strong></p><p>When you see a cmp followed immediately by a jcc, read the Jcc mnemonic, invert it, and that gives you the source-level condition. The signedness is encoded in the mnemonic choice — A/B for unsigned, G/L for signed — which tells you something about the original variable types even without source.</p><p>This pattern is stable across MSVC and Clang/GCC and appears identically in Rust binaries, including inside match arms and if let discriminant checks on Result/Option variants.</p><h4>1.2 IfExample.c</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaRVgoTg0u6Jlk0RdRb84g.png" /></figure><pre>// This Source Code is from<br>// https://gitlab.com/opensecuritytraining/arch1001_x86-64_asm_code_for_class/-/blob/master/IfExample/IfExample.c?ref_type=heads<br><br>int main(){<br> int a = -1, b = 2;<br> if(a == b){<br>  return 1;<br> }<br> if(a &gt; b){<br>  return 2;<br> }<br> if(a &lt; b){<br>  return 3;<br> }<br> return 0xdefea7;<br>}</pre><p>This is IfExample.exe (signed int) vs the previous IfExample2.exe (unsigned int). Diffing the two:</p><p><strong>Jcc differences</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*ZkW9YroTc7ResQc_4cAimQ.png" /></figure><p>jne is identical in both: equality is sign-agnostic, it only checks ZF.</p><p><strong>What else changed</strong></p><p>The initialisation. In IfExample2, a = -1 was stored as 0FFFFFFFFh. Here in the signed version, the disassembly shows int a = -1, b = 2 with the same mov dword ptr [rsp+4], 0FFFFFFFFh, the bit pattern is identical. The difference is purely in how the compiler <em>interprets</em> that pattern when generating the comparison, which is reflected solely in the Jcc choice.</p><p><strong>RE implication</strong></p><p>The bit pattern in memory is the same. You cannot tell signedness from the stored value alone. The Jcc mnemonic is your only reliable indicator of what the compiler believed the type was. This is directly useful for Rust RE, Rust’s type system is strict about signedness, so jle/jge in a comparison context tells you the operand was i32/i64, while jbe/jae tells you u32/u64. That narrows type recovery during binary analysis without needing debug symbols.</p><h4>1.3 <strong>The hardware is sign-agnostic</strong></h4><p>cmp always performs the same subtraction regardless of type. After cmp [rsp+4], eax with operands 0xFFFFFFFF and 0x00000002, the CPU sets <em>all</em> relevant flags simultaneously:</p><ul><li>CF = 1 (unsigned borrow occurred — 0xFFFFFFFF - 2 wraps... actually no, 0xFFFFFFFF &gt; 2 unsigned so CF = 0 here)</li><li>SF and OF are set according to the signed interpretation</li><li>ZF reflects whether the result was zero</li></ul><p>The CPU does not choose between signed and unsigned. It sets every flag, covering both interpretations at once. The bits are just bits to the hardware.</p><p><strong>The compiler is where signedness lives</strong></p><p>The type information exists only at compile time. When the compiler sees unsigned int a, it emits jbe/jaeJcc variants that read CF. When it sees int a, it emits jle/jge variants that read SF and OF together. Same cmp instruction either way. Different Jcc picks a different subset of the flags that were already set.</p><p><strong>The RE implication, stated precisely</strong></p><p>Since the hardware sets all flags on every arithmetic operation, the <em>only</em> place signedness is recorded in a compiled binary is in the Jcc mnemonic choice. There is no other artefact. The operand bit patterns are identical, the cmp encoding is identical, the flag register state after cmp is identical. Only the subsequent jump instruction differs.</p><p>This is why the Jcc is such a reliable type recovery signal in binary analysis: it is the sole surviving artefact of a compile-time type decision.</p><h3>Part 2. Switch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRz4VwmJZdIE9sOzkNs10w.png" /></figure><pre>// This Source Code is from<br>// https://gitlab.com/opensecuritytraining/arch1001_x86-64_asm_code_for_class/-/blob/master/SwitchExample/SwitchExample.c?ref_type=heads<br><br>#include &lt;stdlib.h&gt;<br>int main(int argc, char* argv[]) {<br>    int a = atoi(argv[1]);<br>    switch (a) {<br>    case 0:<br>        return 1;<br>    case 1:<br>        return 2;<br>    default:<br>        return 3;<br>    }<br>    return 0xfee1fed;<br>}</pre><p><strong>Disassembly</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*B9XbL2BCneEWzVf9DsxeLA.png" /></figure><blockquote>Note: The instruction at 0x14000101F is an<strong> indirect call</strong> through the<strong> Import Address Table (IAT).</strong> Rather than encoding the address of atoi directly in the call instruction, the compiler emits a call to a fixed memory slot. At load time, the Windows loader patches that slot with the actual runtime address of atoi from msvcrt.dll (or whichever CRT the binary links against).</blockquote><p><strong>What this demonstrates</strong></p><p>For a small, dense switch with only two cases, MSVC compiles it as a simple cmp/je chain — structurally identical to chained if/else. This is called a <em>linear scan</em> implementation.</p><p>The interesting contrast is what MSVC does with larger switches — once the case count crosses a threshold (typically around 4–5 cases), the compiler switches to a <em>jump table</em>: a contiguous array of target addresses indexed by (a - min_case), accessed via jmp qword ptr [rax*8 + table_base]. That produces a near absolute indirect jmp — exactly the form Xeno listed in the JMP slides.</p><p><strong>RE identification heuristic</strong></p><p>Linear scan: multiple cmp reg, imm + je pairs in sequence, one per case. Jump table: a bounds check (cmp/ja to default), then jmp [reg*8 + base]. Both patterns appear in Rust match expressions — Rust&#39;s match compiles to whichever form the backend deems optimal for the number and density of arms.</p><h3><strong>2.2 ASLR — Address Space Layout Randomisation</strong></h3><p>Every time Windows loads a DLL (or the executable itself, if it has the DYNAMIC_BASE PE flag set), the loader maps it at a randomly chosen base address rather than a fixed one. The randomisation happens at load time, per-boot on older Windows, per-load on modern Windows with high-entropy ASLR.</p><p><strong>What this means for a </strong><strong>call to </strong><strong>atoi</strong></p><p>At compile time, the compiler knows atoi lives somewhere in the CRT DLL, but cannot know <em>where</em> that DLL will be mapped. If it tried to encode the absolute address directly in the call instruction, that address would be wrong on every machine and every run.</p><p>The IAT solves this. The PE image contains a reserved table of pointer-sized slots, one per imported function. The compiler encodes a call to the <em>slot address</em>, which is at a fixed offset within the PE image itself (and therefore has a known RVA). At load time, the loader:</p><ol><li>Maps the imported DLL at its randomised base</li><li>Resolves the actual runtime address of each imported function</li><li>Writes those addresses into the IAT slots before execution begins</li></ol><p>So call qword ptr [0x140004178] always hits the same slot in the image, and that slot always contains the correct atoi address for that run.</p><p><strong>RE implication</strong></p><p>When you see an indirect call through a pointer-sized memory operand at a high fixed address, it is almost certainly an IAT call. The slot address does not change between runs — only its contents do. This is why static analysis of the PE import directory reliably enumerates a binary&#39;s external API surface without needing to run it, and why import-based YARA rules are stable across ASLR-randomised loads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0d0a1358ac1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/unsigned-and-signed-jmp-aslr-condition-in-assmebly-e0d0a1358ac1">Unsigned and signed JMP, ASLR, condition in assmebly</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Reverse Engineering Vol. 7: LEA, IAT in Two Examples]]></title>
            <link>https://medium.com/re-exploit/basic-reverse-engineering-vol-7-lea-iat-in-two-examples-90188c007469?source=rss----1c237f011383---4</link>
            <guid isPermaLink="false">https://medium.com/p/90188c007469</guid>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[x86-64]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <dc:creator><![CDATA[Yen Wang]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 21:28:23 GMT</pubDate>
            <atom:updated>2026-03-20T12:36:39.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*TVpJInL9yNB2ADj9vOq6AA.png" /></figure><blockquote>This is a learning note based on amazing online course of <a href="https://medium.com/medium.com/p/90188c007469/edithttps://apps.p.ost2.fyi/learning/course/course-v1:OpenSecurityTraining2+Arch1001_x86-64_Asm+2021_v1/">OST2</a><a href="https://medium.com/p/90188c007469/medium.com/p/90188c007469/edithttps://apps.p.ost2.fyi/learning/course/course-v1:OpenSecurityTraining2+Arch1001_x86-64_Asm+2021_v1/">: Arch1001 Architecture 1001: x86–64 Assembly</a>.</blockquote><h3>Table of Contents</h3><ul><li>Part 1. Simple atoi and LEA</li><li>Part 2. Helloworld.c and IAT</li></ul><h3>Part 1. Simple atoi and LEA</h3><pre>// This Source Code from OpenSecurityTraining2 (OST2) -<br>// Arch1001 Architecture 1001: x86-64 Assembly<br>// https://gitlab.com/opensecuritytraining/arch1001_x86-64_asm_code_for_class/-/blob/master/SpecialMaths/SpecialMaths.c?ref_type=heads<br><br>#include &lt;stdlib.h&gt;<br><br>int main(int argc, char** argv) {<br>    int a;<br>    //reminder: atoi() converts an<br>    //ASCII string to an integer<br>    a = atoi(argv[1]);<br>    return 2 * argc + a;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7WDc8gGT9jtSnNQ3dyUFQ.png" /></figure><p>The function is main(int argc, char** argv) compiled as MSVC x64 debug. RIP is at 0x140001009 (the sub rsp,38h prologue execution is paused at line 8, before a = atoi(argv[1])).</p><h3>1.1 Disassembly walkthrough</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*pcW4QxVkO-GqZQfrQaNrTg.png" /></figure><p>Then the return expression 2 * argc + a:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*7rFN_iV-TQ9SqlMz0ejfjg.png" /></figure><h3>1.2 How argv and atoi reach the instructions they do</h3><p><strong>argv at </strong><strong>[rsp+48h]</strong></p><p>On entry to main, the Windows x64 ABI places argc in rcx and argv in rdx. The CRT caller owns the shadow space immediately above main&#39;s return address, which from main&#39;s perspective sits at [rsp+8] through [rsp+20h] before the prologue runs. After sub rsp,38h shifts the stack pointer down by 0x38, those same slots appear at [rsp+40h] through [rsp+58h]. argv was the second parameter (rdx), so its shadow slot lands at rsp+48h (0x10 + 0x38).</p><p>MSVC debug builds spill every parameter to its shadow slot in the function prologue. The reload at 0x140001016 is therefore not redundant: it reads argv back from that spill location so the subsequent dereference has a stable, debugger-visible source.</p><p><strong>argv[1] via </strong><strong>[rcx+rax]</strong></p><p>After the lea loads argv into rcx, the instruction at 0x14000101B executes mov rcx, qword ptr [rcx+rax]. This dereferences a pointer-sized element of the char* array at byte offset rax from the base address in rcx.</p><p>The preceding imul rax,rax,1 is a MSVC debug-mode artefact. In a debug build, the compiler materialises index expressions as explicit register values so they are visible to the debugger and inspectable as named temporaries, even when the multiplication is trivially by 1. At the point this instruction executes during normal program flow, rax holds the array index 1, making the effective address argv + 1*8 = argv[1].</p><p>The Autos pane showing RAX = 2 at the debugger pause point does not contradict this. The debugger is stopped at the sub rsp,28h prologue, before the index computation runs. rax at that moment reflects whatever the CRT left in it prior to the call main, which is unrelated to the index. The value 2 is CRT state, not the array index.</p><p>The result of the dereference is the char* pointer to the string argv[1], which lands in rcx ready to pass to atoi as its first argument.</p><p><strong>atoi via IAT indirect call</strong></p><p>The call at 0x14000101F takes the form call qword ptr [000000014004178h]. The linker does not know the runtime address of atoi in msvcrt.dll at build time, so it emits an indirect call through a fixed slot in the Import Address Table. At load time, the PE loader resolves msvcrt.dll!atoi, writes its virtual address into [14004178h], and every subsequent call dereferences that slot transparently. The return value arrives in eax per the Windows x64 integer return convention and is immediately written to [rsp+20h] as local variable a.</p><p><strong>lea eax, [rax+rcx*2] for </strong><strong>2 * argc + a</strong></p><p>The compiler implements return 2 * argc + a as a single lea instruction. With rax holding a and rcx holding argc, the SIB encoding of [rax+rcx*2] computes a + argc*2 in one cycle, writing the result to eax without needing a separate imul or add.</p><h3>1.3 The Import Address Table (IAT)</h3><p><strong>The Import Address Table</strong> (IAT) is a pointer array embedded in a PE binary that the Windows loader populates at process load time with the resolved virtual addresses of all imported functions.</p><p><strong>How it works</strong></p><p>When the linker encounters an external symbol such as atoi, it cannot embed the final address because that address is determined by where msvcrt.dll is mapped at runtime. Instead it reserves a slot in the IAT and emits an indirect call:</p><pre>call qword ptr [14004178h]   ; slot filled by loader with &amp;msvcrt!atoi  </pre><p>At load time the PE loader walks the Import Directory, locates each named DLL and function, resolves the virtual address, and writes it into the corresponding IAT slot. From that point every indirect call dereferences the correct target.</p><p><strong>Relevant PE structures</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*8ASUFSsnjQf-0uRj9l9Rmg.png" /></figure><p><strong>Why it matters for reverse engineering and malware detection</strong></p><p>The IAT is one of the first analysis targets when examining an unknown binary. The import listing is a direct capability fingerprint: the presence of VirtualAlloc, WriteProcessMemory, and CreateRemoteThread together is a strong indicator of process injection. IAT hooking is a standard user-mode rootkit technique where a slot such as NtOpenProcess is overwritten with a trampoline address to intercept all callers transparently.</p><p>Packers and Rust-based malware frequently strip or stub the IAT to defeat static analysis, resolving imports at runtime through GetProcAddress instead. This leaves the IAT sparse or empty before the unpacking stub runs, which is itself a detectable signal.</p><p>In Binary Ninja, resolved IAT slots appear as named symbols (for example __imp_atoi), so indirect calls are annotated automatically. A binary where most calls remain as raw addresses rather than named imports is a strong indicator of deliberate import obfuscation.</p><p><strong>Rust-specific note</strong></p><p>Rust statically links the majority of its runtime, so the IAT of a Rust binary is considerably smaller than an equivalent C or C++ binary. Fewer msvcrt entries appear, and much of the call graph consists of direct calls into monomorphised code within the binary itself. For detection purposes this means import-based heuristics are less effective against Rust malware, reinforcing the need for structural and bytecode-level signatures.</p><h4>Turn on “Symbols Names” in Assembly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1Fn2VTYea-F7-GYeuHPRig.png" /></figure><p>The disassembly now shows symbol-decorated operands instead of raw addresses. The two differences from the earlier view:</p><p><strong>lea rcx, [__NULL_IMPORT_DESCRIPTOR+15A0h (0140006000h)]</strong></p><p>Binary Ninja (and VS) resolve the address 0x140006000 relative to the nearest known symbol in the binary. __NULL_IMPORT_DESCRIPTOR is a linker-generated sentinel marking the end of the import descriptor table in .idata. The string literal happens to sit 0x15A0 bytes past that symbol, so the debugger expresses the address as __NULL_IMPORT_DESCRIPTOR + 15A0h with the absolute address in parentheses for confirmation. The instruction itself is identical — it still loads 0x140006000 into rcx. The symbol decoration is purely a debugger display convenience.</p><p><strong>call printf (0140001080h)</strong></p><p>Previously this showed as call 000000014001080. Now that symbols are loaded, VS resolves 0x140001080 to the CRT import stub named printf. The parenthesised address confirms the stub&#39;s location in the binary. This is the same indirect path to msvcrt!printf as before — the symbol name just makes the call target immediately readable without cross-referencing the IAT manually.</p><h3>A brief summary</h3><p><strong>The practical takeaway for RE work</strong>: symbol names are a display layer over the same raw addresses. When symbols are stripped (as they are in most malware), you fall back to the raw address view you had earlier and must recover meaning from context, which is exactly why understanding what the raw addresses refer to (IAT slots, .rdata string literals, linker sentinels) matters for analysis.</p><h3>Part 2. Helloworld.c and IAT</h3><blockquote>Link to OST Gitlab: <a href="https://gitlab.com/opensecuritytraining/arch1001_x86-64_asm_code_for_class/-/tree/master/HelloWorld?ref_type=heads">https://gitlab.com/opensecuritytraining/arch1001_x86-64_asm_code_for_class/-/tree/master/HelloWorld?ref_type=heads</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nf0qzloddt-B3v-WYUGaCQ.png" /></figure><h3>2.1 HelloWorld.exe Assembly Walkthrough</h3><p><strong>State at pause:</strong> RIP = 0x140001000, RSP = 0x14FE08, stopped at the opening { of main() (line 8), before any instructions execute.</p><h4>Disassembly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*ZOsp7-4GAIrtgmRSoQE7zQ.png" /></figure><h4>Frame layout</h4><p>sub rsp,28h allocates 0x28 = 40 bytes. There are no local variables here, so the entire frame is shadow space (32 bytes) plus 8 bytes of alignment padding to maintain the 16-byte stack alignment required by the ABI before the call to printf.</p><pre>Address                 │ Content<br>────────────────────────┼──────────────────────────────────<br> 00000000`0014FE08      │ [RETURN] return address (CRT → main)      ← RSP on entry<br>────────────────────────┼──────────────────────────────────<br> 00000000`0014FE00      │ [PADDING] 8-byte alignment pad<br> 00000000`0014FDF8      │ shadow slot 4 (unused)<br> 00000000`0014FDF0      │ shadow slot 3 (unused)                     main() frame<br> 00000000`0014FDE8      │ shadow slot 2 (unused)<br> 00000000`0014FDE0      │ shadow slot 1 (unused)                    ← RSP(main) after sub rsp,28h</pre><h4>Key points</h4><p>1.<strong>lea rcx, [14006000h] instead of </strong><strong>mov</strong></p><p>printf&#39;s first argument is a const char*. The string literal &quot;Hello World!\n&quot; lives in .rdata at 0x14006000. lea loads the address of that location rather than its contents, which is correct: printf receives a pointer, not the string data itself.</p><p><strong>2. Direct call vs IAT indirect</strong></p><p>Unlike atoi in the previous example, this call targets a fixed address (0x14001080) rather than an IAT slot. That address is the CRT import stub compiled into the binary. Depending on the build, MSVC may emit either form; both ultimately reach printf in msvcrt.dll.</p><p><strong>mov eax, 1234h for </strong><strong>return 0x1234</strong></p><p>Integer return values go in eax (32-bit) per the Windows x64 ABI. The compiler emits a direct mov with the constant since this is a compile-time-known value. No computation needed.</p><p><strong>3. No parameter spilling</strong></p><p>main() here is declared as main() with no parameters, so there is nothing to spill into shadow space. The four shadow slots are allocated but left uninitialised, which is normal: the callee (here, main) owns the shadow space but is not required to use it.</p><p><strong>AL = 02, </strong><strong>RAX = 2 in Autos</strong></p><p>These reflect the state of rax at the current pause point (entry to main), carried over from whatever the CRT did before the call. They are not meaningful for this function&#39;s logic.</p><p><strong>4. Memory Inspection</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*BM2PQ-RH5lk-8B5Bg-VsuQ.png" /></figure><pre>Address           │ Raw qword         │ ASCII<br>──────────────────┼───────────────────┼──────────────<br>0x140006000       │ 6c6c6548          │ Hell<br>0x140006004       │ 6f57206f          │ o Wo<br>0x140006008       │ 21646c72          │ rld!</pre><p>0x140006000 holds the first 4 bytes: 48 65 6c 6c = Hell.</p><ul><li>The string spans three rows, starting at 0x140006000 and ending with ! at 0x14000600B, followed by 0a 00 (newline + null terminator) at 0x14000600C and 0x14000600D.</li><li>0x14000600C = 0a 00 00 00. The 0a is \n and the 00 immediately after it at 0x14000600D (the second byte inside the 0x14000600C row) is the null terminator. They are in the same 4-byte word, which is why you only see one row rather than two separate entries. The null terminator is not on its own line because it shares a display unit with the newline byte.</li></ul><h3>2.2 Relative Virtual Address (RVA)</h3><p><strong>RVA</strong> = Relative Virtual Address. An offset from the image base, rather than an absolute virtual address. The PE format uses RVAs internally so the binary can be loaded at any base address without the on-disk structures needing patching.</p><p><strong>Before loading: hint/name RVAs</strong></p><p>The on-disk IAT slots contain RVAs pointing into the Import Hint/Name Table. Each entry there is a small structure:</p><pre>WORD  Hint;       // index into the export name table of the target DLL (a guess to speed lookup)<br>CHAR  Name[];     // null-terminated function name, e.g. &quot;atoi&quot;</pre><p>So before the loader runs, [14004178h] does not hold a callable address. It holds an RVA that points to a structure saying &quot;I want the function named atoi&quot;.</p><p><strong>After loading: resolved VAs</strong></p><p>The loader walks the Import Directory, opens each required DLL, finds the exported function by name (using the hint as a shortcut), gets its absolute virtual address in the mapped DLL, and overwrites the IAT slot with that VA. After this point [14004178h] holds something like 0x7FFE&#39;A3C12040, the actual address of msvcrt!atoi in memory.</p><p>The INT (Import Name Table) is a parallel array with identical on-disk content to the IAT. The loader reads from the INT and writes into the IAT, leaving the INT untouched. This means you can always recover the original import names from the INT even after the IAT has been overwritten, which is useful when analysing a running process.</p><p><strong>Why this matters for malware analysis</strong></p><p>A packer or Rust malware sample may zero or stub the IAT before execution, then rebuild it at runtime via GetProcAddress. At that point the IAT slots contain resolved VAs placed there by the malware&#39;s own loader stub rather than by Windows. The INT, if preserved, still shows the original import names. If the INT is also wiped, static import recovery requires either emulation or a memory dump after the unpacking stub completes.</p><h3>2.3 HelloWorld.exe — annotated assembly with symbols</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upQSkw4qwMevxgYa0VflrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*B_kWGW9HgBfcfduAU5SVbA.png" /></figure><h3>Prologue: sub rsp, 28h</h3><p>Allocates 0x28 = 40 bytes on the stack. The frame has no local variables, so the full 40 bytes decompose as 32 bytes of shadow space for callees (required by the Windows x64 ABI regardless of whether the callee uses it) plus 8 bytes of alignment padding. The padding ensures rsp is 16-byte aligned before the call to printf, as the ABI requires.</p><h3>Loading the string: lea rcx, [__NULL_IMPORT_DESCRIPTOR+15A0h (0140006000h)]</h3><p>printf takes a const char* as its first argument, which goes in rcx per the Windows x64 ABI. The string literal &quot;Hello World!\n&quot; is stored in .rdata at absolute address 0x140006000.</p><p>The symbol decoration __NULL_IMPORT_DESCRIPTOR+15A0h is a debugger display artefact. __NULL_IMPORT_DESCRIPTOR is a linker-generated sentinel at the end of the import descriptor table in .idata. The string happens to be 0x15A0 bytes past that symbol, so VS expresses the address relative to it. The instruction is simply loading a pointer to the string — the symbol arithmetic is not something the CPU computes at runtime.</p><p>lea is used rather than mov because printf needs the address of the string, not the string contents themselves.</p><h3>Calling printf: call printf (0140001080h)</h3><p>0x140001080 is the CRT import stub for printf compiled into the binary. With symbols loaded, VS resolves the address to the name printf directly, making the call target immediately readable. Without symbols this showed as a raw address and required cross-referencing the IAT manually to identify it.</p><p>At this point rcx = 0x140006000 (confirmed in the earlier Autos pane screenshot), so printf receives the correct pointer and will output Hello World! followed by a newline.</p><h3>Return value: mov eax, 1234h</h3><p>return 0x1234 in the source compiles to a direct mov into eax. Integer return values go in eax per the Windows x64 ABI. The compiler emits a mov with the immediate constant rather than a load because the value is known at compile time.</p><h3>Epilogue: add rsp, 28h + ret</h3><p>add rsp, 28h undoes the prologue allocation, restoring rsp to its value on entry to main. ret pops the return address (placed there by the CRT call main) into rip and transfers control back to the CRT bootstrap.</p><h3>References</h3><p>Microsoft Corporation, 2024. <em>x64 calling convention</em>. Microsoft Learn. Available at: <a href="https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention">https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention</a></p><p>Microsoft Corporation, 2024. <em>PE format</em>. Microsoft Learn. Available at: <a href="https://learn.microsoft.com/en-us/windows/win32/debug/pe-format">https://learn.microsoft.com/en-us/windows/win32/debug/pe-format</a></p><p>Pietrek, M., 1994. Peering inside the PE: a tour of the Win32 portable executable file format. <em>Microsoft Systems Journal</em>, 9(3), pp.15–38.</p><p>Fog, A., 2024. <em>Calling conventions for different C++ compilers and operating systems</em>. Copenhagen University College of Engineering. Available at: <a href="https://www.agner.org/optimize/calling_conventions.pdf">https://www.agner.org/optimize/calling_conventions.pdf</a></p><p>Kovah, X., 2023. <em>Architecture 1001: x86–64 Assembly</em> [online course]. OpenSecurityTraining2. Available at: <a href="https://ost2.fyi/Arch1001">https://ost2.fyi/Arch1001</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90188c007469" width="1" height="1" alt=""><hr><p><a href="https://medium.com/re-exploit/basic-reverse-engineering-vol-7-lea-iat-in-two-examples-90188c007469">Basic Reverse Engineering Vol. 7: LEA, IAT in Two Examples</a> was originally published in <a href="https://medium.com/re-exploit">RE: Exploit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>