<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by axhlzy on Medium]]></title>
        <description><![CDATA[Stories by axhlzy on Medium]]></description>
        <link>https://medium.com/@axhlzy?source=rss-c6c6420fe53a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LD-UVFVJjKyCja_f</url>
            <title>Stories by axhlzy on Medium</title>
            <link>https://medium.com/@axhlzy?source=rss-c6c6420fe53a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:32:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@axhlzy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From C++20 Coroutines to Unity IL2CPP Coroutines]]></title>
            <link>https://medium.com/@axhlzy/from-c-20-coroutines-to-unity-il2cpp-coroutines-20b647077c1d?source=rss-c6c6420fe53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/20b647077c1d</guid>
            <dc:creator><![CDATA[axhlzy]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 08:22:29 GMT</pubDate>
            <atom:updated>2026-10-12T08:22:29.021Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A “dig-to-the-bottom” note on exploring coroutines</em></blockquote><blockquote><em>Not content with “knowing how to use coroutines”, this goes all the way down: </em><strong><em>what does a coroutine actually compile into?</em></strong><em> Starting from the assembly and memory layout of C++20 coroutines, working step by step down to Unity’s C# coroutines — what the il2cpp tool </em><em>Convert to CPP really does under the hood</em></blockquote><blockquote><em>Hopefully by the end you’ll have a deeper understanding of coroutines</em></blockquote><h3>0. What Is a Coroutine</h3><p><strong>A coroutine is not a library, not a thread, and not a magic stack</strong> — it is a “state machine + a state number” produced by the compiler. <strong>A C++20 coroutine and a Unity C# coroutine are essentially the same thing</strong>: the compiler splits co_yield / yield return into a &quot;state machine&quot;, one case/goto per suspension point, and remembers &quot;where it was suspended&quot;.</p><h3>Part 1 · C++20 Coroutines</h3><h3>1. It’s a “language mechanism”, not a library</h3><p>C++20 gives you only three keywords:</p><ul><li>co_await: wait / suspend;</li><li>co_yield: produce a value and suspend;</li><li>co_return: finish.</li></ul><p>As for “what gets saved on suspension, who resumes, where the value goes” — all of that is decided by <strong>types you provide yourself</strong> (promise_type, awaiter). So it&#39;s zero-overhead and fully controllable, and that&#39;s also why it looks like &quot;so much boilerplate&quot;.</p><p>The plainest generator (compiled with clang++ -std=c++20):</p><pre>#include &lt;coroutine&gt;<br>#include &lt;cstdio&gt;<br>#include &lt;exception&gt;</pre><pre>struct Generator {<br>    struct promise_type {<br>        int current_value;<br>        Generator get_return_object() {<br>            return Generator{std::coroutine_handle&lt;promise_type&gt;::from_promise(*this)};<br>        }<br>        std::suspend_always initial_suspend() noexcept { return {}; }<br>        std::suspend_always final_suspend() noexcept { return {}; }<br>        void return_void() {}<br>        void unhandled_exception() { std::terminate(); }<br>        std::suspend_always yield_value(int value) { current_value = value; return {}; }<br>    };</pre><pre>std::coroutine_handle&lt;promise_type&gt; handle;<br>    explicit Generator(std::coroutine_handle&lt;promise_type&gt; h) : handle(h) {}<br>    Generator(const Generator&amp;) = delete;<br>    Generator&amp; operator=(const Generator&amp;) = delete;<br>    Generator(Generator&amp;&amp; o) noexcept : handle(o.handle) { o.handle = {}; }<br>    ~Generator() { if (handle) handle.destroy(); }</pre><pre>bool next() { handle.resume(); return !handle.done(); }   // resume + !done<br>    int value() const { return handle.promise().current_value; }<br>};</pre><pre>Generator counter(int n) { for (int i = 1; i &lt;= n; ++i) co_yield i; }</pre><pre>int main() {<br>    auto g = counter(5);<br>    while (g.next()) std::printf(&quot;value = %d\n&quot;, g.value());<br>}</pre><p><strong>Naming rules</strong>: the outer type name Generator can be whatever you like; but the nested type <strong>must be called </strong>promise_type (unless you specialize std::coroutine_traits). <strong>Member rules</strong>: get_return_object / initial_suspend / final_suspend / unhandled_exception are always required; yield_value / return_void / return_value depend on the function body.</p><h3>2. The “magic” of coroutines is just three layers: frame + state machine + yield=goto</h3><p>The C++ form above uses a lot of compiler built-ins (see libc++’s c++/v1/__coroutine/coroutine_handle.h). What follows is a more intuitive way to understand coroutines: it manually expands all the co_* into ordinary C++ (no coroutine keywords), behaving <strong>byte-for-byte identically</strong> to the original:</p><pre>struct CounterFrame {                    // ① frame: holds promise, params, locals, state number<br>    Promise      promise;<br>    SuspendAlways aw;<br>    int     n = 0, i = 0;<br>    int     state = 0;<br>    bool    done = false;</pre><pre>    void resume() {                      // ② resume: switch(state) + goto state machine<br>            switch (state) { case 0: goto start; case 1: goto resume_yield; default: return; }<br>        start:<br>            i = 1;<br>        loop:<br>            if (!(i &lt;= n)) goto end;<br>            aw = promise.yield_value(i);     // ③ co_yield i  ⇒  promise.yield_value(i)<br>            if (!aw.await_ready()) { state = 1; aw.await_suspend(); return; }  // suspend<br>        resume_yield:<br>            aw.await_resume(); ++i; goto loop;<br>        end:<br>            promise.return_void(); done = true; state = 2; return;<br>        }<br>};</pre><p><strong>No threads, no magic stack, no runtime scheduler — just a state machine.</strong> Once expanded, co_yield i is &quot;store the value + record the state + return&quot;.</p><h4>A small rule: as many suspension points (yields) as there are cases [ignoring compiler optimizations, of course]</h4><pre>for (int i = 1; i &lt;= n; ++i) co_yield i;   // only 1 co_yield in the source</pre><p>Even though it yields 5 times at runtime, the state machine <strong>needs only 1 case</strong> — it reuses the same state = 1 over and over via goto loop. <strong>Only two consecutive </strong>co_yield<strong>s produce two cases.</strong> This rule shows up again later in Unity.</p><h3>3. At the assembly level: what are the pointers in the frame?</h3><p>The pseudo-code above was only meant to show the basic concept of a state machine. Now let’s go back to the official form of the code and compile/disassemble it.</p><p>Generate assembly with clang++ -std=c++20 -O2 -S. counter(5) is compiled into three functions:</p><ul><li>_Z7counteri: the <strong>ramp</strong> (allocates the frame)</li><li>_Z7counteri.resume: the <strong>state machine</strong></li><li>_Z7counteri.destroy: <strong>destruction</strong></li></ul><p><strong>ramp — allocates the frame and fills in two function pointers</strong> (decompiled with r2; this function is <strong>only 72 bytes / 15 instructions</strong>, fully shown below, nothing omitted):</p><pre>; r2: sym.counter_int_  (counter(int))   0x15e00, 72 bytes total<br>_Z7counteri:<br>    stp  x29, x30, [sp, -0x20]!      ; prologue<br>    stp  x20, x19, [sp, 0x10]<br>    mov  x29, sp<br>    mov  w19, w0                     ; w19 = n<br>    mov  w0, 0x20                    ; frame size = 32 bytes<br>    mov  x20, x8                     ; x20 = sret hidden return pointer<br>    bl   operator new(unsigned long) ; allocate the 32-byte coroutine frame<br>    adrp x8, 0x15000<br>    add  x8, x8, 0xea8               ; x8 = 0x15ea8 = _Z7counteri.resume<br>    adrp x9, 0x15000<br>    add  x9, x9, 0xef4               ; x9 = 0x15ef4 = _Z7counteri.destroy<br>    stp  w19, w19, [x0, 0x10]        ; frame[+0x10] = n<br>    stp  x8,  x9,  [x0]              ; * frame[+0]=resume, frame[+8]=destroy<br>    str  x0, [x20]                   ; return handle (= frame address) to caller<br>    strb wzr, [x0, 0x1c]             ; frame[+0x1c(=28)] = state number = 0<br>    ldp  x20, x19, [sp, 0x10]        ; epilogue<br>    ldp  x29, x30, [sp], 0x20<br>    ret</pre><blockquote><em>After r2 resolves </em><em>adrp + add into symbol addresses, </em><em>x8 = 0x15ea8 is exactly </em><em>_Z7counteri.resume and </em><em>x9 = 0x15ef4 is exactly </em><em>_Z7counteri.destroy — so </em><em>stp x8, x9, [x0] confirms on the spot that &quot;frame[0]/frame[1] are the two function pointers&quot;.</em></blockquote><p><strong>resume — “suspension” is just </strong>strb state#<strong> + </strong>ret (also very short, <strong>76 bytes</strong>, fully shown):</p><pre>; r2: sym.counter_int_ [clone .resume]   0x15ea8, 76 bytes total<br>_Z7counteri.resume:<br>    ldrb w8, [x0, 0x1c]          ; read state number (+0x1c = +28)<br>    cbz  w8, 0x15ec4             ; state==0 → first entry<br>    ldp  w9, w8, [x0, 0x14]      ; read n(+0x14) and i(+0x18)<br>    cmp  w8, w9<br>    b.eq 0x15ee8                 ; i == n → finish<br>    add  w8, w8, 1               ; ++i<br>    b    0x15ed4<br>    ldr  w8, [x0, 0x14]          ; (0x15ec4) first time: read n<br>    cmp  w8, 1<br>    b.lt 0x15ee8<br>    mov  w8, 1<br>    str  w8, [x0, 0x18]          ; (0x15ed4) store i<br>    str  w8, [x0, 0x10]          ; store current_value (promise)<br>    mov  w8, 1<br>    strb w8, [x0, 0x1c]          ; state = 1<br>    ret                          ; ← suspend<br>    str  w8, [x0, 0x10]          ; (0x15ee8)<br>    str  xzr, [x0]               ; * frame[+0] = 0 → mark done<br>    ret</pre><p>.destroy is just as short — it&#39;s operator delete(frame, 32):</p><pre>; r2: sym.counter_int_ [clone .destroy]   0x15ef4, 8 bytes total<br>_Z7counteri.destroy:<br>    mov  w1, 0x20                    ; size = 32<br>    b    operator delete(void*, unsigned long)   ; free the coroutine frame</pre><h3>The real frame layout (Itanium C++ ABI)</h3><pre>frame →<br>  +0    (*resume)(handle)     ← fixed<br>  +8    (*destroy)(handle)    ← fixed<br>  +16   promise object (inline)  ← offset fixed (promise() asm: add x0, x8, #16)<br>  +16+S params / locals / awaiter / state number   ← offset chosen by the compiler</pre><p><strong>So this is the pointer situation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8993sZPfHeKra_Fhne8J0Q.png" /></figure><blockquote><em>In one sentence: </em><em>g</em><strong><em> (the Generator) is just an 8-byte pointer on the stack, pointing at a frame on the heap; the first two slots of the frame are function pointers, and the data/promise start from the third slot.</em></strong></blockquote><h3>Hands-on verification: read the frame out</h3><p>Bypass the API with inline assembly to extract the frame from g:</p><pre>void* frame = nullptr;<br>asm volatile(&quot;ldr %0, [%1]&quot; : &quot;=r&quot;(frame) : &quot;r&quot;(&amp;g) : &quot;memory&quot;);   // read the first 8 bytes of &amp;g<br>void* resume  = ((void**)frame)[0];       // frame+0<br>void* destroy = ((void**)frame)[1];       // frame+8<br>int*  promise = (int*)((char*)frame + 16); // frame+16</pre><p>Operation log (dump the three slots after each next()):</p><pre>before       frame[0] resume=0x..0aa0  frame[1] destroy=0x..0b54  frame[2] promise=0x3  done=0<br>after next#1 frame[0] resume=0x..0aa0  frame[1] destroy=0x..0b54  frame[2] promise=0x1  done=0<br>after next#3 frame[0] resume=0x..0aa0  frame[1] destroy=0x..0b54  frame[2] promise=0x3  done=0<br>after done   frame[0] resume=0x0 ←null  frame[1] destroy=0x..0b54  frame[2] promise=0x3  done=1</pre><ul><li>frame[0] (resume) <strong>becomes null at the end</strong> — matching the assembly str xzr,[x0];</li><li>frame[1] (destroy) <strong>stays valid the whole time</strong>;</li><li>frame[2] is promise.current_value.</li></ul><h3>Two corollaries</h3><ul><li><strong>The implementation of </strong>done(): frame[0] == nullptr (on completion the coroutine clears its own head pointer). Confirmed by the handle.resume() assembly — it&#39;s just &quot;load frame[0] → blr indirect call&quot;.</li><li>next()<strong> = </strong>resume()<strong> + </strong>!done(): calling the resume pointer directly is only &quot;half a step&quot; (measured: g++ gives SIGSEGV, clang returns silently — <strong>the same code, two different outcomes</strong> — so you must check !done() first).</li></ul><h3>The frame size grows with the promise</h3><p>counter&#39;s frame is 0x20. If we add more members to promise_type, does the frame grow? We modify promise_type, recompile with -O2, and <strong>read the immediate of </strong>operator new<strong> in the ramp</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Jcspi3Xf8g8x2g-mLfGcEw.png" /></figure><p><strong>Conclusion: frame size = </strong>16<strong> (two function pointers) + </strong>sizeof(promise)<strong> + params/locals/state number, rounded up to alignment. So as soon as the promise grows, the frame grows with it.</strong></p><ul><li>Adding an int grows by 8: 4 bytes itself + alignment padding;</li><li>Adding an 8-byte type (pointer / long) grows by 16: the preceding int is <strong>padded to 8-byte alignment</strong> before the 8 bytes are placed;</li><li>Adding int+pointer+long at once grows by 24 (4+4 +8 +8).</li></ul><h3>4. Custom awaiter (the core usage of coroutines)</h3><p>co_yield/co_return only produce/finish; the real power of coroutines is co_await<strong> + a custom awaiter</strong> — what happens on suspension, who resumes, and what comes back after resuming are all defined by you. An awaiter has just three members:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*A_a1pFxyc2imy5ncRtNebg.png" /></figure><p>An example — <strong>an awaiter that waits N seconds</strong>:</p><pre>struct WaitForSeconds {<br>    double seconds;<br>    bool await_ready() const noexcept { return seconds &lt;= 0.0; }   // no suspend needed if &lt;=0s<br>    void await_suspend(std::coroutine_handle&lt;&gt; h) const {<br>        std::thread([h, sec = seconds] {                           // on suspend: start a timer thread<br>            std::this_thread::sleep_for(std::chrono::duration&lt;double&gt;(sec));<br>            h.resume();                                            // time&#39;s up, resume the coroutine<br>        }).detach();<br>    }<br>    void await_resume() const noexcept {}<br>};</pre><p>A complete minimal program — <strong>waiting 3 times in a row (1, 2, 3 seconds)</strong>, so you can see “<strong>one case per </strong>co_await&quot;:</p><pre>#include &lt;coroutine&gt;<br>#include &lt;cstdio&gt;<br>#include &lt;chrono&gt;<br>#include &lt;thread&gt;<br>#include &lt;atomic&gt;</pre><pre>std::atomic&lt;bool&gt; g_finished{false};<br>std::chrono::steady_clock::time_point g_start;<br>double elapsed() { return std::chrono::duration&lt;double&gt;(std::chrono::steady_clock::now() - g_start).count(); }<br>struct Task {<br>    struct promise_type {<br>        Task get_return_object() { return {}; }<br>        std::suspend_never initial_suspend() noexcept { return {}; }<br>        std::suspend_always final_suspend() noexcept { return {}; }<br>        void return_void() {}<br>        void unhandled_exception() { std::terminate(); }<br>    };<br>};<br>Task timer_demo() {<br>    printf(&quot;[t=%.1fs] start\n&quot;, elapsed());<br>    co_await WaitForSeconds{1.0};                // suspension point ①<br>    printf(&quot;[t=%.1fs] 1 second passed\n&quot;, elapsed());<br>    co_await WaitForSeconds{2.0};                // suspension point ②<br>    printf(&quot;[t=%.1fs] another 2 seconds passed\n&quot;, elapsed());<br>    co_await WaitForSeconds{3.0};                // suspension point ③<br>    printf(&quot;[t=%.1fs] another 3 seconds passed\n&quot;, elapsed());<br>    g_finished.store(true);<br>    co_return;<br>}<br>int main() {<br>    g_start = std::chrono::steady_clock::now();<br>    timer_demo();                                // start: runs to the first co_await and suspends<br>    while (!g_finished.load()) std::this_thread::sleep_for(std::chrono::milliseconds(50)); // hold so main doesn&#39;t exit<br>    printf(&quot;[t=%.1fs] main: done\n&quot;, elapsed());<br>}</pre><p>Output (1 second, then 2, then 3):</p><pre>[t=0.0s] start<br>[t=1.0s] 1 second passed<br>[t=3.0s] another 2 seconds passed<br>[t=6.0s] another 3 seconds passed<br>[t=6.0s] main: done</pre><p>r2 decompilation. <strong>The ramp runs to the first </strong>co_await<strong> and suspends; after that, every entry goes through </strong>.resume<strong>, dispatching on the state number</strong>:</p><pre>; ───────── ramp: runs to the first co_await and suspends ─────────<br>0x2fd8  mov  w0, 0x20                     ; frame size 0x20<br>0x2fdc  bl   operator new                 ; allocate the coroutine frame<br>0x2ff4  stp  x8, x9, [x0]                 ; frame[0]=.resume(0x3110) frame[1]=.destroy(0x322c)<br>0x3024  bl   printf                       ; printf(&quot;[t=..] start&quot;)<br>0x302c  strb wzr, [x19, 0x11]             ; * state number = 0<br>0x3030  str  x8,  [x19, 0x18]             ;    awaiter.seconds = 1.0<br>0x3040  bl   std::thread::thread&lt;lambda&gt;  ;    await_suspend: start thread, wait 1s<br>0x3060  ret                               ;    → suspend, hand back to caller</pre><pre>; ───────── .resume: resumed by the timer thread, dispatches on the state number ─────────<br>_Z10timer_demov.resume (0x3110):<br>0x3120  ldrb w20, [x0, 0x11]              ; * read state number<br>0x3130  cmp  w20, 2                       ; ┐<br>0x3150  b.eq 0x3194                       ; │  state dispatch<br>0x3154  cmp  w20, 1                       ; │  (= the shape of switch(state))<br>0x3158  b.ne 0x31b8                       ; ┘<br>; ---- case 1 (state number == 1: just past the 2nd co_await) ----<br>0x3164  bl   printf                       ; printf(&quot;[t=..] another 2 seconds passed&quot;)<br>0x3168  mov  x8, 0x4008000000000000       ; 3.0<br>0x316c  mov  w9, 2<br>0x3170  str  x8, [x19, 0x18]              ; awaiter.seconds = 3.0<br>0x3174  strb w9, [x19, 0x11]              ; state number = 2<br>0x3184  bl   std::thread::thread&lt;lambda&gt;  ; await_suspend: start thread, wait 3s<br>0x3190  b    0x31ec                       ; → epilogue(dtor) + ret (suspend)<br>; ---- case 2 (state number == 2: just past the 3rd co_await) ----<br>0x319c  bl   printf                       ; printf(&quot;[t=..] another 3 seconds passed&quot;)<br>0x31a0  mov  w8, 1<br>0x31ac  stlrb w8, [x9]                    ; g_finished = true<br>0x31b0  str  xzr, [x19]                   ; frame[0] = 0 → done<br>0x31b4  b    0x31f4                       ; → ret (finish)<br>; ---- case 0 (state number == 0: just past the 1st co_await) ----<br>0x31c0  bl   printf                       ; printf(&quot;[t=..] 1 second passed&quot;)<br>0x31c4  mov  x8, 0x4000000000000000       ; 2.0<br>0x31c8  mov  w9, 1<br>0x31cc  str  x8, [x19, 0x18]              ; awaiter.seconds = 2.0<br>0x31d0  strb w9, [x19, 0x11]              ; state number = 1<br>0x31e0  bl   std::thread::thread&lt;lambda&gt;  ; await_suspend: start thread, wait 2s<br>0x31f4  ret                               ; → suspend</pre><p><strong>See it now</strong>:</p><ul><li><strong>Each </strong>co_await<strong> corresponds to a state number (0/1/2) and a case</strong> — after ldrb state# come cmp / b.eq / b.ne, which is the shape of switch(state);</li><li><strong>Each case block contains a full awaiter triad</strong> (str stores seconds → bl std::thread spawns a thread = await_suspend; ret = suspend);</li><li>strb state# before suspending, ldrb state# when resuming — that&#39;s &quot;remembering where it was suspended&quot;.</li></ul><blockquote><em>A small trap: when </em><em>await_ready() returns </em><em>true (</em><em>seconds&lt;=0), it </em><strong><em>skips </em></strong><em>await_suspend, so don&#39;t put &quot;must happen whether or not it suspends&quot; logic inside </em><em>await_suspend.</em></blockquote><h3>Part 2 · Unity’s C# Coroutines</h3><blockquote><em>Above, we looked at C++ coroutines along “</em><strong><em>source → assembly → frame memory</em></strong><em>”. Now let’s analyze Unity’s C# coroutines with the same approach, using </em><strong><em>three compile stages + one dynamic stage</em></strong><em>:</em></blockquote><blockquote><strong><em>① C# → IL</em></strong><em> (Roslyn; by this point the </em><em>switch is already visible)</em></blockquote><blockquote><strong><em>② IL → C++</em></strong><em> (il2cpp.exe </em><em>--convert-to-cpp)</em></blockquote><blockquote><strong><em>③ C++ → </em></strong><em>.so (NDK clang compile + link)</em></blockquote><blockquote><strong><em>④ Install on a real device · dynamic verification</em></strong><em> (IDA + Frida)</em></blockquote><h3>5. Source: a UI + Action callback + coroutine</h3><p>CoroutineUIDemo.cs from a real Unity project: a button on the UI; clicking it starts a coroutine that &quot;waits 2 seconds then calls the callback&quot;.</p><pre>public class CoroutineUIDemo : MonoBehaviour<br>{<br>    public Text statusText;<br>    public Button startButton;</pre><pre>    void Start() {<br>        statusText.text = &quot;click to start&quot;;<br>        startButton.onClick.AddListener(OnButtonClick);          // button → callback<br>    }</pre><pre>    void OnButtonClick() {<br>        Debug.Log(&quot;[UI] button clicked&quot;);<br>        StartCoroutine(DoWork(2f, () =&gt; {                        // Action callback<br>            statusText.text = &quot;done!&quot;;<br>            Debug.Log(&quot;[UI] completion callback invoked&quot;);<br>        }));<br>    }</pre><pre>    IEnumerator DoWork(float seconds, Action onDone) {<br>        statusText.text = &quot;processing...&quot;;<br>        Debug.Log(&quot;[Co] start, waiting &quot; + seconds + &quot; seconds&quot;);<br>        yield return new WaitForSeconds(seconds);                // suspend ①<br>        Debug.Log(&quot;[Co] wait finished&quot;);<br>        yield return null;                                       // suspend ②<br>        onDone?.Invoke();                                        // call the callback<br>    }<br>}</pre><p>Two yield returns. Below we&#39;ll <strong>watch step by step what it compiles into</strong>.</p><h3>6. First compile stage: C# → IL (the switch is already visible)</h3><p>The C# compiler (Roslyn) first compiles DoWork to IL. For readability, we drop the Unity dependency and write an <strong>equivalent minimal version</strong> (exactly the same structure):</p><pre>public class CoroutineDemo {<br>    public static IEnumerator DoWork(float seconds) {<br>        Console.WriteLine(&quot;processing...&quot;);<br>        yield return new WaitForSeconds(seconds);   // suspend ①<br>        Console.WriteLine(&quot;wait finished&quot;);<br>        yield return null;                          // suspend ②<br>        Console.WriteLine(&quot;done&quot;);<br>    }<br>}</pre><p>Use ildasm (ildasm /text /out:ildemo.il ildemo.dll) to look at its IL. DoWork<strong> is gone, replaced by a compiler-generated nested class </strong>&lt;DoWork&gt;d__0:</p><pre>.class auto ansi sealed nested private beforefieldinit &#39;&lt;DoWork&gt;d__0&#39;   // ← compiler-generated state-machine class<br>.field private int32  &#39;&lt;&gt;1__state&#39;      // state number<br>.field private object &#39;&lt;&gt;2__current&#39;    // the value yielded out each time<br>.field public  float32 seconds          // captured parameter</pre><pre>.method instance bool MoveNext() cil managed {<br>    IL_0001:  ldfld  int32 CoroutineDemo/&#39;&lt;DoWork&gt;d__0&#39;::&#39;&lt;&gt;1__state&#39;<br>    IL_0006:  stloc.0<br>    IL_0007:  ldloc.0<br>    IL_0008:  switch  (IL_001b, IL_0046, IL_0067)   // !!! three cases<br>    IL_0019:  ldc.i4.0<br>    IL_001a:  ret                                    // default branch: return false (finish)<br>  IL_001b:  // ---- case 0 ----<br>    ldarg.0 ; ldc.i4.m1 ; stfld &lt;&gt;1__state           // state = -1<br>    ldstr &quot;processing...&quot; ; call Console::WriteLine<br>    ldarg.0 ; ldfld seconds ; newobj WaitForSeconds ; stfld &lt;&gt;2__current<br>    ldarg.0 ; ldc.i4.1 ; stfld &lt;&gt;1__state            // state = 1<br>    ldc.i4.1 ; ret                                   // return true (suspend)<br>  IL_0046:  // ---- case 1 ----<br>    ... <br>}</pre><p><strong>In IL</strong>: &lt;&gt;1__state (the int state number) + switch (IL_001b, IL_0046, IL_0067) with three branches + each segment&#39;s trailing stfld &lt;&gt;1__state; ldc.i4.1; ret (store state, return true = suspend). <strong>2 </strong>yield return<strong>s in the source correspond to 2 cases (the other one is the initial case)</strong></p><h3>7. Second stage: C# (IL) → C++ (IL2CPP)</h3><h3>7.1 Build</h3><p>IL2CPP <strong>translates IL into C++ instruction by instruction</strong>. Batch-build in Unity with the Android IL2CPP backend installed:</p><p>Compilation pipeline:</p><pre>C# source<br>  │ Roslyn<br>  ▼<br>iterator method → compiler-generated nested state-machine class &lt;Xxx&gt;d__N<br>  │ IL2CPP (il2cpp.exe --convert-to-cpp --dotnetruntime=Il2Cpp --platform=Android)<br>  ▼<br>C++ (Library/Bee/artifacts/Android/il2cppOutput/cpp/Assembly-CSharp*.cpp)<br>  │ NDK clang compile + link<br>  ▼<br>libil2cpp.so → APK</pre><h3>7.2 First, a look at the product — why are the symbols so long and weird?</h3><p>Open Assembly-CSharp.cpp and grab any snippet — the whole screen is full of names like this:</p><pre>struct U3CDoWorkU3Ed__6_t001EAA1C1E8F52701D4761ED06B1BCDCF5E892C8 : public RuntimeObject { ... };</pre><pre>IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* CoroutineUIDemo_DoWork_m075247933123D01E5AEA6F192324DAC00A03991C (...);</pre><p>U3CDoWorkU3Ed__6_t001EAA…, _m0752… — long and weird. There are just <strong>two reasons</strong>:</p><p><strong>① Characters like </strong>&lt;&gt;<strong> aren&#39;t recognized by C++, so they&#39;re ASCII-encoded</strong>: &lt;=0x3C→U3C, &gt;=0x3E→U3E. So &lt;DoWork&gt;d__6 in IL becomes U3CDoWorkU3Ed__6 in C++:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*ElZbmf1gq2YFxZPbydiebg.png" /></figure><p><strong>② Each type/method then gets a SHA-1 chunk</strong> (40 hex digits) to guarantee global uniqueness (so overloads, generics, and compiler-generated names never collide):</p><pre>U3CDoWorkU3Ed__6   _t001EAA1C1E8F52701D4761ED06B1BCDCF5E892C8<br>CoroutineUIDemo_DoWork   _m075247933123D01E5AEA6F192324DAC00A03991C<br>   └ class name_method name ┘    └ _m ┘  └———— SHA-1 of that method&#39;s declaration ————┘<br>Types are &lt;name&gt;_t&lt;SHA1&gt;; methods are &lt;ClassName&gt;_&lt;methodName&gt;_m&lt;SHA1&gt;; strings are _stringLiteral&lt;SHA1&gt;.</pre><p>So “weird symbols” = <strong>the character escaping </strong>&lt;&gt;<strong>→</strong>U3C/U3E + <strong>the </strong>_t/_m&lt;SHA1&gt;<strong> uniqueness suffix</strong> — just two things stacked.</p><h3>7.3 Product #1: the state machine class (= the coroutine “frame”)</h3><pre>struct U3CDoWorkU3Ed__6_t001EAA1C1E8F52701D4761ED06B1BCDCF5E892C8 : public RuntimeObject<br>{<br>    int32_t ___U3CU3E1__state;                   // &lt;&gt;1__state   —— the state number (that int)<br>    RuntimeObject* ___U3CU3E2__current;          // &lt;&gt;2__current —— the current yield value<br>    CoroutineUIDemo_t1320...* ___U3CU3E4__this;  // captured this<br>    float ___seconds;                            // captured parameter<br>    Action_tD00B0...* ___onDone;                 // captured Action callback<br>};</pre><p>Compare with the source DoWork(float seconds, Action onDone): its parameters, this, state number, current value… <strong>all become fields of this class</strong> — that&#39;s the &quot;coroutine frame&quot;.</p><h3>7.4 Product #2: DoWork (the ramp — only constructs the object)</h3><pre>RuntimeObject* CoroutineUIDemo_DoWork_m0752... (CoroutineUIDemo_t* __this, float ___0_seconds, Action_t* ___1_onDone, ...) {<br>    U3CDoWorkU3Ed__6_t* L_0 = il2cpp_codegen_object_new(U3CDoWorkU3Ed__6_il2cpp_TypeInfo_var);  // new &lt;DoWork&gt;d__6<br>    U3CDoWorkU3Ed__6__ctor(L_0, 0, NULL);          // state = 0<br>    L_0-&gt;___U3CU3E4__this = __this;                // fill captured variables<br>    L_0-&gt;___seconds       = ___0_seconds;<br>    L_0-&gt;___onDone        = ___1_onDone;<br>    return L_0;                                     // return the IEnumerator<br>}</pre><p>Just like the C++ ramp: <strong>it doesn’t run logic; it just prepares the state-machine object and the captured variables</strong>.</p><h3>7.5 Product #3: MoveNext (that switch in the IL)</h3><pre>bool U3CDoWorkU3Ed__6_MoveNext_m5E19... (U3CDoWorkU3Ed__6_t* __this, ...) {<br>    int32_t L_0 = __this-&gt;___U3CU3E1__state;         // read the state number<br>    switch (V_0) {                                     // ← this is the switch in the IL<br>        case 0: goto IL_0022;<br>        case 1: goto IL_0080;<br>        case 2: goto IL_00a1;<br>    }<br>    return (bool)0;                                    // finish</pre><pre>IL_0022:                                               // case 0<br>    __this-&gt;___U3CU3E1__state = (-1);<br>    statusText.text = &quot;processing...&quot;;<br>    Debug.Log(&quot;[Co] start, waiting &quot; + seconds + &quot; seconds&quot;);<br>    __this-&gt;___U3CU3E2__current = new WaitForSeconds(seconds);  // * hand off to the engine<br>    __this-&gt;___U3CU3E1__state = 1;<br>    return (bool)1;                                    // * suspend<br>IL_0080:                                               // case 1<br>    Debug.Log(&quot;[Co] wait finished&quot;);<br>    __this-&gt;___U3CU3E2__current = NULL;                // * wait for the next frame<br>    __this-&gt;___U3CU3E1__state = 2;<br>    return (bool)1;                                    // * suspend<br>IL_00a1:                                               // case 2<br>    if (__this-&gt;___onDone) Action_Invoke(__this-&gt;___onDone);   // * call the callback<br>    return (bool)0;                                    // * finish<br>}</pre><p><strong>The </strong>switch (IL_001b, IL_0046, IL_0067)<strong> in the IL becomes, verbatim, the </strong>switch (state)<strong> in the C++</strong>: 2 yield returns in the source → case 0/1/2 + one int state number.</p><h3>8. Disassembly and dynamic analysis (IDA + Frida)</h3><p>The product is only “on paper”; let’s install it on a real device and explore it dynamically.</p><h3>8.1 IDA: how to locate things in a stripped .so</h3><p>The libil2cpp.so loaded into IDA is the <strong>stripped</strong> build — method names are LOCAL HIDDEN, so you can&#39;t find them by name. The trick: <strong>take addresses from the un-stripped </strong>libil2cpp.sym.so<strong> with </strong>llvm-readelf --syms, then add names/commentary in the stripped library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*OXyOhGWX3Wett07ydGbdlw.png" /></figure><h3>8.2 IDA: decompile DoWork / MoveNext / OnButtonClick</h3><p>DoWork<strong> (0x99BB4C) = the ramp</strong>: just new &lt;DoWork&gt;d__6 + fill the captured variables.</p><pre>; C# IEnumerator DoWork(float seconds, Action onDone)   ABI: x0=this, s0=seconds, x1=onDone<br>99bb6c  MOV  X19,X1                    ; X19 = onDone<br>99bb70  MOV  V8.16B,V0.16B             ; V8  = seconds (float)<br>99bb74  MOV  X20,X0                    ; X20 = this<br>99bb94  BL   ...object_new(&lt;DoWork&gt;d__6)  ; new &lt;DoWork&gt;d__6  = allocate the coroutine frame object<br>99bba0  BL   &lt;DoWork&gt;d__6::.ctor(v6, 0)   ; state machine construction<br>99bba8  STR  WZR,[X21,#0x10]           ; v6-&gt;&lt;&gt;1__state = 0   (state number at +0x10)<br>99bbac  STR  X20,[X0,#0x20]!           ; v6-&gt;&lt;&gt;4__this = this (+0x20)<br>99bbbc  STR  S8,[X21,#0x28]            ; v6-&gt;seconds = seconds (+0x28)<br>99bbc0  STR  X19,[X0,#0x30]!           ; v6-&gt;onDone = onDone  (+0x30)<br>99bbe0  RET                            ; return v6</pre><p>MoveNext<strong> (0x99BCF4) = the state machine</strong> (= the switch in the IL):</p><pre>U3CDoWorkU3Ed__6_MoveNext:<br>99bd6c  LDR  W8,[X19,#0x10]            ; v3 = this-&gt;&lt;&gt;1__state  (read the state number)<br>99bd70  CMP  W8,#2<br>99bd74  B.EQ loc_99BE88                ; case 2 -&gt; call onDone + finish<br>99bd7c  B.EQ loc_99BEB0 (CMP#1)        ; case 1 -&gt; emit null (next frame)<br>99bd80  CBNZ W8,loc_99BEA8             ; else -&gt; return 0<br>; ---- case 0 ----<br>99bde4  BLR  X9                        ; statusText.text = &quot;processing...&quot;<br>99be18  BL   String.Concat             ; &quot;[Co] start, waiting &quot; + seconds + &quot; seconds&quot;<br>99be58  BL   new WaitForSeconds(...)<br>99be6c  STR  X20,[X19,#0x18]!          ; this-&gt;&lt;&gt;2__current = waitForSeconds  (+0x18)<br>99be7c  MOV  W0,#1                     ; return 1  // suspend<br>99be80  STUR W0,[X19,#-8]              ; this-&gt;&lt;&gt;1__state = 1<br>; ---- case 2 ----<br>99be98  LDR  X9,[X8,#0x18]; BLR X9     ; onDone.Invoke()  (indirect delegate call)<br>99bea8  MOV  W0,WZR                    ; return 0  // finish<br>; ---- case 1 ----<br>99bee4  STR  XZR,[X19,#0x18]!          ; this-&gt;&lt;&gt;2__current = null<br>99bef8  ... (state=2)<br>99befc  MOV  W0,#1                     ; return 1  // suspend</pre><p>OnButtonClick<strong> (0x99BA74)</strong>: button click → build delegate → start coroutine:</p><pre>99bb00  BL   sub_11138F0               ; Debug.Log(&quot;[UI] button clicked&quot;)<br>99bb08  BL   il2cpp_object_new         ; new Action<br>99bb1c  BL   Action::.ctor(this, &lt;OnButtonClick&gt;b__5_0_RuntimeMethod_var)<br>99bb2c  BL   CoroutineUIDemo_DoWork    ; DoWork(this, 2.0f, action) returns IEnumerator<br>99bb48  B    StartCoroutine            ; hand off to the engine (native icall)</pre><h3>8.3 What is &lt;OnButtonClick&gt;b__5_0_RuntimeMethod_var, or RuntimeMethod_var?</h3><p>When constructing the Action delegate, the C++ passes a ..._RuntimeMethod_var. In IDA it looks like this in .data:</p><pre>0x142ADB0   OnButtonClick_RuntimeMethod_var   DCQ 0x6000BAED</pre><p><strong>This </strong>0x6000BAED<strong> is not a pointer!</strong> It&#39;s a <strong>packed metadata token</strong> (the official decoding formulas):</p><pre>GetEncodedIndexType(idx)   = (idx &amp; 0xE0000000) &gt;&gt; 29   // top 3 bits = kind<br>GetDecodedMethodIndex(idx) = (idx &amp; 0x1FFFFFFE) &gt;&gt; 1    // the rest = index</pre><p>The top 3 bits 0b011=3 = kIl2CppMetadataUsageMethodDef, and the index = <strong>23926</strong> (a global method definition).</p><p><strong>Only at runtime does it become a real pointer</strong> — measured with Frida base.add(0x142ADB0).readPointer():</p><p>The .data slot holds a token in the file; only at runtime is it resolved into a pointer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*gsU_D9VxPlPZwq1jIM0PIQ.png" /></figure><p>That is: _RuntimeMethod_var is a RuntimeMethod* (= MethodInfo*); in the file it&#39;s a token, resolved into a real pointer at runtime by il2cpp_codegen_initialize_runtime_metadata.</p><blockquote>These addresses, SHA-1 suffixes, and the token/index here are all things I jotted down over many rounds of writing code and running builds. So when you see <em>0x6000BAED</em> above and <em>0x6000077B</em> in the dump below, and the various sections&#39; function addresses don&#39;t line up, <strong>that&#39;s normal</strong> — just look at the &quot;shape/pattern&quot;, no need to match character for character.</blockquote><p>And what exactly is the RuntimeMethod structure? In codegen/il2cpp-codegen-metadata.h:</p><pre>typedef MethodInfo RuntimeMethod;   // just an alias of MethodInfo</pre><p>The real structure (il2cpp-class-internals.h, excerpt):</p><pre>typedef struct MethodInfo {<br>    Il2CppMethodPointer methodPointer;          // * the real function pointer<br>    Il2CppMethodPointer virtualMethodPointer;<br>    InvokerMethod       invoker_method;         // invoker<br>    const char*         name;<br>    Il2CppClass*        klass;<br>    ...<br>} MethodInfo;</pre><h3>8.4 Who calls MoveNext?</h3><p>Set a breakpoint on MoveNext and print the call stack (breakWithStack(0x99bcf4)):</p><pre>Start → OnButtonClick → new Action(lambda) → DoWork(ramp) → new &lt;DoWork&gt;d__6<br>  → MoveNext(state 0/1/2) → onDone.Invoke() → lambda</pre><pre>0x716737a334 libil2cpp.so!0x112f334  SetupCoroutine::InvokeMoveNext(IEnumerator, IntPtr)  ← direct caller<br>0x7166b49f3c libil2cpp.so!0x8fef3c   il2cpp::vm::Runtime::Invoke<br>0x716be9e6b8 libunity.so!0x8396b8    ← native Unity engine<br>0x7166b49e88 libil2cpp.so!0x8fee88   il2cpp_runtime_invoke<br>0x716ba858f4 libunity.so!0x4208f4    ← native Unity engine<br>0x716ba9519c libunity.so!0x43019c    ← native Unity engine (coroutine update / player loop)</pre><p>IDA decompilation of the stack top 0x112F334 confirms it&#39;s a managed helper method:</p><pre>// UnityEngine.SetupCoroutine.InvokeMoveNext(IEnumerator enumerator, IntPtr returnValueAddress)<br>if (!enumerator) throw NRE;<br>result = enumerator.MoveNext();               // * call the coroutine<br>*(uint8_t*)returnValueAddress = result &amp; 1;   // write the bool back to the address given by the engine</pre><p><strong>The driving chain: </strong>libunity.so<strong> (native engine) → </strong>il2cpp_runtime_invoke<strong> → </strong>Runtime::Invoke<strong> → </strong>SetupCoroutine.InvokeMoveNext<strong> → </strong>MoveNext<strong>.</strong> All on the main thread.</p><h3>8.5 A derived conclusion: InvokeMoveNext = catch all coroutines</h3><p>BF(&quot;InvokeMoveNext&quot;) matches <strong>two</strong> same-named but different methods:</p><pre>0xfa053c   mscorlib: MoveNextRunner.InvokeMoveNext(Object)                     ← C# async/await (a separate system)<br>0x112f27c  UnityEngine: SetupCoroutine.InvokeMoveNext(IEnumerator, IntPtr)     ← Unity coroutines *</pre><p>After setting a breakpoint on the latter, they hit back-to-back at the same moment:</p><pre>...<br>enumerator = 0x74aa230770  UnityEngine.UI.CoroutineTween.TweenRunner`1+&lt;Start&gt;d__2[ColorTween]  ← Unity-internal coroutine<br>enumerator = 0x74aa23ca40  CoroutineUIDemo+&lt;DoWork&gt;d__6                                          ← * our coroutine<br>...</pre><p>Two parameters: enumerator (input) = the state-machine object; returnValueAddress (output) = an address reference.</p><h3>8.6 What’s stored in the state machine object</h3><p>Combined with a runtime inspection lfs(0x74aa23ca40):</p><pre>&lt;&gt;1__state  = -1      (0..N = suspended at the Nth yield; -1 = finished)<br>&lt;&gt;2__current = null<br>&lt;&gt;4__this   = Runner (CoroutineUIDemo)<br>seconds     = 2<br>onDone      = &lt;OnButtonClick&gt;b__5_0  (MP:0x99bc14)</pre><p>Field offsets: state +0x10 / current +0x18 / __this +0x20 / seconds +0x28 / onDone +0x30 (object header 0x10).</p><h3>Part 3 · Comparison and Summary</h3><h3>9. Conclusion</h3><h3>9.1 yield return = a compiler-generated state machine (N yields = N cases + one int)</h3><p>Through the whole path C# → IL → C++, a yield return method is compiled into a hidden class (called &lt;DoWork&gt;d__0 in IL, U3CDoWorkU3Ed__6 in C++), and the logic lives in MoveNext&#39;s switch(&lt;&gt;1__state). <strong>2 </strong>yield return<strong>s in the source → IL </strong>switch(3 targets)<strong> → C++ </strong>switch(state)<strong> with three cases</strong> — the same origin as C++20&#39;s co_yield, and &lt;&gt;1__state is that &quot;where it&#39;s suspended&quot; state number.</p><h3>9.2 Who drives it: C++ relies on you, Unity relies on the engine</h3><ul><li><strong>C++20</strong>: there’s no driver; who calls resume inside await_suspend is entirely up to you (or your awaiter).</li><li><strong>Unity</strong>: StartCoroutine hands the state machine to the engine via a native icall; every frame the engine calls MoveNext through il2cpp_runtime_invoke → Runtime::Invoke → SetupCoroutine.InvokeMoveNext, then decides when to call again based on the return value and Current (null = next frame, WaitForSeconds = timer).</li></ul><p><strong>A coroutine is not a thread; it’s sequential code executed frame-by-frame on the main thread.</strong></p><h3>9.3 Those 6 interface methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Py9qzxOIO3HVw0ZBB93-4Q.png" /></figure><h3>10. C++20 coroutines vs Unity coroutines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cPU0qV6gIkv8ZmQ58i_og.png" /></figure><h3>11. What did we “catch” along the way</h3><ol><li><strong>The pointers in the C++ frame</strong>: g is an 8-byte pointer on the stack → pointing at a frame on the heap; frame[0]=resume, frame[1]=destroy, frame[+16]=promise; done() = frame[0]==null; next() = resume()+!done().</li><li><strong>Unity’s state-machine object</strong>: state +0x10 / current +0x18 are the core; MoveNext is the state machine.</li><li><strong>The truth of </strong>_RuntimeMethod_var: in the file it&#39;s a <strong>metadata token</strong> (0x6000BAED → MethodDef #23926), resolved into a MethodInfo* only at runtime (measured with Frida: reading +24 yields &quot;OnButtonClick&quot;).</li><li><strong>A universal hook</strong>: hooking SetupCoroutine.InvokeMoveNext(IEnumerator, IntPtr) = <strong>catching every step of every </strong>IEnumerator<strong> coroutine</strong> (arg0 gives the state-machine object, arg1 gives the result write-back address); distinguish it from MoveNextRunner.InvokeMoveNext (async/await).</li><li><strong>Methodology</strong>: for a stripped .so, take addresses from the un-stripped sym.so → add names/comments in IDA; use Frida to read runtime memory / call stacks / dump objects, to falsify the static conclusions.</li></ol><h3>Appendix: some loose ideas</h3><p><strong>① A general-purpose “Unity coroutine tracker”</strong></p><pre>hook SetupCoroutine.InvokeMoveNext(IEnumerator enumerator, IntPtr retAddr):<br>    klass = *(void**)enumerator           // read object header → class name (filter for the coroutines you want)<br>    state = *(int*)(enumerator + 0x10)    // state number<br>    cur   = *(void**)(enumerator + 0x18)  // the value yielded this time<br>    log(className, state, cur)<br>    // after the function returns: read one byte at *retAddr → 1 = not finished / 0 = finished</pre><p>Print each coroutine’s <strong>state transition + yield value</strong> for every MoveNext in real time — that&#39;s a &quot;coroutine-aware call tracer&quot;.</p><p><strong>② Locating a coroutine frame (a C++ coroutine frame) in an “unsigned binary” by its signature</strong></p><p>The frame header has two consecutive function pointers: [+0]=resume, [+8]=destroy. In assembly this shows up as &quot;<strong>right after </strong>new<strong>, stick two code pointers into the head of the heap block</strong>&quot; (like a two-slot vtable); the body of destroy is usually just delete(frame, size):</p><pre>bl   operator new(size)          ; allocate the frame<br>...                              ; get the frame pointer frame<br>adrp/add x8, &lt;some function&gt;     ; = resume<br>adrp/add x9, &lt;some function&gt;     ; = destroy<br>stp  x8,  x9,  [frame]           ; frame[0]=resume, frame[1]=destroy</pre><p><strong>③ In the NDK, “who resumes?” — ALooper</strong></p><p>C++20 leaves “who drives it” entirely blank to you; Unity uses PlayerLoop / Update to call MoveNext every frame for you. Is there such a role in the Android NDK? Yes, my friend, there is — ALooper: the event loop of android_app::looper in android_main is the native version of PlayerLoop.</p><pre>while (!app-&gt;destroyRequested) {<br>    ALooper_pollOnce(-1, nullptr, &amp;events, &amp;data);   // your &quot;Update&quot;<br>    drain_ready_coroutines();                        // resume each ready handle in turn<br>}</pre><p>await_suspend only &quot;registers&quot; (enqueue + wake the loop with eventfd / ALooper_wake), and the callback does h.resume() — nothing more than rebuilding Unity&#39;s &quot;poll every frame → MoveNext&quot; on a different base. In one line: ALooper<strong> ≈ PlayerLoop, </strong>h.resume()<strong> ≈ </strong>MoveNext(). And the looper is thread-local, so the resume naturally happens on the loop thread — just like Unity, <strong>single-threaded, frame-by-frame</strong>.</p><blockquote><em>That’s all just some of my own loose thinking; if you folks think something’s off, or have slicker ideas, feel free to share your take in the comments.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20b647077c1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Reverse Engineering Basics: Syscalls and Inline Assembly]]></title>
            <link>https://medium.com/@axhlzy/android-reverse-engineering-basics-syscalls-and-inline-assembly-27587365f329?source=rss-c6c6420fe53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/27587365f329</guid>
            <category><![CDATA[binary-reversing]]></category>
            <category><![CDATA[android-ndk]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[axhlzy]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 01:17:54 GMT</pubDate>
            <atom:updated>2025-07-19T02:06:32.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*0nUrQ8yLEyxm9zbm.jpg" /></figure><p>In the realm of Android security and reverse engineering, direct interaction with the system’s low-level components is crucial for bypassing detection and implementing advanced functionalities. The combination of <strong>System Calls (Syscall)</strong> and <strong>Inline Assembly (Inline Asm)</strong> serves as a powerful weapon to achieve this deep-seated interaction.</p><p>This article will delve into this core technology by dissecting a simple demo project,<a href="https://github.com/axhlzy/android_example/tree/master/android_syscall">android_syscall</a> exploring it in two parts and extending to related offensive and defensive strategies.</p><h3>Part One: System Calls (Syscall) — A Bridge to the Kernel</h3><h4>1. What are System Calls?</h4><p>A <strong>System Call (Syscall)</strong> is the sole official channel for an application to request high-privileged operations from the operating system kernel. In Android (which is based on the Linux kernel), when an app needs to perform actions like file I/O, network communication, or process management, it cannot execute these directly. Instead, it must “apply” to the kernel through a system call.</p><p>On ARM-based devices, this “application” action is typically initiated by an instruction called svc (Supervisor Call). This instruction triggers a software interrupt, safely switching the CPU&#39;s processing state from the less privileged <strong>user mode</strong> to the highly privileged <strong>kernel mode</strong>. After the kernel completes the task, it returns the result to the application.</p><h4>2. Standard Implementation: The Role of Bionic libc.so</h4><p>In conventional Android development, we don’t directly write svc instructions. Android provides a lightweight C library optimized for mobile devices called <strong>Bionic</strong>, with its core residing in the libc.so file.</p><p>When we call standard functions like fopen or read, we are actually invoking wrapper functions within libc.so. Bionic&#39;s libc.so handles all the complex details and, on our behalf, executes the actual system call internally.</p><p>App (fopen) -&gt; Bionic libc.so (fopen wrapper) -&gt; Kernel (syscall)</p><h4>3. Core Issue: Why Bypass libc.so for Direct Calls?</h4><p>While libc.so is convenient to use, in the fields of reverse engineering and security, it represents a clear monitoring point. Many hooking and detection tools operate by intercepting functions within libc.so (e.g., via GOT/PLT Hooking or LD_PRELOAD to hijack fopen).</p><p>From an offensive and defensive security perspective, the purpose of directly initiating system calls is very clear:</p><ul><li><strong>Anti-Hooking and Anti-Monitoring:</strong> This is the primary goal. Suppose a malicious app wants to detect if it’s running on a rooted device. It might attempt to access the /system/bin/su file. Some root-hiding tools or security sandboxes might hook libc.so&#39;s open or stat functions to deceive it. When they detect an access path to /system/bin/su, they might directly return an &quot;file not found&quot; error. If the app uses a <strong>direct system call</strong> (e.g., raw_syscall(__NR_openat, ...)), it completely bypasses the tainted libc.so, querying the kernel directly to obtain the true result, rendering the security tool&#39;s hook ineffective.</li><li><strong>Hiding Program Behavior:</strong> Security analysis tools (like frida-trace) often analyze program behavior by tracing standard library functions. If the core logic of a program is entirely composed of direct system calls, the tracing capabilities of these high-level tools will be significantly diminished, greatly increasing the difficulty of reverse analysis.</li></ul><h4>4. The Game of Cat and Mouse</h4><p>While direct system calls can bypass libc layer monitoring, they are not undetectable. Since all system calls must pass through the kernel, defenders can deploy defenses at a lower level.</p><p>The main methods for monitoring system calls include:</p><ul><li><strong>eBPF (extended Berkeley Packet Filter):</strong> This is currently the most powerful and flexible kernel observation technology. eBPF allows developers to dynamically load a secure, sandboxed “observational code” into the kernel without modifying the kernel’s source code. Defensive tools can write an eBPF program and attach it to the kernel’s system call entry point (tracepoint:sys_enter). This way, no matter how an application initiates a system call, as long as it enters the kernel, the eBPF program can capture it immediately. An example of using stackplz for this purpose is provided.</li></ul><p>stackplz -p $(pidof android_syscall) — stack -s read,write,fstat</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHEdDmBHQ_KazPrC_WH7BQ.png" /></figure><ul><li><strong>Using strace:</strong> strace is the most commonly used system call tracing tool on Linux (based on ptrace) for debugging programs, troubleshooting problems, and analyzing performance. It can show which system calls (e.g. open, read, write) have been invoked by a program during runtime, as well as the corresponding arguments and return values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ha2IWUZyJMDDHo5mE0litQ.png" /></figure><ul><li><strong>Kernel Module (LKM):</strong> This is the most traditional and powerful way to use apatch to hook system calls. example code <a href="https://github.com/axhlzy/android_example/blob/master/android_syscall/module.c">here</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epIww5-B1nQAokebcE3PqQ.png" /></figure><p>Security is an escalating game of cat and mouse. Hooks at the application level can be circumvented by using direct system calls, but deeper kernel-level monitoring techniques are still an effective countermeasure.</p><h3>Part Two: Inline Assembly (Inline Asm) — The Sharp Tool for Low-Level Implementation</h3><p>Since the goal is to bypass libc.so, how do we manually initiate system calls? The answer lies in <strong>inline assembly</strong>.</p><h3>1. Why Use Inline Assembly Directly? What Are Its Benefits?</h3><ul><li><strong>Ultimate Control:</strong> Inline assembly allows developers pixel-level precise control over the generated machine code. You can decide which registers to use, how to manipulate the stack, the order of instructions, and more. This predictability is crucial in security and performance-sensitive scenarios, as it helps avoid unexpected behavior caused by compiler optimizations. For instance, techniques like stack overflow attacks, structured exception handling (SHE) attacks, and virtual function table attacks might leverage this.</li><li><strong>No External Dependencies, Self-Contained Code:</strong> All assembly code resides within the C++ source file. This makes the entire project more concise, reduces dependencies, and improves maintainability and portability.</li><li><strong>Accessing Areas Beyond C++’s Reach:</strong> Some operations cannot be performed in standard C++. The most typical example is obtaining the value of specific registers. You can use inline assembly to directly retrieve the address of <strong>Thread Local Storage (TLS)</strong> from a register, where this pointer is stored in the thread object managed by a specific register. Such an operation can only be accomplished by directly reading the register via inline assembly. For examples, see:</li><li>Getting task_struct:<br><a href="https://github.com/bmax121/KernelPatch/blob/e4af910982ecb17d35b632c24ce303c02ccba02e/kernel/linux/arch/arm64/include/asm/current.h#L50">kernalPatch(current.h)</a></li><li>Getting TLS:<br><a href="https://cs.android.com/android/platform/superproject/main/+/main:art/runtime/thread-current-inl.h;l=30?q=inline%20Thread*%20Thread::Current()&amp;ss=android%2Fplatform%2Fsuperproject%2Fmain">AndroidSource(thread-current-inl.h)</a><br><a href="https://github.com/canyie/pine/blob/fff37b8/core/src/main/cpp/art/thread.h#L16">Pine(thread.h)</a></li></ul><h3>2. Implementation Details of the raw_syscall Function</h3><p>The sample code provides a <strong>naked function</strong> for raw_syscall, which implements the corresponding system call logic based on different CPU architectures.</p><ul><li><strong>Adhering to Calling Convention:</strong> These assembly codes are not written arbitrarily but strictly adhere to the <strong>EABI (Embedded Application Binary Interface)</strong> of the target platform. EABI defines how parameters are passed, how return values are obtained, which registers can be freely modified, and which must be restored before the function returns.</li><li><strong>Error Handling:</strong> Linux system calls typically return a non-negative value on success (e.g., a file descriptor) and a negative value on failure, where its absolute value is the error code (e.g., ENOENT).</li></ul><h4>ARM64 (aarch64) Architecture</h4><p>The ARM64 calling convention is more concise: the system call number is placed in x8, parameters are placed sequentially starting from x0, and then svc #0 is executed.</p><pre>#if defined(__aarch64__)<br>__attribute__((naked)) long raw_syscall(long __number, ...) {<br>    __asm__ __volatile__(<br>            &quot;mov    x8, x0\n&quot;      // syscall number -&gt; x8<br>            &quot;mov    x0, x1\n&quot;      // arg1 -&gt; x0<br>            // ...<br>            &quot;svc    #0\n&quot;          // Trigger syscall<br>            &quot;ret\n&quot;                // Return<br>            : : : &quot;memory&quot;<br>    );<br>}<br>#endif</pre><h4>ARM32 (arm) Architecture</h4><p>The ARM32 convention is relatively more complex, requiring manual stack manipulation to pass more parameters. The push {r4-r7, lr} and pop {r4-r7, pc} operations here perfectly illustrate the essence of function calls and Hook Trampolines: saving the context (register state) before executing the core logic (svc #0), and restoring the context and returning after execution.</p><pre>#elif defined(__arm__)<br>__attribute__((naked)) long raw_syscall(long __number, ...) {<br>    __asm__ __volatile__(<br>            &quot;push   {r4-r7, lr}\n&quot;     // Save registers<br>            &quot;mov    r7, r0\n&quot;          // syscall number -&gt; r7<br>            // ...<br>            &quot;ldr    r4, [sp, #24]\n&quot;   // Load arg5 from stack<br>            &quot;svc    #0\n&quot;              // Trigger syscall<br>            &quot;pop    {r4-r7, pc}\n&quot;     // Restore registers and return<br>            : : : &quot;memory&quot;<br>    );<br>}<br>#endif</pre><h3>3. Upper-Layer Encapsulation and Application</h3><p>With the underlying raw_syscall in place, we can, as shown in the android_syscall project, wrap it in a C++ layer to make it easy to use and handle errors.</p><pre>int my_open(const char* pathname, int flags, mode_t mode) {<br>    long result = raw_syscall(__NR_openat, AT_FDCWD, pathname, flags, mode);<br>    if (result &lt; 0) {<br>        LOGI(&quot;open failed: %s, error: %ld&quot;, pathname, -result);<br>        return -1;<br>    }<br>    return (int)result;<br>}</pre><h3>Summary</h3><p>The <a href="https://github.com/axhlzy/android_example/tree/master/android_syscall">android_syscall</a> project uses file operations as an example to briefly introduce the specific use cases of <strong>inline assembly</strong> and <strong>system calls</strong>, as well as their applications in Android reverse engineering and security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27587365f329" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>