<?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 TimWood on Medium]]></title>
        <description><![CDATA[Stories by TimWood on Medium]]></description>
        <link>https://medium.com/@jinhopers?source=rss-59d77e44f709------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eeKoq_aeaCJ6GSRDlJSsKg.jpeg</url>
            <title>Stories by TimWood on Medium</title>
            <link>https://medium.com/@jinhopers?source=rss-59d77e44f709------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:59:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jinhopers/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[Shedding Old Baggage, I Designed My Own Agent Framework]]></title>
            <link>https://medium.com/@jinhopers/shedding-old-baggage-i-designed-my-own-agent-framework-64e2608f8c7a?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e2608f8c7a</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agent-frameworks]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 09:10:49 GMT</pubDate>
            <atom:updated>2026-06-15T09:10:49.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, before I begin, let me ask a quick question: how did you all learn about Agents?</p><p>I initially started with deep learning papers, but their mathematical principles completely overwhelmed me. Later, I found a tutorial on GitHub, but I still only had a superficial understanding; each concept was fragmented and couldn’t be systematically pieced together. Then I wondered if I wasn’t suited for AI and even considered giving up… Finally, I came up with an idea: I would create a demo of an agent, compare it with mainstream agents, and incorporate some of my own ideas. Would that work? And so, this project came about.</p><p>Great, let’s get started. But here’s the question: what is an agent? What problem does it solve? I eagerly researched various reports and even asked about GPT and Gemini. Oh, so it’s driven by LLM to complete a series of tasks (I have to complain, there are so many ridiculous terms in this field).</p><p>So I’m wondering, what can the agent do? What problems can it solve? How is it different from what I’ve encountered in the GPT Q&amp;A section on the website?</p><p>Then I remembered the local knowledge bases that were so popular last year, so why don’t I build one? I started writing scripts using Python and a vector database.</p><p>After that, with the help of AI, I started my first agent-like project: a local knowledge base. After finishing the coding, when I first executed python main.py, I saw that the local notes were first split, then embedded, and then stored in the database. Then I tried to write my first search command. I asked the local ollama 3 hey, can you tell me what’s in the local knowledge base? It quickly gave me a reply… Not bad, at least it’s a good start.</p><p>The Excitement Didn’t Last Long<br>At first, I was thrilled. It actually worked! But as I tried to make it more powerful — adding tool calling, multi-step reasoning, memory across sessions, and letting multiple agents collaborate — things quickly fell apart.<br>Python was slow when handling concurrent agents. Memory management became messy. The workflow logic turned into a spaghetti of callbacks and state machines. Every time I wanted to change the flow (add a new step, add failover, or support human-in-the-loop), I had to rewrite half the code. Debugging long-running agent sessions felt like chasing ghosts.<br>I kept thinking: “There must be a better way.”<br>Why I Chose Go<br>I’ve always loved Go for its simplicity, performance, and great concurrency support. So I asked myself — what if I rebuild this agent system in Go from the ground up?<br>That decision became the starting point of GoAgentX.<br>How GoAgentX Was Born<br>I started small, just like before — implementing basic LLM calling and simple RAG. But this time everything felt different:</p><ul><li>Goroutines made concurrent agents naturally fast and lightweight.</li><li>Strong typing and clean interfaces forced me to design clearer abstractions.</li><li>Channels and context made workflow orchestration and cancellation much more reliable.</li></ul><p>As the project grew, I gradually added the features I wished I had in my Python experiments:</p><ul><li>Dynamic DAG Workflows — Agents’ execution flow can be built and modified at runtime. No more hardcoded sequences.</li><li>Memory Distillation — Long-term memory is automatically summarized and compressed so agents don’t drown in context.</li><li>AHP (Agent-to-Agent Hierarchical Protocol) — A clean way for agents to communicate, delegate, and collaborate.</li><li>Leader + Sub-Agent architecture with Failover — If the leader fails, another agent can seamlessly take over.</li><li>Pluggable vector stores (PostgreSQL pgvector, Qdrant, etc.) and high-performance benchmarks (many operations under 1µs with zero allocation hot paths).</li></ul><p>From a simple local knowledge base demo, it evolved into a production-ready multi-agent framework.<br>What GoAgentX Is Today<br>GoAgentX is no longer just my personal learning project. It’s a general-purpose, high-performance Multi-Agent framework written in Go that focuses on reliability, observability, and scalability.<br>Whether you want to build:</p><ul><li>Complex RAG systems</li><li>Autonomous research agents</li><li>Multi-agent collaboration workflows</li></ul><p>repo: <a href="https://github.com/Timwood0x10/GoAgentX">https://github.com/Timwood0x10/GoAgentX</a></p><p>Next, I will start a series of articles to gradually break down the design concept of this project, helping everyone to better understand my design approach. Discussions and comments are welcome.</p><p>Of course, if you don’t like this narrative style, you can tell me, and I’ll try to be more serious.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e2608f8c7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OmniScope v0.2.0 — From Pattern Matching to Semantic Understanding]]></title>
            <link>https://medium.com/@jinhopers/omniscope-v0-2-0-from-pattern-matching-to-semantic-understanding-dc57a4631f8b?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc57a4631f8b</guid>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[llvm-ir]]></category>
            <category><![CDATA[ffi]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 07:59:23 GMT</pubDate>
            <atom:updated>2026-06-09T07:59:23.857Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How a static analysis tool rewired itself to understand language boundaries, resource ownership, and cross-language FFI safety.</strong></p><p><a href="https://github.com/Timwood0x10/OmniScope">v0.2.0</a> is a major architecture upgrade for OmniScope. It moves the project from a rule-heavy, multi-pass heuristic FFI detector toward a context-aware framework built around semantic resolution, function surface classification, resource contracts, and a unified Issue Gate.</p><h4>The Problem v0.1.8 Couldn’t Solve</h4><p>In v0.1.8, OmniScope was essentially a pattern matcher with good taste. It knew what free looked like, what malloc looked like, and which APIs were dangerous. But it couldn&#39;t answer the hard questions:</p><ul><li>Is this free paired with the right allocator family?</li><li>Does this pointer actually cross a language boundary, or is it local?</li><li>Is this ownership transfer intentional (e.g. Box::into_raw) or accidental?</li></ul><p>v0.2.0 was built to answer those questions.</p><p>Here is the complete architecture, from CLI input to formatted output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgtJ-9tHcatHNseICqMJbA.png" /></figure><h4>The Data Flow: How One Analysis Run Works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*py4Eew95EGWZkZvjwt_DuA.png" /></figure><p><strong>What this shows:</strong> The flow is strictly layered. Language detection happens before classification, which happens before semantic resolution, which happens before passes run. Each stage feeds the next with richer facts. The Issue Gate (G) is the bottleneck — it queries the Semantic Resolution Tree before deciding whether an issue is real.</p><h3>The Five Big Ideas in v0.2.0</h3><h4>1. SurfaceClassifier — Decide What to Analyze Before Analyzing It</h4><p>In v0.1.8, every pass independently guessed whether a function was relevant. v0.2.0 introduces a dedicated pass that classifies every function upfront:</p><ul><li><strong>boundary</strong> — highest priority, never suppressed</li><li><strong>standard_library / </strong><strong>compiler_generated / </strong><strong>runtime</strong> — skipped by default, cutting Rust drop glue and C++ ABI noise</li><li><strong>unknown</strong> — always kept for analysis, protecting recall when classification is uncertain</li></ul><p>The surface classifier runs once, producing shared facts that all downstream passes consume. This alone eliminates many false positives that v0.1.8 could not avoid because each pass worked with incomplete context.</p><h4>2. Issue Gate — Every Finding Gets Vetted Against Semantic Evidence</h4><p>In v0.1.8, if a pass saw free() on a dangerous path, it reported it. In v0.2.0, the Issue Gate queries the Semantic Resolution Tree (SRT) before emitting anything.</p><p>Examples of what the gate understands:</p><ul><li><strong>borrow_escape</strong> is fine if the pointer has heap provenance, global provenance, or comes from a mutable parameter</li><li><strong>write_to_immutable</strong> is fine if the field uses interior mutability</li><li><strong>use_after_free</strong> is fine if the release follows RAII drop semantics</li><li><strong>cross_language_free or </strong><strong>leak</strong> is fine if ownership was explicitly transferred (e.g. into_raw), or if the function uses a non-memory release path (e.g. a syscall or library-specific cleanup)</li></ul><p>The gate uses a confidence threshold of <strong>0.85</strong>. Below that, it lets the issue through rather than hiding it. This is a deliberate design choice: the system favors recall over silence when evidence is weak or conflicting.</p><h4>3. Resource Contracts — From “Saw a Free” to “Release Pair Is Correct”</h4><p>In v0.1.8, the system knew a list of allocation functions and a list of free functions. If a pointer was allocated and then freed, it was considered balanced.</p><p>v0.2.0 introduces <strong>resource families</strong> and <strong>function summaries</strong>. SSL_new should pair with SSL_free, not with free(). The contract system validates this.</p><p>Ownership models drive the behavior:</p><ul><li><strong>gc</strong>, <strong>callee</strong>, <strong>borrowed</strong> — suppress false leaks because the caller does not own the resource</li><li><strong>caller</strong>, <strong>custom</strong> — reported conservatively</li></ul><p>The key function is isValidRelease(), which checks that the release function belongs to the same resource family as the allocation. This catches mismatches that a simple malloc/free pair check would miss.</p><h4>4. SymbolGraph — Per-Symbol Language Detection</h4><p>In v0.1.8, language detection was module-level. A mixed C++/Rust file was guessed based on file extension or mangling hints.</p><p>In v0.2.0, every symbol carries its own:</p><ul><li>Language tag</li><li>ABI classification</li><li>Export surface</li><li>Cross-language call sites</li></ul><p>This fixes misclassification in real-world scenarios: C shims wrapping Rust libraries, mixed C++/Rust mangling, JNI glue code, and Python C API extensions. The SymbolGraph is the foundation that makes per-symbol reasoning possible.</p><h4>5. Shared Indexes — Don’t Scan the IR Twice</h4><p>New infrastructure in v0.2.0:</p><ul><li><strong>IRStore</strong> — pre-categorizes functions and instructions</li><li><strong>InstCache</strong> — caches opcode, operand, and callee lookups</li><li><strong>TraversalIndex</strong> — indexes functions, calls, allocations, and free sites</li></ul><p>In v0.1.8, if three passes each needed to find all call instructions, each pass rescanned the module. In v0.2.0, the scan happens once during pipeline initialization. Lookups go from O(n) to O(1). For large real-world IR corpora, this is the difference between minutes and seconds.</p><h3>The Pass Pipeline in Detail</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS5psJoHJDhM60QU56cpTg.png" /></figure><p>The dependency graph is intentionally structured. Foundation passes build shared facts and emit no issues. Analysis passes consume those facts and produce issue candidates. The gate and verifier filter those candidates.</p><h4>Foundation Passes</h4><p>These build shared evidence rather than diagnostics. Much of v0.2.0’s accuracy improvement comes from this layer:</p><ul><li><strong>cfg</strong> — Builds basic-block control-flow facts</li><li><strong>dfg</strong> — Builds def-use / value-flow facts</li><li><strong>alias</strong> — Local alias evidence for lifetime checks</li><li><strong>surface-classifier</strong> — Classifies functions into surface categories</li><li><strong>SemanticResolver</strong> — Semantic state for allocator/release/RAII</li><li><strong>call-graph</strong> — Call relationships and cross-language edges</li><li><strong>pointer-flow</strong> — Propagates pointer and taint state</li></ul><p>These passes mainly produce shared evidence. Later passes reuse a common CFG/DFG/call graph/surface/semantic view instead of rebuilding local guesses.</p><h4>FFI Boundary and Cross-Language Passes</h4><ul><li><strong>ffi-detector</strong> (no issues) — Combines declarations, calls, pointer-flow to produce FFI risk candidates</li><li><strong>ffi-boundary</strong> (emits issues) — Shared definition of FFI boundary, reports boundary issues</li><li><strong>ffi-type-mismatch</strong> (emits issues) — Cross-language integer width, signedness, pointer, enum mismatches</li><li><strong>abi-compat-checker</strong> (emits issues) — ABI-level compatibility: calling convention, parameter/return representation</li><li><strong>ffi-body-check</strong> (emits issues) — Checks exported function bodies for risky patterns</li><li><strong>ffi-unsafe</strong> (emits issues) — Finds unsafe APIs in boundary context</li><li><strong>ownership-violation</strong> (no issues) — Analyzes ownership violations via pointer-flow</li><li><strong>cross-lang-dataflow</strong> (emits issues) — Tracks values created in one language and consumed in another</li></ul><p>Key responsibility split:</p><ul><li>ffi-boundary is the boundary fact producer for all downstream FFI passes</li><li>ffi-type-mismatch, abi-compat-checker, and layout_mismatch separate type, ABI, and layout so reports can point to narrower causes</li><li>cross-lang-dataflow connects boundary evidence with pointer-flow — the main path for cross-language ownership reasoning</li></ul><h4>New v0.2.0 FFI-Specific Passes</h4><ul><li><strong>layout_mismatch</strong> — Struct layout, padding, alignment mismatches across language boundaries</li><li><strong>string_safety_ffi</strong> — Loss of string length, encoding, NUL termination across FFI</li><li><strong>unwind-boundary</strong> — Exceptions or panics crossing non-unwind-safe boundaries</li><li><strong>callback-lifecycle</strong> — Callback registration, unregistration, context retention</li><li><strong>gc-safety</strong> — JNI/Python/GC runtime object references across FFI</li><li><strong>error-propagation-tracer</strong> — Errors crossing FFI, dropped or mistranslated error values</li><li><strong>jni-leak-detector</strong> — JNI local/global reference leaks</li></ul><h4>Lifetime, Ownership, and Memory-Safety Passes</h4><ul><li><strong>ptr-lifetime</strong> (emits issues) — Tracks allocation/free/escape, updates MemoryGraph</li><li><strong>danger-surface</strong> (no issues) — Marks paths near FFI as report-relevant</li><li><strong>pointer-ownership</strong> (no issues) — Tracks allocation/release/transfer evidence at boundaries</li><li><strong>memory-safety</strong> (emits issues) — Double free, use-after-free, leak-like behavior</li><li><strong>free-validation</strong> (emits issues) — Validates pointer origin, allocator family, release family</li><li><strong>malloc-check</strong> (emits issues) — Checks allocation return values for null</li><li><strong>buffer-overflow</strong> (emits issues) — Risky copy/format/buffer operations</li><li><strong>integer-overflow</strong> (emits issues) — Integer overflows affecting size/count/allocation lengths</li><li><strong>return-check</strong> (emits issues) — Ignored return values from allocation/I/O/syscall APIs</li><li><strong>lock</strong> (emits issues) — Lock/unlock imbalance and concurrency patterns</li></ul><p>Responsibility split:</p><ul><li>ptr-lifetime gathers lifetime facts</li><li>danger-surface decides whether facts are relevant enough to report</li><li>memory-safety and free-validation are the main reporters</li><li>pointer-ownership and the resource model explain cross-language ownership transfer; they are not equivalent to reporting</li></ul><h4>Language and Runtime-Specific Passes</h4><ul><li><strong>rust-ffi-filter</strong> (emits issues) — Rust FFI ownership transfer, into_raw/from_raw, borrow escape, drop glue</li><li><strong>callback-escape</strong> (emits issues) — Callbacks retaining stack pointers or state beyond language lifetime</li><li><strong>gc-safety</strong> (emits issues) — GC-managed object reference safety across FFI</li><li><strong>jni-leak-detector</strong> (emits issues) — JNI reference handling and leaks</li></ul><h3>v0.1.8 vs v0.2.0</h3><ul><li><strong>Main goal</strong>: output standardization → Semantic-analysis and multi-language FFI architecture upgrade</li><li><strong>Boundary model</strong>: Module/pass-level heuristics → SymbolGraph + per-symbol language/ABI/export surface</li><li><strong>Noise control</strong>: Local pass filters and whitelists → SurfaceClassifier + SRT-backed Issue Gate + Resource Contracts</li><li><strong>Ownership</strong>: Allocation/free registry → Resource families, summaries, ownership transfer, lifecycle contracts</li><li><strong>Language handling</strong>: Registry and detection rules → Adapter framework + language overrides + per-symbol classification</li><li><strong>FFI coverage</strong>: Core FFI/memory-safety checks → ABI/type/layout/string/unwind/callback/GC/JNI/cross-lang dataflow</li><li><strong>Performance</strong>: Bug fixes, reduced repeated traversal → IRStore, InstCache, TraversalIndex, arenas, string interning</li><li><strong>Tests</strong>: Integration/red-team tests → Inline IR matrix, cross-language suite, golden baselines, real-world corpus</li></ul><h3>Summary</h3><p>v0.2.0 upgrades OmniScope from “find suspicious patterns” to “understand language boundaries, resource ownership, and semantic context before reporting suspicious issues.”</p><p>The core insight is simple: pattern matching tells you <em>what</em> happened. Semantic understanding tells you <em>why</em> it happened — and whether it’s actually a problem.</p><p>Finally, let me reiterate that the goal of version 0.2.x remains performance optimization and TP improvement. Additionally, a Rust version is currently under development, and the plan is to use a completely different architecture to achieve this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc57a4631f8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arc/Rc Clone Detection: Why StackOwner Matters]]></title>
            <link>https://medium.com/@jinhopers/arc-rc-clone-detection-why-stackowner-matters-e2925cc16a09?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2925cc16a09</guid>
            <category><![CDATA[rust-memory-safety]]></category>
            <category><![CDATA[memory-analysis]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Sat, 23 May 2026 15:36:00 GMT</pubDate>
            <atom:updated>2026-05-23T15:36:00.509Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 4 of the memscope-rs feature breakdown series.Tracking shared ownership in Rust without hardcoding ArcInner offsets.</p><p>Rust’s ownership model is strong, but things become less intuitive once you get into shared ownership.</p><p>Arc&lt;T&gt; and Rc&lt;T&gt; are inherently safe abstractions, but they make memory ownership opaque:</p><pre>  let root = Arc::new(vec![1, 2, 3]);<br><br>  let worker_a = Arc::clone(&amp;root);<br>  let worker_b = Arc::clone(&amp;root);</pre><p>From a business semantics perspective, there are now three owners sharing the same data.</p><p>However, from the perspective of the underlying allocator, it may only see the initial heap allocation.</p><p>This is the problem:</p><blockquote>Cloning Arc/Rc doesn’t necessarily create a new heap allocation, but it does change the ownership graph.</blockquote><p>Memscope-rs doesn’t handle this by hooking Arc::clone() or reading Rust’s private ArcInner layout. It uses a more pragmatic model:</p><blockquote>Treating Arc/Rc as an owner on the stack, recording its own stack pointer and the heap pointer it points to.</blockquote><p>This model is called <strong>StackOwner</strong> in the project.</p><h4>Why Arc/Rc Are Hard to Observe</h4><p>A typical heap profiler excels at answering:</p><ul><li>Where was memory allocated?</li><li>How many bytes were allocated?</li><li>Was it freed?</li></ul><p>But for Arc/Rc, these questions aren’t enough. What we really want to know is:</p><ul><li>which variables point to the same allocation?</li><li>how many tracked smart pointers share this heap object?</li><li>where does shared ownership fan out?</li><li>is this an Arc/Rc clone pattern?</li></ul><p>The problem is that <em>Arc::clone() / Rc::clone()</em> typically just copies the smart pointer and increments the reference count.</p><p>It doesn’t necessarily create a new block of user data allocation like <em>Vec::new()</em>.</p><p>Therefore, if you only rely on <strong>GlobalAlloc</strong>, you can see heap allocation, but you won’t see the clone relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*cAe_Wvi34IZCqatnewVhsg.png" /><figcaption>stackOwner</figcaption></figure><p>This is also why memscope-rs introduced StackOwner.</p><h4>The Key Insight: Arc/Rc Are Stack Owners</h4><p>Arc&lt;T&gt; and Rc&lt;T&gt; are not T itself. They are <strong>smart pointer values</strong>.</p><p>These smart pointer values ​​typically reside <strong>on the stack</strong>, in a struct field, or are moved to other contexts. Internally, they point to data on the heap.</p><p>Therefore, memscope-rs models them as:</p><pre>TrackKind::StackOwner {<br>      ptr: stack_ptr,<br>      heap_ptr,<br>      size,<br>  }</pre><p>The TrackKind definition in the source code includes this class.</p><pre>  pub enum TrackKind {<br>      HeapOwner { ptr: usize, size: usize },<br>      Container,<br>      Value,<br>      StackOwner {<br>          ptr: usize,<br>          heap_ptr: usize,<br>          size: usize,<br>      },<br>  }</pre><p>The core of this design consists of two pointers:</p><ul><li>stack_ptr : The address of the smart pointer itself;</li><li>heap_ptr : The address of the data that the smart pointer points to after dereferencing.</li></ul><p>In other words:</p><pre>  Arc variable on stack  ---&gt;  heap data<br>  Rc variable on stack   ---&gt;  heap data</pre><p>If multiple different stack_ptr points to the same heap_ptr, they form a <strong>shared ownership structure</strong>.</p><h4>How Arc&lt;T&gt; Is Implemented as Trackable</h4><p>memscope-rs supplements std types with Rust-level memory semantics through the Trackable trait.</p><p>The implementation of Arc&lt;T&gt; is roughly as follows:</p><pre>impl&lt;T&gt; Trackable for std::sync::Arc&lt;T&gt; {<br>      fn track_kind(&amp;self) -&gt; TrackKind {<br>          let stack_ptr = self as *const _ as usize;<br>          let heap_ptr = &amp;**self as *const T as usize;<br><br>          TrackKind::StackOwner {<br>              ptr: stack_ptr,<br>              heap_ptr,<br>              size: std::mem::size_of::&lt;T&gt;(),<br>          }<br>      }<br><br>      fn get_type_name(&amp;self) -&gt; &amp;&#39;static str {<br>          &quot;Arc&lt;T&gt;&quot;<br>      }<br><br>      fn get_ref_count(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(std::sync::Arc::strong_count(self))<br>      }<br><br>      fn get_data_ptr(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(&amp;**self as *const T as usize)<br>      }<br><br>      fn get_data_size(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(std::mem::size_of::&lt;T&gt;())<br>      }<br>  }</pre><p>Rc&lt;T&gt; follows the same approach:</p><pre>  impl&lt;T&gt; Trackable for std::rc::Rc&lt;T&gt; {<br>      fn track_kind(&amp;self) -&gt; TrackKind {<br>          let stack_ptr = self as *const _ as usize;<br>          let heap_ptr = &amp;**self as *const T as usize;<br><br>          TrackKind::StackOwner {<br>              ptr: stack_ptr,<br>              heap_ptr,<br>              size: std::mem::size_of::&lt;T&gt;(),<br>          }<br>      }<br><br>      fn get_ref_count(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(std::rc::Rc::strong_count(self))<br>      }<br>  }</pre><p>Note:</p><ul><li>It does not read internal fields of ArcInner&lt;T&gt;;</li><li>It does not assume strong count at a certain offset;</li><li>It only uses data pointers that can be obtained through Rust safe dereferencing;</li><li>strong_count() exists as auxiliary information, but the main clone detection path does not rely on it.</li></ul><h4>What Happens When You Call track!</h4><p>When the user calls: <strong>track!(tracker, arc_data);</strong></p><p>The <em>track! </em>macro passes the variable name, file, line number, and module path to `tracker`.</p><p>If the variable is `Arc&lt;T&gt;` or `Rc&lt;T&gt;`, `track_kind()` will return <strong>StackOwner</strong>.</p><p>Then Tracker::track_inner() will enter a dedicated StackOwner branch.</p><pre>  TrackKind::StackOwner {<br>      ptr: stack_ptr,<br>      heap_ptr,<br>      size,<br>  } =&gt; {<br>      self.inner.track_allocation(stack_ptr, size);<br><br>      let mut event = MemoryEvent::allocate(heap_ptr, size, thread_id);<br>      event.var_name = Some(name.to_string());<br>      event.type_name = Some(type_name.clone());<br>      event.source_file = Some(file.to_string());<br>      event.source_line = Some(line);<br>      event.module_path = Some(module_path.to_string());<br>      event.stack_ptr = Some(stack_ptr);<br><br>      self.event_store.record(event);<br>  }</pre><p>Here’s a crucial design detail:</p><ul><li>event.ptr stores the heap_ptr</li><li>event.stack_ptr stores the address of the smart pointer itself</li></ul><p>This allows us to see the following during the later analysis phase:</p><pre>root      stack_ptr = S1, heap_ptr = H<br>worker_a  stack_ptr = S2, heap_ptr = H<br>worker_b  stack_ptr = S3, heap_ptr = H</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOa4F-Y1BMUYr1IaI_e1sQ.png" /></figure><h4>How the Event Stores StackOwner Metadata</h4><p>There is a special field in MemoryEvent</p><pre> pub struct MemoryEvent {<br>      pub ptr: usize,<br>      pub size: usize,<br>      pub var_name: Option&lt;String&gt;,<br>      pub type_name: Option&lt;String&gt;,<br>      pub source_file: Option&lt;String&gt;,<br>      pub source_line: Option&lt;u32&gt;,<br>      pub module_path: Option&lt;String&gt;,<br>      pub stack_ptr: Option&lt;usize&gt;,<br>      ...<br>  }</pre><p>This indicates that StackOwner doesn’t just exist within TrackKind.</p><p>It is actually <strong>written to the event stream</strong>. This is important because subsequent relation inference isn’t guessed, but based on the stack_ptr metadata in the event.</p><h4>Detection Strategy: Group StackOwners by heap_ptr</h4><p>The core logic of Arc/Rc clone detection is in <strong>shared_detector.</strong></p><pre>// Strategy 2: StackOwner-based detection (for Arc/Rc)<br>// Find all StackOwner allocations (Arc/Rc) and group them by their heap_ptr<br><br>// The implementation logic can be simplified to:<br><br>  let mut stack_owners: Vec&lt;(usize, usize)&gt; = Vec::new();<br><br>  for (i, record) in records.iter().enumerate() {<br>      if let Some(stack_ptr) = record.stack_ptr {<br>          if stack_ptr &gt; 0x1000 {<br>              stack_owners.push((i, record.ptr));<br>          }<br>      }<br>  }<br><br>  let mut heap_to_records: HashMap&lt;usize, Vec&lt;usize&gt;&gt; = HashMap::new();<br><br>  for (record_id, heap_ptr) in stack_owners {<br>      heap_to_records.entry(heap_ptr).or_default().push(record_id);<br>  }<br><br>  for (_heap_ptr, record_ids) in heap_to_records {<br>      if record_ids.len() &gt;= 2 {<br>          for i in 0..record_ids.len() {<br>              for j in (i + 1)..record_ids.len() {<br>                  relations.push(RelationEdge {<br>                      from: record_ids[i],<br>                      to: record_ids[j],<br>                      relation: Relation::ArcClone,<br>                  });<br>              }<br>          }<br>      }<br>  }</pre><p>The algorithm is very simple:</p><p>1. Find the records with stack_ptr;</p><p>2. Group them by record.ptr;</p><p>3. Here, record.ptr is heap_ptr for StackOwner;</p><p>4. If the same heap_ptr corresponds to multiple records, generate an ArcClone relation.</p><p>The advantage of this strategy is not its complexity, but its interpretability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCNvFOcncDl4N13BzeMDTA.png" /><figcaption><strong>shared_detector</strong></figcaption></figure><h4>Why This Avoids Fragile ArcInner Assumptions</h4><p>A common but dangerous practice is attempting to parse the internal structure of Arc:</p><ul><li>Where are the strong counts?</li><li>Where are the weak counts?</li><li>What is the data pointer offset?</li><li>Does the layout change across different Rust versions?</li><li>Are Arc&lt;T&gt; and Rc&lt;T&gt; completely identical?</li></ul><p>memscope-rs doesn’t take this approach. It doesn’t hardcode the ArcInner&lt;T&gt; layout. It only cares about more stable external facts:</p><p>Multiple tracked smart pointers point to the same heap data pointer.</p><p>This is more pragmatic than reading internal fields. Of course, this also means it’s not “compiler-level precise clone tracing.”</p><p>A more accurate description is: <strong>StackOwner-based shared ownership detection.</strong></p><p>In other words, based on the observed relationship between the stack owner and heap pointer, the shared ownership candidate is reconstructed.</p><h4>What the Test Actually Verifies</h4><p>The project includes a corresponding test: <em>test_stackowner_arc_clone_detection</em>.</p><p>The test constructs three different `stack_ptr` values:`</p><pre>let heap_ptr = 0x3000;<br>let stack_ptr1 = 0x7ff0000;<br>let stack_ptr2 = 0x7ff0008;<br>let stack_ptr3 = 0x7ff0010;<br><br>// Then make them all point to the same heap_ptr:<br><br>let records = vec![<br>      make_record_with_stack_ptr(0, heap_ptr, stack_ptr1, 48, None, TypeKind::Buffer),<br>      make_record_with_stack_ptr(1, heap_ptr, stack_ptr2, 48, None, TypeKind::Buffer),<br>      make_record_with_stack_ptr(2, heap_ptr, stack_ptr3, 48, None, TypeKind::Buffer),<br>  ];<br>// Finally call<br>let shared = detect_shared(&amp;records, &amp;existing_edges);<br><br>// And asserts the existence of ArcClone edges:<br><br>let arc_clone_edges: Vec&lt;_&gt; = shared<br>      .iter()<br>      .filter(|e| matches!(e.relation, Relation::ArcClone))<br>      .collect();<br><br>assert!(!arc_clone_edges.is_empty(), &quot;Should have ArcClone edges&quot;);<br></pre><p>In other words, when multiple StackOwner records point to the same heap_ptr, an ArcClone relation can be generated.</p><h4>A Practical Example</h4><pre>use memscope_rs::{global_tracker, init_global_tracking, track, MemScopeResult};<br>  use std::sync::Arc;<br><br>  fn main() -&gt; MemScopeResult&lt;()&gt; {<br>      init_global_tracking()?;<br>      let tracker = global_tracker()?;<br><br>      let root = Arc::new(vec![1, 2, 3, 4]);<br><br>      let worker_a = Arc::clone(&amp;root);<br>      let worker_b = Arc::clone(&amp;root);<br><br>      track!(tracker, root);<br>      track!(tracker, worker_a);<br>      track!(tracker, worker_b);<br><br>      tracker.export_json(&quot;MemoryAnalysis/arc_clone_demo&quot;)?;<br>      tracker.export_html(&quot;MemoryAnalysis/arc_clone_demo&quot;)?;<br><br>      Ok(())<br>  }</pre><p>The key point of this example is:</p><pre> track!(tracker, root);<br> track!(tracker, worker_a);<br> track!(tracker, worker_b);</pre><p>If you don’t track the cloned variable, the new variable will not enter the event stream as a StackOwner.</p><blockquote>tips: Currently, memscope-rs does not automatically hook all Arc::clone() calls; instead, it relies on explicit tracking to record smart pointer variables.</blockquote><h4>What This Can Detect</h4><p>Practically speaking, the current implementation can detect:</p><ul><li>Multiple Arc&lt;T&gt; recorded by `track!` pointing to the same heap data;</li><li>Multiple Rc&lt;T&gt; recorded by `track!` pointing to the same heap data;</li><li>Shared ownership fan-out;</li><li>StackOwner-based clone relationship candidate;</li><li>ArcClone edge in the relation graph;</li><li>The basis for certain clone storm analyses.</li></ul><p>A more accurate statement is:</p><p><strong>It detects observed shared ownership among tracked StackOwner values.</strong></p><h4>What This Cannot Detect</h4><p>The current implementation cannot guarantee detection:</p><ul><li>Untracked Arc/Rc clones;</li><li>Precise call points where clones occurred;</li><li>History of every strong count change;</li><li>Smart pointers created but with extremely short lifecycles that were not tracked;</li><li>Intermediate values ​​of variables whose forms are no longer observable after compiler optimization;</li><li>Reference counts in foreign code or other runtime environments;</li><li>Complete borrow/move semantics;</li><li>The true business meaning of all Rc cycles.</li></ul><pre> track! Arc/Rc variable<br>      -&gt; Trackable::track_kind()<br>      -&gt; TrackKind::StackOwner<br>      -&gt; MemoryEvent with stack_ptr<br>      -&gt; relation inference groups by heap_ptr<br>      -&gt; ArcClone relation</pre><blockquote>tips:</blockquote><blockquote>Runtime overhead mainly comes from explicitly tracking Arc/Rc variables as StackOwner events. The clone relation itself is reconstructed during post-analysis by grouping records with the same heap pointer. The current benchmark suite does not isolate StackOwner grouping as a standalone benchmark</blockquote><h4>Why StackOwner Matters</h4><p>StackOwner is important not because it’s complex, but because it perfectly encapsulates the true nature of Arc/Rc:</p><ul><li>Smart pointer values ​​live somewhere</li><li>Smart pointers point to heap data</li><li>Multiple smart pointers may point to the same heap data</li></ul><p>This is precisely the runtime structure of shared ownership.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-afst0cxBTbmrZScPLH3oA.png" /></figure><p>It transforms a Rust semantics problem into an observable data problem: <strong>Which stack owners point to the same heap object?</strong></p><h4>Summary</h4><p>Arc/Rc clone detection is a design feature in memscope-rs that deserves its own discussion.</p><p>It doesn’t attempt to magically hook every clone. nor does it rely on Rust’s private memory layout.</p><p>It does something more pragmatic:</p><ul><li>Modeling Arc/Rc as StackOwners;</li><li>Logging stack_ptr and heap_ptr;</li><li>Writing this metadata to an event stream;</li><li>Grouping by heap_ptr in the post-analysis phase;</li><li>Generating shared/clone relations for multiple StackOwners within the same group.</li></ul><p>This isn’t “perfect ownership tracing.”</p><p>But it’s a clear, interpretable, and scalable shared ownership detection model. This capability is highly valuable for Rust projects.</p><p>Because often, memory issues don’t stem from unsafety, but from “too safe, too convenient” shared ownership:</p><pre>Arc::clone(&amp;state)<br>Rc::clone(&amp;node)<br>Arc&lt;Mutex&lt;HashMap&lt;...&gt;&gt;&gt;<br>Rc&lt;RefCell&lt;Node&gt;&gt;</pre><p>The significance of StackOwner lies here: I<strong>t transforms the shared ownership hidden behind smart pointers back into observable, analyzable, and discussable data.</strong></p><p>In the next article, we will discuss how memscope handles asynchronous tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2925cc16a09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unsafe and FFI Memory Passport: Tracking Memory Across Rust’s Trust Boundary]]></title>
            <link>https://medium.com/@jinhopers/unsafe-and-ffi-memory-passport-tracking-memory-across-rusts-trust-boundary-c73b5caf14f2?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/c73b5caf14f2</guid>
            <category><![CDATA[unsafe-rust]]></category>
            <category><![CDATA[memory-analysis]]></category>
            <category><![CDATA[memorypassport]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Sat, 23 May 2026 01:21:00 GMT</pubDate>
            <atom:updated>2026-05-23T01:21:00.441Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust provides strong safety, but it’s not a system that <strong>automatically interprets everything</strong>.</p><p>Once code crosses these boundaries, things start to become less transparent:</p><ul><li>unsafe blocks</li><li>raw pointers</li><li>std::alloc::alloc</li><li>C malloc/free</li><li>raw pointers returned by external libraries</li><li>cross-language ownership contracts</li></ul><p>These types of memory behaviors are often not directly visible to the compiler, but rather truly implemented at runtime.</p><p>The third article in memscope-rs revolves around this issue.</p><p>How to create an <strong>identity profile</strong> for memory that crosses Rust’s trust boundaries — that is, a memory passport.</p><p>This article doesn’t pretend that memscope-rs can prove unsafe code is safe. What it does is more practical:</p><ul><li>Record where the memory comes from;</li><li>Record which boundaries it crosses;</li><li>Record whether it is ultimately freed by Rust or taken over by foreign code;</li><li>Record whether warning signs such as double free, invalid free, or potential leak occur.</li></ul><h3>Why Unsafe and FFI Need a Separate Model</h3><p>If you only look at the allocator hook, you’ll see:</p><ul><li>pointer</li><li>size</li><li>alloc/free event</li></ul><p>But that’s not enough.</p><p>When memory is manually managed via FFI or unsafe methods, the real questions become:</p><ul><li>Who created this memory?</li><li>Is it managed by Rust or foreign code?</li><li>Has it been handed over?</li><li>Has it been freed by the foreign side?</li><li>Has it been incorrectly freed multiple times?</li><li>Is it lingering in foreign custody for an extended period?</li></ul><p>This is the significance of a memory passport. It’s not a single event, but a lifecycle logger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfawAjTqbPUtpsNQycppVw.png" /><figcaption>memory-passport</figcaption></figure><h3>The Main Idea: A Passport for Memory</h3><p>memscope-rs treats each cross-boundary memory segment as an object file.</p><p>This file includes:</p><ul><li>allocation pointer</li><li>size</li><li>type name</li><li>variable name</li><li>lifecycle events</li><li>status at shutdown</li><li>metadata</li></ul><p>The structure of MemoryPassport is defined as follows in the source code:</p><pre>  pub struct MemoryPassport {<br>      pub passport_id: String,<br>      pub allocation_ptr: usize,<br>      pub size_bytes: usize,<br>      pub type_name: String,<br>      pub var_name: String,<br>      pub status_at_shutdown: PassportStatus,<br>      pub lifecycle_events: Vec&lt;PassportEvent&gt;,<br>      pub created_at: u64,<br>      pub updated_at: u64,<br>      pub metadata: HashMap&lt;String, String&gt;,<br>  }</pre><p>Its design is not for being “cooler”, but for merging runtime facts and boundary semantics together.</p><h3>Allocation Source: Where Did This Memory Come From?</h3><p>The first key dims of passport is <strong>AllocationSource</strong>. In the source code, it is divided into several categories:</p><pre>  pub enum AllocationSource {<br>      RustSafe,<br>      UnsafeRust {<br>          unsafe_block_location: String,<br>          call_stack: CallStackRef,<br>          risk_assessment: RiskAssessment,<br>      },<br>      FfiC {<br>          resolved_function: ResolvedFfiFunction,<br>          call_stack: CallStackRef,<br>          libc_hook_info: LibCHookInfo,<br>      },<br>      CrossBoundary {<br>          from: Box&lt;AllocationSource&gt;,<br>          to: Box&lt;AllocationSource&gt;,<br>          transfer_timestamp: u128,<br>          transfer_metadata: TransferMetadata,<br>      },<br>  }</pre><p>The key concepts here are:</p><ul><li>RustSafe: Normal Rust allocation;</li><li>UnsafeRust: Manual allocation via unsafe;</li><li>FfiC: Allocation from C/external libraries;</li><li>CrossBoundary: Ownership transfer has occurred.</li></ul><p>This means that passport doesn’t just know <strong>this memory exists</strong>, but also knows: <strong><em>From which trust domain does it enter the system?</em></strong></p><h3>Safety Violations: What Can Go Wrong</h3><p>memscope-rs does not claim to <strong>verify</strong> the logic of unsafe; what it does is record signs of danger.</p><pre>pub enum SafetyViolation {<br>      DoubleFree { ... },<br>      InvalidFree { ... },<br>      PotentialLeak { ... },<br>      CrossBoundaryRisk { ... },<br>  }</pre><p>These four signals correspond to:</p><ul><li>DoubleFree: The same pointer is freed twice;</li><li>InvalidFree: An attempt is made to free a pointer not in the table;</li><li>PotentialLeak: The pointer has not been freed for an extended period;</li><li>CrossBoundaryRisk: Cross-boundary operations pose a risk.</li></ul><p>These should be written as candidate / risk / suspicious, rather than absolute conclusions.</p><p>Because runtime records can only prove:</p><ul><li>An event occurred;</li><li>An abnormal pointer state;</li><li>An unclosed lifetime.</li></ul><p>But it cannot automatically prove the semantic truth of all ownership contracts.</p><h3>The Passport Tracker: Recording Lifecycle, Not Just Events</h3><p><strong><em>MemoryPassportTracker </em></strong>is the core of this model. It not only records the passport itself, but also the <strong>passport’s lifecycle event</strong>s.</p><h4>Create passport</h4><p>An initial event is inserted when a passport is created:</p><pre>pub fn create_passport(<br>      &amp;self,<br>      allocation_ptr: usize,<br>      size_bytes: usize,<br>      initial_context: String,<br>      type_name: Option&lt;String&gt;,<br>      var_name: Option&lt;String&gt;,<br>  ) -&gt; TrackingResult&lt;String&gt; {<br>      let passport_id = self.generate_passport_id(allocation_ptr)?;<br><br>      let initial_event = PassportEvent {<br>          event_type: PassportEventType::AllocatedInRust,<br>          timestamp: current_time,<br>          context: initial_context,<br>          call_stack: self.capture_call_stack()?,<br>          metadata: HashMap::new(),<br>          sequence_number: self.get_next_event_sequence(),<br>      };<br><br>      let passport = MemoryPassport {<br>          passport_id: passport_id.clone(),<br>          allocation_ptr,<br>          size_bytes,<br>          type_name: type_name.unwrap_or_else(|| &quot;-&quot;.to_string()),<br>          var_name: var_name.unwrap_or_else(|| &quot;-&quot;.to_string()),<br>          status_at_shutdown: PassportStatus::Unknown,<br>          lifecycle_events: vec![initial_event],<br>          created_at: current_time,<br>          updated_at: current_time,<br>          metadata: HashMap::new(),<br>      };<br>      ...<br>  }</pre><h4>Record boundary events</h4><p>Different events can be recorded for the same passport subsequently:</p><ul><li>HandoverToFfi</li><li>FreedByForeign</li><li>ReclaimedByRust</li><li>BoundaryAccess</li><li>OwnershipTransfer</li><li>ValidationCheck</li><li>CorruptionDetected</li></ul><p>This is important because a passport is not a static tag, but a lifecycle track.</p><h4>Status at Shutdown: The Final State Matters</h4><p>The passport will have a status when the process ends.</p><pre> pub enum PassportStatus {<br>      FreedByRust,<br>      HandoverToFfi,<br>      FreedByForeign,<br>      ReclaimedByRust,<br>      InForeignCustody,<br>      Unknown,<br>  }</pre><p>This is actually a very practical summary layer:</p><ul><li>FreedByRust: Rust has been reclaimed and released;</li><li>HandoverToFfi: Handed over to the foreign side but not yet reclaimed;</li><li>FreedByForeign: Foreign code has been released;</li><li>InForeignCustody: Held externally, potentially a leak;</li><li>Unknown: State is unclear.</li></ul><p>The value of this part lies in compressing the <strong>runtime lifecycle</strong> into a final state, making it easy to export and report.</p><h3>A Concrete Example: Unsafe Rust and FFI in the Showcase</h3><p>The most direct example in the repo is <em>examples/global_tracker_showcase.rs</em>.</p><h4>Unsafe Rust allocation</h4><pre>unsafe {<br>      let layout = Layout::new::&lt;[i32; 64]&gt;();<br>      let ptr = alloc(layout);<br><br>      if !ptr.is_null() {<br>          tracker<br>              .create_passport(ptr as usize, layout.size(), format!(&quot;unsafe_vec_{}&quot;, i))<br>              .map_err(|e| { ... })?;<br><br>          let slice = std::slice::from_raw_parts_mut(ptr as *mut i32, 64);<br>          for (j, item) in slice.iter_mut().enumerate() {<br>              *item = (i * 100 + j) as i32;<br>          }<br><br>          dealloc(ptr, layout);<br>      }<br>  }</pre><p>The key point here isn’t the general statement that “unsafe is dangerous,” but rather:</p><ul><li>Alloc is done manually;</li><li>Passport is created immediately after allocation;</li><li>Memory content is written via raw pointers;</li><li>Finally, it is manually freed.</li></ul><p>This is a typical unsafe lifecycle path.</p><h4>FFI allocation</h4><pre>extern &quot;C&quot; {<br>      fn malloc(size: usize) -&gt; *mut std::ffi::c_void;<br>      fn free(ptr: *mut std::ffi::c_void);<br>  }<br><br>  let ffi_ptr = unsafe { malloc(size) };<br><br>  if !ffi_ptr.is_null() {<br>      tracker<br>          .create_passport(ffi_ptr as usize, size, format!(&quot;ffi_alloc_{}&quot;, i))?;<br><br>      tracker.record_handover(<br>          ffi_ptr as usize,<br>          &quot;foreign_function&quot;.to_string(),<br>          format!(&quot;ffi_call_{}&quot;, i),<br>      );<br><br>      unsafe {<br>          std::ptr::write_bytes(ffi_ptr as *mut u8, (0x40 + i) as u8, size);<br>          free(ffi_ptr);<br>      }<br>  }</pre><p>The source code description is very clear.</p><ul><li>Allocation originates from malloc</li><li>The Rust side only knows it as *mut c_void</li><li>Ownership is marked out via record_handover()</li><li>Freeing occurs under foreign allocator semantics</li></ul><p>This is precisely where memory passports are used.</p><h3>How the Global Tracker Wires It Together</h3><p>The unsafe/FFI model does not exist in isolation; it is integrated into a unified interface through <strong>GlobalTracker</strong>.</p><pre>pub fn create_passport(&amp;self, ptr: usize, size: usize, context: String) -&gt; Result&lt;String, ...&gt;<br>pub fn record_handover(&amp;self, ptr: usize, context: String, function: String)<br>pub fn record_free(&amp;self, ptr: usize, context: String, function: String)<br>pub fn detect_leaks(&amp;self) -&gt; LeakDetectionResult</pre><h4>Export Pipeline: Where the Passport Goes</h4><p>The passport doesn’t just exist in memory; it’s exported.</p><p><em>export_all_json()</em> will output several related files:</p><ul><li>memory_passports.json</li><li>leak_detection.json</li><li>unsafe_ffi.json</li></ul><h4>Memory passports export</h4><pre>let passport_data: Vec&lt;_&gt; = passports<br>      .values()<br>      .map(|p| {<br>          serde_json::json!({<br>              &quot;passport_id&quot;: p.passport_id,<br>              &quot;allocation_ptr&quot;: format!(&quot;0x{:x}&quot;, p.allocation_ptr),<br>              &quot;size_bytes&quot;: p.size_bytes,<br>              &quot;created_at&quot;: p.created_at,<br>              &quot;lifecycle_events&quot;: p.lifecycle_events.len(),<br>              &quot;status&quot;: format!(&quot;{:?}&quot;, p.status_at_shutdown),<br>          })<br>      })<br>      .collect();</pre><h4>Unsafe FFI export</h4><pre> let ffi_reports: Vec&lt;_&gt; = passports<br>      .values()<br>      .filter(|p| {<br>          matches!(<br>              p.status_at_shutdown,<br>              PassportStatus::HandoverToFfi<br>                  | PassportStatus::InForeignCustody<br>                  | PassportStatus::FreedByForeign<br>          )<br>      })<br>      ...</pre><h3>What This Module Can and Cannot Prove</h3><h4>memscope-rs can observe:</h4><ul><li>Pointer creation</li><li>Size</li><li>Call stack</li><li>Unsafe block location</li><li>FFI function name</li><li>Handover / Free / Reclaim events</li><li>Final status at shutdown</li></ul><h4>It can flag</h4><ul><li>invalid free</li><li>double free</li><li>potential leak</li><li>cross-boundary risk</li></ul><h4>It cannot prove</h4><ul><li>Unsafe block logic is always safe.</li><li>Foreign code always adheres to the ownership contract.</li><li>All external pointers can be fully traced back to their source.</li><li>The call stack hash equals the complete stack semantics.</li></ul><h3>Why Memory Passport Is a Useful Concept</h3><p>The advantage of this concept is that it expresses cross-boundary issues very intuitively. To be honest, I designed it with reference to the concept of a passport, hence the name “Memory Passport”.</p><ul><li>allocation origin</li><li>lifecycle stamps</li><li>current custody</li><li>validity status</li><li>safety violations</li></ul><p>Can think of it as a memory “passport”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAHGrJvf_ElgNSQovF38Sg.png" /></figure><p>Its value lies not in its visual appeal, but in its practicality:</p><ul><li>Better for auditing;</li><li>Better for exporting;</li><li>Better for integration with dashboards;</li><li>Better for explaining the lifecycle of unsafe/FFI.</li></ul><h3>Summary</h3><p>The most important point here isn’t that “unsafe is dangerous,” but rather:</p><blockquote>Once memory leaves Rust’s safety boundaries, we no longer just look at the allocation itself, but at its identity, origin, destination, and final state.</blockquote><p>memscope-rs’ memory passport does exactly this:</p><ul><li>Gives unsafe allocations a traceable identity;</li><li>Gives FFI memory a lifecycle profile;</li><li>Leaves evidence for cross-boundary ownership transfers;</li><li>Provides auditable logs for invalid free/double free/leak candidates.</li></ul><p>It doesn’t replace Rust’s safety model, but rather fills the gaps in Rust’s runtime observability.</p><p>This design laid the foundation for my later <a href="https://medium.com/@jinhopers/in-depth-llvm-ir-how-omniscope-tracks-ownership-across-languages-2919e418ca61">OmniScope</a> project. It was also the project I decided to work on after the second refactoring of memscope-rs.</p><p>Next article: Arc/Rc Clone Detection: Why StackOwner Matters</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c73b5caf14f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lockfree Tracking: How memscope-rs Handles Concurrent Memory Events]]></title>
            <link>https://medium.com/@jinhopers/lockfree-tracking-how-memscope-rs-handles-concurrent-memory-events-9c06d19f2c5a?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c06d19f2c5a</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[memory-analysis]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Fri, 22 May 2026 09:06:00 GMT</pubDate>
            <atom:updated>2026-05-22T09:06:00.484Z</atom:updated>
            <content:encoded><![CDATA[<p>The first article discussed single-threaded tracing.</p><p>However, things immediately become more complex once you put memscope-rs into a real service:</p><ul><li>Multiple threads allocate and release resources simultaneously;</li><li>Event streams need concurrent writing;</li><li>Active allocations must be precise;</li><li>Statistical data must be accurate;</li><li>Performance must not be compromised under high concurrency.</li></ul><p>Therefore, the focus of the second article is not on “more visually appealing” analysis, but rather:</p><blockquote>In multi-threaded scenarios, how can memscope-rs use a lock-free/low-lock structure to collect memory events as stably as possible?</blockquote><h3>Why Multithread Tracking Is a Different Problem</h3><p>In a single-threaded environment, the order of events is largely controllable.</p><p>In a multi-threaded environment, the order is no longer reliable:</p><ul><li>Thread A and Thread B may allocate resources concurrently;</li><li>Deallocation may occur earlier than you expect in a snapshot;</li><li>Statistics may be updated concurrently by multiple writers;</li><li>If relying on a large lock, tracing itself can become a bottleneck.</li></ul><p>Therefore, memscope-rs’ concurrency design doesn’t lock everything, but rather breaks it down into <strong>two layers:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4zlfhBcXoOWE9PLMFJ8Wg.png" /><figcaption>mutil-thread</figcaption></figure><p>The goals of this type of design are clear:</p><ul><li>To make writes as fast as possible;</li><li>To make reads as acceptable as possible;</li><li>To avoid turning the “tracing tool” into a “system bottleneck”.</li></ul><h3>The Core Multithread Primitive: ThreadLocalTracker</h3><p>The core structure of multi-threaded tracking is in <strong>ThreadLocalTracker</strong>. Its fields in the source code are straightforward:</p><ul><li>events: Arc&lt;SegQueue&lt;Event&gt;&gt;</li><li>active_allocations: Arc&lt;DashMap&lt;usize, usize&gt;&gt;</li><li>total_allocations / total_allocated / …: AtomicU64</li><li>peak_memory: AtomicU64</li><li>sample_rate</li><li>total_seen / total_tracked</li></ul><p>Source code anchors: src/capture/backends/lockfree_tracker.rs:25 src/capture/backends/lockfree_tracker.rs:29.</p><p>Its design illustrates a key idea:</p><p>The event queue, activity allocation table, and statistics count are not completed by a single structure, but are separated according to their responsibilities.</p><p>The advantages of this approach are:</p><ul><li>SegQueue handles high-concurrency event writing;</li><li>DashMap handles concurrent lookups/deletions;</li><li>Atomic counters handle statistics;</li><li>Peak memory is maintained using CAS to avoid global locks.</li></ul><h3>Recording Events Without Blocking Writers</h3><p>When tracking allocations, the most important thing is to avoid blocking writers. The general path of `ThreadLocalTracker::track_allocation()` is as follows:</p><pre>pub fn track_allocation(&amp;self, ptr: usize, size: usize, call_stack_hash: u64) {<br>      self.total_seen.fetch_add(1, Ordering::Relaxed);<br><br>      if self.sample_rate &lt; 1.0 {<br>          let sample_decision = rand::random::&lt;f64&gt;();<br>          if sample_decision &gt;= self.sample_rate {<br>              return;<br>          }<br>      }<br><br>      self.total_tracked.fetch_add(1, Ordering::Relaxed);<br><br>      let event = Event::allocation(ptr, size, call_stack_hash, self.thread_id);<br>      self.events.push(event);<br><br>      self.active_allocations.insert(ptr, size);<br><br>      self.total_allocations.fetch_add(1, Ordering::Relaxed);<br>      self.total_allocated.fetch_add(size as u64, Ordering::Relaxed);<br>  }</pre><blockquote>Source code anchor: src/capture/backends/lockfree_tracker.rs:64</blockquote><p>Here are a few points worth emphasizing:</p><h4>SegQueue is used to write events.</h4><p>SegQueue is a typical lock-free queue, suitable for multi-threaded producers.</p><p>Its role here is to:</p><ul><li>Record allocation/deallocation events;</li><li>Prevent write events from being blocked by the mutex;</li><li>Allow snapshots/exports to be consumed collectively later.</li></ul><h4>DashMap is used to maintain active allocations.</h4><p><em>active_allocations</em> is not a regular HashMap + Mutex, but a <strong>DashMap</strong>.</p><p>This means:</p><ul><li>Concurrent insert/remove operations are possible in a multi-threaded environment;</li><li>Looking up the allocation size does not require a global lock;</li><li>The determination of double-free/untracked free is more direct.</li></ul><h4>atomic counters only perform statistics</h4><p>The statistics are atomic:</p><ul><li>total_allocations</li><li>total_allocated</li><li>total_deallocations</li><li>total_deallocated</li><li>active_memory</li><li>peak_memory</li></ul><p>This means that the statistics path should not affect the main write process as much as possible.</p><h3>Peak Memory Is Updated With CAS, Not a Big Lock</h3><p>Peak memory is one of the most contention-prone points in concurrency statistics. Memscope-rs doesn’t use a large lock here, but instead uses a<strong> CAS loop</strong>:</p><pre>let new_active = self.active_memory.fetch_add(size as u64, Ordering::Relaxed) + size as u64;<br><br>  let mut current_peak = self.peak_memory.load(Ordering::Relaxed);<br>  let mut backoff_count = 0u32;<br>  const MAX_BACKOFF_ATTEMPTS: u32 = 10;<br><br>  while new_active &gt; current_peak {<br>      match self.peak_memory.compare_exchange_weak(<br>          current_peak,<br>          new_active,<br>          Ordering::Relaxed,<br>          Ordering::Relaxed,<br>      ) {<br>          Ok(_) =&gt; break,<br>          Err(actual) =&gt; {<br>              current_peak = actual;<br>              backoff_count += 1;<br><br>              if backoff_count &lt; MAX_BACKOFF_ATTEMPTS {<br>                  std::hint::spin_loop();<br>              } else if backoff_count &lt; MAX_BACKOFF_ATTEMPTS * 2 {<br>                  std::thread::yield_now();<br>              } else {<br>                  std::thread::sleep(std::time::Duration::from_micros(1));<br>              }<br>          }<br>      }<br>  }</pre><p>This implementation reveals two engineering judgments:</p><p>1. Peak updates are hotspots, but not worth using heavy locks for;</p><p>2. Under extreme contention, the CPU first spins, then yields the scheduler, and finally briefly sleeps to avoid CPU idling.</p><p>This is not a “pure lock-free theoretical version,” but rather a<strong> pragmatic design</strong> with a strong engineering focus.</p><h3><strong>Multithread Deallocation: Detecting Missing or Double Frees</strong></h3><p>The deallocation path is also important. <em>track_deallocation() </em>will remove the corresponding pointer from the DashMap:</p><pre>// src/capture/backends/lockfree_tracker.rs:120<br>pub fn track_deallocation(&amp;self, ptr: usize, call_stack_hash: u64) {<br>      let size = self<br>          .active_allocations<br>          .remove(&amp;ptr)<br>          .map(|(_, v)| v)<br>          .unwrap_or(0);<br><br>      let event = Event::deallocation(ptr, size, call_stack_hash, self.thread_id);<br>      self.events.push(event);<br><br>      self.total_deallocations.fetch_add(1, Ordering::Relaxed);<br>      self.total_deallocated.fetch_add(size as u64, Ordering::Relaxed);<br>  }</pre><p>This means:</p><ul><li>If the pointer can be found: the memory was released normally;</li><li>If the pointer cannot be found: it could be due to double-freeing or untracked allocation.</li></ul><p>It can help locate <strong>abnormal release patterns</strong>, but you cannot conclude that a program definitely has double-free based solely on the result of a single remove operation.</p><h3><strong>The Event Pipeline Still Matters in Multithread Mode</strong></h3><p>In concurrent scenarios, events ultimately enter a unified EventStore.</p><p>The EventStore’s logic is simple:</p><ul><li>egQueue handles push operations;</li><li>RwLock&lt;Vec&lt;MemoryEvent&gt;&gt; handles snapshot caching;</li><li>AtomicUsize records approximate quantities;</li><li>The clearing flag prevents conflicts between clearing and writing.</li></ul><p>This demonstrates that multi-threaded tracing is not a case of “each thread doing its own thing,” but rather that they ultimately converge into a unified event stream, facilitating subsequent analysis and export.</p><h3>Backend Strategy: Core, Lockfree, Async, Unified</h3><p>The multi-threaded capture backend is located in `src/capture/backends/mod.rs`.</p><p>It defines a unified interface:</p><ul><li><em>capture_alloc</em></li><li><em>capture_dealloc</em></li><li><strong><em>capture_realloc</em></strong></li><li><strong><em>capture_move</em></strong></li></ul><p>Source code anchor: `src/capture/backends/mod.rs:127`.</p><p>Then it’s divided into several implementations:</p><ul><li>CoreBackend</li><li>LockfreeBackend</li><li>AsyncBackend</li><li>UnifiedCaptureBackend</li></ul><p>The one that truly has a “<strong>concurrency feel</strong>” is LockfreeBackend:</p><ul><li><em>allocation/deallocation </em>includes <em>call_stack_hash</em></li><li><em>hash_call_stack() </em>uses thread ID + counter for lightweight grouping</li><li>Not a complete backtrace, but sufficient for basic clustering.</li></ul><p>Note:</p><p>UnifiedCaptureBackend’s automatic selection logic is not complex:</p><ul><li>Single-core or unavailable parallelism → Core</li><li>Multi-core → Lockfree</li></ul><p>The source code explicitly states: AsyncBackend detection is not currently implemented.</p><blockquote>Source code anchors: src/capture/backends/mod.rs:390, src/capture/backends/mod.rs:393.</blockquote><p>Therefore, don’t describe Unified as an <strong>intelligent dynamic scheduling system</strong>; it currently functions more like a practical environment selector.</p><h3><strong>What the Benchmarks Really Show</strong></h3><p>In the multi-threaded benchmark, <strong>benches/run.log</strong> provides the actual results.</p><h4>Concurrent tracking</h4><pre> | Threads | Time |<br>  |---|---:|<br>  | 1 | ~19.17 µs |<br>  | 2 | ~40.60 µs |<br>  | 4 | ~55.30 µs |<br>  | 8 | ~134.74 µs |<br>  | 16 | ~372.96 µs |<br>  | 32 | ~961.58 µs |<br>  | 48 | ~1.80 ms |<br>  | 64 | ~1.86 ms |<br>  | 96 | ~3.26 ms |<br>  | 128 | ~4.67 ms |</pre><h4>Shared tracker concurrent</h4><pre>  | Threads | Time |<br>  |---|---:|<br>  | 1 | ~98.30 µs |<br>  | 2 | ~231.96 µs |<br>  | 4 | ~363.82 µs |<br>  | 8 | ~924.19 µs |<br>  | 16 | ~1.84 ms |<br>  | 32 | ~3.57 ms |<br>  | 48 | ~5.26 ms |<br>  | 64 | ~7.06 ms |</pre><h4>Parallel track</h4><pre>  | Threads | Time |<br>  |---|---:|<br>  | 1 | ~94.93 µs |<br>  | 2 | ~103.12 µs |<br>  | 4 | ~129.04 µs |<br>  | 8 | ~176.40 µs |<br>  | 16 | ~307.88 µs |<br>  | 32 | ~496.13 µs |<br>  | 48 | ~692.33 µs |<br>  | 64 | ~917.88 µs |</pre><p>These data illustrate that:</p><ul><li>Multithreaded paths can work, and their scaling is continuous;</li><li>However, it’s not a case of “more threads, more linear speedup”;</li><li>The growth curves of both shared tracker and parallel track demonstrate that concurrency costs are real;</li><li>These costs primarily stem from scheduling, shared state, statistics updates, and event aggregation, rather than a “magic trick” disappearing.</li></ul><p><strong><em>The multi-threaded design goal of memscope-rs is not to allow tracing to expand indefinitely, but to keep data loss and lock contention within an acceptable range while ensuring that concurrency is actually present.</em></strong></p><h3>Sampling Is Not Full Coverage</h3><p>When <strong>sample_rate &lt; 1.0</strong>, track_allocation() does not record every event. It intentionally drops a portion of allocations based on <em>random sampling</em>.</p><p>That means the resulting trace is a sampled view of runtime behavior, not a complete record. This is a valid engineering tradeoff for reducing overhead, but it should never be presented as full-fidelity tracing.</p><h4>call_stack_hash Is a Lightweight Signal</h4><p>The lockfree backend uses a lightweight call_stack_hash for grouping, not a full stack trace. It is useful for coarse clustering and correlation, but it is not equivalent to precise backtrace reconstruction.</p><p>That distinction matters because a hash can help identify patterns, but it cannot replace full symbolic stack capture.</p><h4>Concurrency Still Has Real Runtime Costs</h4><p>The design reduces contention, but it does not eliminate it.</p><p>Even with SegQueue, DashMap, atomics, and CAS, multithreaded tracking still has to deal with:</p><ul><li>scheduling variability</li><li>shared-state contention</li><li>cache-line traffic</li><li>peak-memory update races</li><li>snapshot/export synchronization</li></ul><p>So the concurrency model is <strong>low-lock and contention-aware</strong>, not <strong>zero-cost.</strong></p><h4>Shared Tracker Scenarios Are Stressful by Nature</h4><p>A benchmark where many threads share one tracker is not a theoretical ideal case. It is a stress scenario by design.</p><p>That makes it useful, but it also means the results should be interpreted as:</p><p>how the system behaves under shared-state pressure not as proof of ideal scalability.</p><h3>Summary</h3><p>Single-threaded processing addresses the question of “whether data can be collected correctly,” while multi-threaded processing addresses the question of “whether data collection can continue under real concurrency.”</p><p>Memscope-rs’ multi-threaded module doesn’t attempt to solve everything with a single, overly complex data structure; instead, it adopts a more pragmatic approach:</p><ul><li>SegQueue handles concurrent event streams;</li><li>DashMap manages active allocation;</li><li>Atomic counters record statistics;</li><li>CAS + backoff maintain peak performance;</li><li>Backend abstraction isolates different strategies.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c06d19f2c5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single-Thread Tracking: From GlobalAlloc to Rust-Level Memory Semantics]]></title>
            <link>https://medium.com/@jinhopers/single-thread-tracking-from-globalalloc-to-rust-level-memory-semantics-51c07384464f?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/51c07384464f</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[system]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[memories]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Wed, 20 May 2026 15:06:00 GMT</pubDate>
            <atom:updated>2026-05-20T15:06:00.508Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust provides very strong memory safety guarantees. However, “memory safety” does not equate to “transparent memory behavior.”</p><p>In real-world projects, we still encounter these problems:</p><ul><li>A request path suddenly generates a large number of temporary allocations;</li><li>A cache structure continuously expands during runtime;</li><li>Arc/Rc is over-cloned, but the sharing relationships are difficult to discern;</li><li>A business object appears small but internally holds a large amount of heap data;</li><li>Traditional heap profilers can tell you “how many bytes were allocated,” but they rarely tell you “whose variables these are.”</li></ul><p>Therefore, I created the <a href="https://github.com/Timwood0x10/memscope-rs">memscope-rs</a> project with the aim of making Rust’s memory allocation transparent.</p><p>memscope-rs doesn’t attempt to replace the Rust compiler, nor does it claim to fully understand Rust’s ownership system at runtime. Its goal is more engineering-oriented:</p><blockquote>Capture real runtime memory allocation events and, as far as possible, break these low-level events down into variables, types, and source code locations that Rust developers can understand.</blockquote><p>This article is the first in this series, focusing on the most fundamental and crucial layer:</p><blockquote>Single-threaded memory tracing: From GlobalAlloc to Rust-level memory semantics.</blockquote><h3>Why Single-Thread Tracking Comes First</h3><p>When developing memory analysis tools, multithreading, asynchronous tasks, ownership graphs, and visualization dashboards are all very appealing. However, if the single-threaded data collection model itself is unreliable, all subsequent analyses will be built on sand.</p><p>Therefore, memscope-rs’ first-layer design is very simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*xbsAQUDrCQiGODLNKve28A.png" /><figcaption>Single-thread</figcaption></figure><p>It breaks down the data sources into two parts:</p><p>1. GlobalAlloc captures the actual allocation facts:</p><ul><li>pointer address</li><li>allocation size</li><li>allocation/deallocation event</li></ul><p>2. track! + Trackable supplement Rust semantics:</p><ul><li>variable name</li><li>type name</li><li>source file</li><li>source line</li><li>module path</li><li>semantic memory role</li></ul><h3>The First Layer: GlobalAlloc as Runtime Ground Truth</h3><p>Rust allows us to customize the global allocator.</p><p>Memscope-rs’ underlying tracing starts here: implementing a TrackingAllocator, wrapping the system’s default allocator.</p><p>The core logic can be simplified as follows:</p><pre>unsafe impl GlobalAlloc for TrackingAllocator {<br>      unsafe fn alloc(&amp;self, layout: Layout) -&gt; *mut u8 {<br>          let ptr = System.alloc(layout);<br><br>          if !ptr.is_null() {<br>              let _ = tracker.track_allocation(ptr as usize, layout.size());<br>          }<br><br>          ptr<br>      }<br><br>      unsafe fn dealloc(&amp;self, ptr: *mut u8, layout: Layout) {<br>          let _ = tracker.track_deallocation(ptr as usize);<br>          System.dealloc(ptr, layout);<br>      }<br>  }</pre><p>There’s another important detail in the actual source code: preventing recursive tracing.</p><p>Because tracing itself can also allocate memory, if another allocator hook is triggered within the allocator hook, it could lead to a recursion explosion.</p><p>Therefore, the source code uses the thread-local flag:</p><pre> thread_local! {<br>      static TRACKING_DISABLED: std::cell::Cell&lt;bool&gt; =<br>          const { std::cell::Cell::new(false) };<br>  }</pre><p>Temporarily disable tracing before entering the tracing logic:</p><pre>TRACKING_DISABLED.with(|disabled| disabled.set(true));<br><br>// record allocation / deallocation<br><br>TRACKING_DISABLED.with(|disabled| disabled.set(false));</pre><p>This layer provides the most reliable data:</p><pre><br>  | Data            |  Source   | Reliability |<br>  |-----------------|------------|------------|<br>  | pointer address | GlobalAlloc | high      |<br>  | allocation size | Layout::size() | high   |<br>  | allocation event | alloc()     |    high  |<br>  | deallocation event | dealloc() | high     |</pre><p>However, it also has significant limitations.</p><p>GlobalAlloc can only see:</p><blockquote>“N bytes were allocated at a certain address.”</blockquote><p>It doesn’t know:</p><ul><li>Whether this is a Vec&lt;u8&gt; or a String;</li><li>Which variable does this allocation correspond to;</li><li>Which source file does it come from;</li><li>Whether it belongs to a specific business object;</li><li>Whether it is heap data shared by Arc/RC.</li></ul><p>Therefore, we need to introduce the second layer.</p><h3>The Second Layer: Why Raw Allocation Data Is Not Enough</h3><p>Let’s assume we only rely on the allocator hook. We might get events like this:</p><pre> alloc ptr=0x1048a0000 size=1024<br> alloc ptr=0x1048b4000 size=24<br> dealloc ptr=0x1048a0000</pre><p>This is useful for low-level analysis, but it’s not user-friendly enough for Rust developers.</p><pre>variable: users<br>type: Vec&lt;User&gt;<br>source: src/main.rs:42<br>size: 1024 bytes</pre><p>This is why memscope-rs chose to introduce explicit tracking macros.</p><pre>let users = vec![User::new(&quot;Alice&quot;), User::new(&quot;Bob&quot;)];<br><br>track!(tracker, users);<br><br><br>// marco track impl<br>macro_rules! track {<br>      ($tracker:expr, $var:expr) =&gt; {{<br>          let var_name = stringify!($var);<br>          $tracker.track_as(<br>              &amp;$var,<br>              var_name,<br>              file!(),<br>              line!(),<br>              module_path!(),<br>          );<br>      }};<br>  }</pre><blockquote>What `track!` does isn’t complicated magic, but rather injects the information that Rust compile-time macros can obtain</blockquote><p>In this way, memscope-rs can connect the raw memory facts of the allocator layer with the variable context of the Rust layer.</p><h4>The Core Abstraction: Trackable</h4><p>For a Rust value to be understood by memscope-rs, it needs to implement Trackable. This trait is the <strong>core abstraction of the single-threaded tracing</strong> module. It looks something like this in a simplified form:</p><pre>pub trait Trackable {<br>      fn track_kind(&amp;self) -&gt; TrackKind;<br><br>      fn get_type_name(&amp;self) -&gt; &amp;&#39;static str;<br><br>      fn get_size_estimate(&amp;self) -&gt; usize;<br><br>      fn get_ref_count(&amp;self) -&gt; Option&lt;usize&gt; {<br>          None<br>      }<br><br>      fn get_data_ptr(&amp;self) -&gt; Option&lt;usize&gt;;<br><br>      fn get_data_size(&amp;self) -&gt; Option&lt;usize&gt;;<br>  }<br></pre><p>The most crucial step is to use <strong>fn track_kind(&amp;self) -&gt; TrackKind;</strong></p><p>Because different Rust types behave completely differently in memory.</p><ul><li><em>Vec&lt;T&gt;</em> has a stable heap buffer.</li><li><em>String</em> has contiguous heap bytes.</li><li><em>Box&lt;T&gt; </em>points to a heap object.</li><li>However, the internal bucket structure of <em>HashMap&lt;K, V&gt; </em>should not be simply disguised as a stable pointer.</li><li>A<em>rc&lt;T&gt; / Rc&lt;T&gt;</em> are more special: the smart pointers themselves are on the stack, but they point to shared heap data.</li></ul><p>Therefore, memscope-rs does not crudely treat all types as <strong>a pointer + a size</strong>. It introduces `TrackKind`.</p><h3>TrackKind: Turning Rust Types into Memory Semantics</h3><p><em>trackkind </em>It categorizes Rust values ​​into several classes.</p><pre>  pub enum TrackKind {<br>      HeapOwner {<br>          ptr: usize,<br>          size: usize,<br>      },<br><br>      Container,<br><br>      Value,<br><br>      StackOwner {<br>          ptr: usize,<br>          heap_ptr: usize,<br>          size: usize,<br>      },<br>  }</pre><p>If converted into an image, it would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0F-L-3geuq5_0l5CTiCalQ.png" /><figcaption>trackkind</figcaption></figure><p>This classification addresses a practical problem: <strong>Not all Rust types should be treated as scannable heap owners.</strong></p><h4>HeapOwner</h4><p>HeapOwner indicates that this type actually owns an observable block of heap memory.</p><p>Typical types:</p><ul><li>Vec&lt;T&gt;</li><li>String</li><li>Box&lt;T&gt;</li></ul><p>The implementation of Vec&lt;T&gt; is roughly as follows:</p><pre>impl&lt;T&gt; Trackable for Vec&lt;T&gt; {<br>      fn track_kind(&amp;self) -&gt; TrackKind {<br>          TrackKind::HeapOwner {<br>              ptr: self.as_ptr() as usize,<br>              size: self.capacity() * std::mem::size_of::&lt;T&gt;(),<br>          }<br>      }<br><br>      fn get_type_name(&amp;self) -&gt; &amp;&#39;static str {<br>          &quot;Vec&lt;T&gt;&quot;<br>      }<br><br>      fn get_size_estimate(&amp;self) -&gt; usize {<br>          std::mem::size_of::&lt;T&gt;() * self.capacity()<br>      }<br><br>      fn get_data_ptr(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(self.as_ptr() as usize)<br>      }<br><br>      fn get_data_size(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(std::mem::size_of::&lt;T&gt;() * self.len())<br>      }<br>  }</pre><p>Here’s a detail: <em>size_estimate</em> uses <em>capacity </em>, not <em>len </em>. This is closer to the actual allocation cost.</p><p>Because even if a <em>Vec</em> only stores 10 elements, it may already have reserved capacity for 1024 elements.</p><h4>Container</h4><p>HashMap serves as a good example.</p><p>If we force ourselves to treat a HashMap as a simple heap pointer, it’s easy to be misled.</p><p>The internal structure of a HashMap is complex;<strong> its bucket distribution</strong>, <strong>control bytes</strong>, and <strong>hash state</strong> are not suitable for simply exposing as a stable user-level pointer.</p><p>Therefore, memscope-rs models it as a <strong>Container</strong>:</p><pre> impl&lt;K, V&gt; Trackable for std::collections::HashMap&lt;K, V&gt; {<br>      fn track_kind(&amp;self) -&gt; TrackKind {<br>          TrackKind::Container<br>      }<br><br>      fn get_type_name(&amp;self) -&gt; &amp;&#39;static str {<br>          &quot;HashMap&lt;K, V&gt;&quot;<br>      }<br><br>      fn get_size_estimate(&amp;self) -&gt; usize {<br>          std::mem::size_of::&lt;(K, V)&gt;() * self.capacity()<br>      }<br><br>      fn get_data_ptr(&amp;self) -&gt; Option&lt;usize&gt; {<br>          None<br>      }<br><br>      fn get_data_size(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(std::mem::size_of::&lt;(K, V)&gt;() * self.len())<br>      }<br>  }</pre><p>This means:</p><ul><li>A HashMap will appear in the analysis graph;</li><li>It will have a type name and estimated size;</li><li>But it won’t be disguised as a scannable heap pointer.</li></ul><p>This is a very restrained design.</p><p>Rather than “appearing to support everything,” I prefer memscope-rs to remain<strong> honest </strong>where accuracy cannot be guaranteed.</p><h4>StackOwner</h4><p>Arc&lt;T&gt; and Rc&lt;T&gt; are another special type of object. They are <strong>smart pointers on the stack</strong>, but they point to data on the heap.</p><p>Therefore, memscope-rs uses <strong>StackOwner</strong> to represent this structure.</p><pre>impl&lt;T&gt; Trackable for std::sync::Arc&lt;T&gt; {<br>      fn track_kind(&amp;self) -&gt; TrackKind {<br>          let stack_ptr = self as *const _ as usize;<br>          let heap_ptr = &amp;**self as *const T as usize;<br><br>          TrackKind::StackOwner {<br>              ptr: stack_ptr,<br>              heap_ptr,<br>              size: std::mem::size_of::&lt;T&gt;(),<br>          }<br>      }<br><br>      fn get_type_name(&amp;self) -&gt; &amp;&#39;static str {<br>          &quot;Arc&lt;T&gt;&quot;<br>      }<br><br>      fn get_ref_count(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(std::sync::Arc::strong_count(self))<br>      }<br><br>      fn get_data_ptr(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(&amp;**self as *const T as usize)<br>      }<br><br>      fn get_data_size(&amp;self) -&gt; Option&lt;usize&gt; {<br>          Some(std::mem::size_of::&lt;T&gt;())<br>      }<br>  }</pre><p>This lays the foundation for subsequent Arc/Rc clone detection.</p><p>If multiple StackOwners have different stack_ptr but point to the same <strong>heap-ptr</strong>, we can determine that they share the same heap data.</p><p>This is not achieved by hooking <em>Arc::clone()</em>.</p><p>Instead, it’s grouped based on the structural relationships recorded at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3vvUB7K-7ga7KkaiEqZmQ.png" /><figcaption>ARC/RC</figcaption></figure><p>The advantages of this design are:</p><ul><li>It does not rely on hard-coded ArcInner offset;</li><li>It is not bound to the specific Rust version’s internal implementation;</li><li>A similar approach can be used for both Rc and Arc.</li></ul><p>However, to be honest:</p><p>This is still a <strong>runtime-based </strong>detection, not a <strong>compiler-level </strong>proof of ownership.</p><h3>How Events Are Recorded in Single-Thread Tracking</h3><p>When a user calls: <em>track!(tracker, data);</em></p><p>it internally calls <em>Tracker::track_as()</em>, which then calls <strong>track_inner()</strong>. <em>track_inner()</em> follows different paths depending on the <em>TrackKind</em>.</p><h4>HeapOwner Path</h4><pre>TrackKind::HeapOwner { ptr, size } =&gt; {<br>      self.inner.track_allocation(ptr, size);<br><br>      let mut event = MemoryEvent::allocate(ptr, size, thread_id);<br>      event.var_name = Some(name.to_string());<br>      event.type_name = Some(type_name);<br>      event.source_file = Some(file.to_string());<br>      event.source_line = Some(line);<br>      event.module_path = Some(module_path.to_string());<br><br>      self.event_store.record(event);<br>  }</pre><p>This process performs two tasks simultaneously:</p><p>1. Recording the allocation to the underlying tracker;</p><p>2. Writing a MemoryEvent with variable context to the EventStore.</p><h4>StackOwner Path</h4><p>For StackOwner types like Arc/Rc:</p><pre>TrackKind::StackOwner {<br>      ptr: stack_ptr,<br>      heap_ptr,<br>      size,<br>  } =&gt; {<br>      self.inner.track_allocation(stack_ptr, size);<br><br>      let mut event = MemoryEvent::allocate(heap_ptr, size, thread_id);<br>      event.var_name = Some(name.to_string());<br>      event.type_name = Some(type_name);<br>      event.stack_ptr = Some(stack_ptr);<br><br>      self.event_store.record(event);<br>  }</pre><p>Note that two addresses are stored here:</p><ul><li>stack_ptr</li><li>heap_ptr</li></ul><p>This is crucial for identifying the sharing relationship later.</p><h4>Container / Value Path</h4><p>For Container and Value:</p><pre>TrackKind::Container | TrackKind::Value =&gt; {<br>      let mut event = MemoryEvent::metadata(<br>          name.to_string(),<br>          type_name,<br>          thread_id,<br>          var.get_size_estimate(),<br>      );<br><br>      event.source_file = Some(file.to_string());<br>      event.source_line = Some(line);<br>      event.module_path = Some(module_path.to_string());<br><br>      self.event_store.record(event);<br>  }</pre><p>These types of objects are not recorded as actual heap allocations. They only generate metadata events. This avoids writing unstable or non-existent pointers to the analysis system.</p><h3>EventStore: A Simple but Important Component</h3><p>All events eventually end up in the EventStore.</p><p>It uses crossbeam::queue::SegQueue as the write queue:</p><pre>pub struct EventStore {<br>      queue: SegQueue&lt;MemoryEvent&gt;,<br>      cache: RwLock&lt;Vec&lt;MemoryEvent&gt;&gt;,<br>      count: AtomicUsize,<br>      clearing: AtomicUsize,<br>  }<br><br><br>pub fn record(&amp;self, event: MemoryEvent) {<br>      if self.clearing.load(Ordering::Acquire) != 0 {<br>          return;<br>      }<br><br>      self.queue.push(event);<br>      self.count.fetch_add(1, Ordering::Release);<br>  }<br><br>// Flush to cache during snapshot:<br>fn flush_to_cache(&amp;self) {<br>      let mut cache = self.cache.write();<br><br>      while let Some(event) = self.queue.pop() {<br>          cache.push(event);<br>      }<br>  }</pre><p>This design is lightweight enough for single-threaded mode.</p><p>It also leaves room for subsequent <strong>lock-free</strong> data acquisition in multi-threaded mode.</p><h3>Built-in Rust Types Are Only Half the Story</h3><p>Standard library types are just the beginning.</p><p>In real-world business code, we focus more on <strong>user-defined types:</strong></p><pre> struct UserProfile {<br>      id: u64,<br>      name: String,<br>      tags: Vec&lt;String&gt;,<br>  }</pre><p>Requiring users to manually write Trackables would be extremely tedious.</p><p>Therefore, memscope-rs provides a <strong>derive macro</strong>:</p><pre>use memscope_rs::{track, tracker, Trackable};<br>  use memscope_derive::Trackable;<br><br>  #[derive(Trackable)]<br>  struct UserProfile {<br>      id: u64,<br>      name: String,<br>      tags: Vec&lt;String&gt;,<br>  }<br><br>  fn main() {<br>      let tracker = tracker!();<br><br>      let profile = UserProfile {<br>          id: 1,<br>          name: &quot;Alice&quot;.to_string(),<br>          tags: vec![<br>              &quot;rust&quot;.to_string(),<br>              &quot;memory&quot;.to_string(),<br>          ],<br>      };<br><br>      track!(tracker, profile);<br>  }</pre><p>The `derive` macro generates a `Trackable` implementation for user types.</p><p>It attempts to:</p><ul><li>Iterate through the struct fields;</li><li>Call `Trackable::get_size_estimate()` on the fields;</li><li>Recursively accumulate the estimated size of the fields;</li><li>Attempt to obtain the field’s heap pointer;</li><li>Calculate the enum based on the current variant;</li><li>Reject deriving from unions because the safety semantics are too complex.</li></ul><p>The design goal here is not to achieve “<strong>perfect memory layout restoration</strong>,”</p><p>but rather to provide a sufficiently practical Rust-level semantic layer.</p><blockquote><strong>Allowing user-defined types to be included in a unified memory analysis model</strong></blockquote><h3>What the Benchmark Actually Says</h3><p>When discussing performance, I don’t want to just write “low overhead.”Let’s look directly at the benchmark log in the project. In the current `benches/run.log`, univariate tracking looks something like this:</p><pre> | Benchmark         |      Time |<br>  |---------------------|---------:|<br>  | track_single/vec/64 | ~653 ns |<br>  | track_single/vec/1024 | ~666 ns |<br>  | track_single/vec/1048576 | ~4.93 µs |<br><br>  Batch tracking:<br><br>  | Benchmark                     |       Time |<br>  |-------------------------------|-----------:|<br>  | track_multiple/variables/1000 | ~669.67 µs |<br>  | track_multiple/variables/10000 | ~6.59 ms |<br><br>  Backend event construction：<br><br>  | Backend | alloc event time |<br>  |------|---------|<br>  | Core | ~23 ns |<br>  | Async | ~23 ns |<br>  | Lockfree | ~39 ns |<br>  | Unified | ~39 ns |</pre><p>These data illustrate:</p><ul><li>Single-item variable tracking is in the sub-microsecond range;</li><li>Backend event construction is in the tens of nanosecond range;</li><li>Batch tracking shows a roughly linear increase;</li><li>The cost of large object tracking mainly comes from the actual object itself and size/model calculations.</li></ul><p>However, we must also be honest:</p><p>Many projects in the benchmark log indicate: <strong>Performance has regressed.</strong></p><p>For example, both single-item Vec tracking and batch variable tracking have shown a regression compared to historical levels.</p><p>Therefore, a more accurate statement is not:</p><blockquote>memscope-rs is always extremely fast.</blockquote><blockquote>However:</blockquote><blockquote>The absolute latency of current single-threaded tracing is still within usable limits, but performance is still evolving. Some benchmarks show a regression compared to previous versions, requiring continuous optimization.</blockquote><blockquote>This is also where I want this project to remain transparent.</blockquote><h3>What This Module Can and Cannot Know</h3><p>At this point, we can clearly define the data reliability of the memscope-rs single-threaded module.</p><h4>High Confidence</h4><p>These come from real runtime events:</p><ul><li>allocation pointer</li><li>allocation size</li><li>allocation/deallocation event</li><li>timestamp</li><li>thread id</li></ul><h4>Medium Confidence</h4><p>These come from explicit tracing and trait modeling:</p><ul><li>variable name</li><li>type name</li><li>source file</li><li>source line</li><li>estimated size</li><li>TrackKind</li><li>Arc/Rc stack pointer and heap pointer</li></ul><h4>Inferred / Semantic Layer</h4><p>These are not the original facts of the allocator, but rather the results of subsequent analysis.</p><ul><li>ownership relation</li><li>shared relation</li><li>container relation</li><li>possible clone relationship</li><li>higher-level memory graph</li></ul><p>This distinction is crucial. Memscope-rs doesn’t aim to pretend all data is absolute truth. It’s more like a<strong> hierarchical system</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h87r4W5h4QqcYYBhyoQ31Q.png" /><figcaption>layer</figcaption></figure><p>The further down you go, the closer you get to the <strong>real runtime</strong>. The further up you go, the closer you get to the Rust program structure as <strong>understood by humans</strong>.</p><h3>Why This Matters</h3><p>Many memory management tools remain at the heap layer:</p><p><strong>N bytes were allocated here</strong>. But what Rust developers really want to know is:</p><ul><li>From which variable did this allocation come?</li><li>What Rust type is it?</li><li>Is it just a container?</li><li>Was it shared by some Arc clone?</li><li>Can it appear in a source-level report?</li></ul><p>The memscope-rs single-threaded module attempts to bridge this gap:</p><pre>raw allocation<br>      -&gt; memory event<br>      -&gt; Rust variable metadata<br>      -&gt; TrackKind semantic role<br>      -&gt; analysis-ready event stream</pre><p>This forms the foundation for all subsequent capabilities.</p><p>Multi-threaded tracing, async task attribution, Arc/RC clone detection, ownership graph, and dashboard visualization all ultimately rely on this fundamental event model.</p><h3>Summary</h3><p>This article only covers the first layer of memscope-rs: single-threaded tracing.</p><p>Its core isn’t complex algorithms, but rather a few simple yet crucial engineering choices:</p><ul><li>Capturing the true allocation facts using GlobalAlloc;</li><li>Supplementing variable and source code context with the track! macro;</li><li>Describing the memory semantics of Rust types using the Trackable trait;</li><li>Avoiding crudely modeling all types as pointers using TrackKind;</li><li>Storing a unified event stream using EventStore;</li><li>Providing derive macros for user-defined types to reduce integration costs;</li><li>Maintaining transparency in benchmark results, including performance rollbacks.</li></ul><p>This is what I hope memscope-rs will bring to the Rust ecosystem.</p><p>No exaggeration, no speculation, no pretending to understand everything. Make bold assumptions, practice cautiously, and verify meticulously. That’s my style. I’m <a href="https://github.com/Timwood0x10">TimWood</a>.</p><p>In the next article, I will continue to dissect the multi-threaded tracing module.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51c07384464f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In-depth LLVM IR: How OmniScope tracks Ownership across languages]]></title>
            <link>https://medium.com/@jinhopers/in-depth-llvm-ir-how-omniscope-tracks-ownership-across-languages-2919e418ca61?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/2919e418ca61</guid>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[llvm]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[memory-safety]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Tue, 19 May 2026 08:52:09 GMT</pubDate>
            <atom:updated>2026-05-19T08:52:09.900Z</atom:updated>
            <content:encoded><![CDATA[<p>From CrossLangEdge to <strong>Memory Graph</strong>: A Design Breakdown of a Cross-Language Memory Safety Analyzer.</p><blockquote>Memory safety tools typically follow two paths: one understands language semantics at the source code level, and the other observes final behavior at the binary level. OmniScope has chosen a middle path: LLVM IR.</blockquote><blockquote>This choice is subtle. LLVM IR is low enough to unify the call, pointer, load/store, and allocator behaviors of languages ​​such as C, C++, Rust, Zig, and Go; at the same time, it is not so low as to completely lose structural information. For FFI memory safety, this is precisely the golden position.</blockquote><blockquote>This article will delve into OmniScope’s source code, focusing on how it tracks the transfer, escape, and release of ownership across language boundaries using CrossLangEdge, DangerSurface, MemoryGraph, and PointerOwnershipPass.</blockquote><h4>Why is FFI a blind spot in ownership?</h4><p>Rust, Go, Zig, and C/C++ each have their own memory models:</p><ul><li>Rust has ownership/borrow checkers</li><li>Go has GC and cgo boundary constraints</li><li>Zig uses an explicit allocator, emphasizing controllability</li><li>C/C++ uses dependency conventions and RAII</li><li>LLVM IR only shows a unified pointer, call, load/store, and alloc/free pattern</li></ul><p>The problem is:</p><pre> let ptr = Box::into_raw(Box::new(value));<br> extern_c_consume(ptr);</pre><p>From Rust’s perspective, `Box` has been converted to a raw pointer; from C’s perspective, it’s just a `void*` or struct pointer. Who owns it? Who frees it? Can it be freed twice? Will `borrow` escape? These questions, beyond the scope of FFI, are difficult for a single-language compiler to answer fully.</p><p>OmniScope’s approach is that all these languages ​​can ultimately be integrated into LLVM IR. By constructing a unified memory graph at the IR layer, ownership lifecycles can be tracked across languages.</p><h4>Overall architecture diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGs5i7OvsA9ruHm0bEQ11Q.png" /><figcaption>architecture diagram</figcaption></figure><p>Pipeline Execution Architecture Diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnxfZy3V74CH6LkGDzNmHQ.png" /><figcaption>pipeline execution architecture diagram</figcaption></figure><h4>MemoryGraph: OmniScope’s Ownership Memory Graph</h4><p><a href="https://github.com/Timwood0x10/OmniScope/blob/master/src/semantics/memory_graph.zig">src/semantics/memory_graph.zig</a> is the core of ownership tracking.</p><p>Its goal is not simply to count the number of <strong>malloc</strong> and <strong>free</strong> operations, but to answer the more difficult question:</p><p><em>Do these two LLVM values ​​point to the same allocation?</em></p><p>This is especially important for double-free, use-after-free, and cross-language releases.</p><p>for example:</p><pre> <br>  void* p = malloc(64);<br>  void* q = p;<br>  free(q);<br>  free(p);</pre><p>If the parser only looks at the variable names, it might consider <strong>p</strong> and <strong>q</strong> to be two different pointers. However, MemoryGraph maintains alias relationships:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvEYBNYz2O5-dS9E5ftmxA.png" /></figure><p>The information stored by AllocNode includes:</p><ul><li>Allocation instruction</li><li>Aliases</li><li>Whether it has been freed</li><li>Freed_by instruction</li><li>Allocation source kind</li><li>Zone</li><li>Allocation language</li><li>Free language</li></ul><p>This allows OmniScope to determine:</p><ul><li>Whether it is double-free</li><li>Whether it is cross-language alloc/free</li><li>Whether it is unsafe zone allocation</li><li>Whether it is an FFI argument/return value</li><li>Whether it is indirectly used through aliases after memory has been freed</li></ul><h4>Danger Path: Key Design Principles for Avoiding Noise Across the Project</h4><p>A key design principle of OmniScope is that not all pointers warrant an issue.</p><p>In many projects, runtime, standard library, compiler-generated code, and language-internal allocator shims generate a large number of IR pointer operations. Performing equally intensive analysis on all pointers would result in numerous false positives.</p><p>Therefore, OmniScope introduces a danger path gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3lkLmdFygaj-5uRAOzmmw.png" /><figcaption>Danger Path</figcaption></figure><p>The corresponding code in the source code is:</p><ul><li>src/pass/pass.zig:866: isOnDangerPathFull</li><li>src/semantics/memory_graph.zig:892: MemoryGraph.isOnDangerPath</li><li>src/pass/analysis/danger_surface.zig:30: DangerSurfacePass</li></ul><p>In other words, OmniScope is not a “<strong>the more the better</strong>” alarm, but rather focuses the analysis intensity on the boundary areas that are most difficult for the compiler and language runtime to guarantee.</p><h4>CrossLangEdge: The basic unit for cross-language calls</h4><p>CrossLangEdge records cross-language call edges</p><pre>  pub const CrossLangEdge = struct {<br>      caller_name: []const u8,<br>      callee_name: []const u8,<br>      caller_lang: FFIBoundary.Language,<br>      callee_lang: FFIBoundary.Language,<br>      is_ffi_boundary: bool,<br>      ptr_args: []const u32,<br>  };<br></pre><p>This is equivalent to OmniScope’s “cross-language neural connections.” Subsequent passes will consume it:</p><ul><li>ffi-boundary: Determines if it’s an FFI risk point</li><li>ptr-lifetime: Tracks pointer lifetimes</li><li>danger-surface: Marks relevant pointers</li><li>callback-escape: Detects callback or borrow escape</li><li>memory-safety and free-validation: Determine whether to report a security issue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tzx1Q4EsYq7-grpYHw4mNw.png" /><figcaption>CrossLangEdge Data Flow Graph</figcaption></figure><h4>CallSiteIndex: Why it’s Important for Large Projects?</h4><p>Between src/pipeline/pipeline.zig:143 and src/pipeline/pipeline.zig:160, the pipeline scans all functions, basic blocks, and instructions before executing a pass, and writes the found call instruction to the CallSiteIndex.</p><p>The structure of the CallSiteIndex is in src/pass/pass.zig:60:</p><pre>  pub const CallSiteIndex = struct {<br>      map: std.StringHashMap(std.ArrayList(CallSite)),<br>      allocator: Allocator,<br>  };</pre><p>It does something very straightforward: Callee name -&gt; All call sites that invoke it.</p><blockquote>In static analysis, correctness is only the first step. When truly implemented in large-scale C/C++/Rust projects, performance determines whether a tool can enter CI. The significance of CallSiteIndex is to transform “repeatedly scanning IR for each pass” into “one preprocessing, multiple O(1) queries”.</blockquote><h4>Language detection and Channel Gating</h4><p>OmniScope performs module-level language detection only once at the start of the pipeline.</p><p>source code:</p><ul><li>src/pass/pass.zig:653: initModuleLanguage</li><li>src/semantics/language_detector.zig:1: Unified language detector</li><li>src/pass/pass.zig:731: Enable different analysis channels for different languages</li></ul><pre>+---------+--------------+--------------+-----------------+-------------------+<br>| lang    | ffi-boundary | ptr-lifetime | callback-escape | pointer-ownership |<br>+---------+--------------+--------------+-----------------+-------------------+<br>|  Rust   |     full     |     full     |   unsafe-only   |       full        |<br>|  Zig    |   limited    |     skip     |      skip       |       skip        |<br>|  Go     |   limited    |   limited    |    full cgo     |      limited      |<br>|  C/C++  |     full     |     full     |   real-escape   |       full        |<br>| unknown |   generic    |   generic    |     generic     |      generic      |<br>+---------+--------------+--------------+-----------------+-------------------+</pre><p>This demonstrates that OmniScope does not apply a “one-size-fits-all” approach to different languages. For example, Zig’s explicit allocator and defer modes are completely different from Rust’s ownership rules. Applying Rust’s rules to Zig can easily lead to false positives. Therefore, OmniScope uses a language-first strategy to determine pass strength.</p><h4>Zone Classification: Trust Language, Focus on Boundaries</h4><p>OmniScope divides function or code regions into different zones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9q57cfhOYZc-5noryp-SUQ.png" /><figcaption>Zone</figcaption></figure><p>OmniScope’s goal is not to treat all IRs as dangerous code, but to identify which IRs truly deviate from the language safety model.</p><h4>PointerOwnershipPass’s Three-Source Integration Design</h4><p>src/pass/analysis/pointer_ownership.zig:166 is the entry point for the ownership pass.</p><p>This pass has a very practical design: it doesn’t just trust one data source, but integrates three types of sources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfGQ5Jj2Zkt8_VCbTTIf-A.png" /></figure><p>The three sources address different issues:</p><ol><li>MemoryGraph.nodes<br>Originating from the ptr lifetime pass, it stores allocation, alias, and freed states, providing the strongest semantic information.</li><li>GlobalAllocTracker.records<br>Used for cross-function allocation/free pairing, reducing false alarms caused by “allocation in function A, release in function B”.</li><li>IR-level free scan fallback<br>As a backup solution, it prevents the former two from missing certain free commands.</li></ol><p>So, static analysis is not just about writing rules; it’s about handling real-world issues such as incomplete IR (In-Reference Architecture), missing debugging information, post-optimization structural changes, external function declarations, and cross-function releases.</p><h4>Rust FFI Ownership case</h4><pre>  #[no_mangle]<br>  pub extern &quot;C&quot; fn make_obj() -&gt; *mut Obj {<br>      Box::into_raw(Box::new(Obj::new()))<br>  }<br><br>  void consume(void* p) {<br>      free(p);<br>  }</pre><p>If the Rust side later takes over and drops the function again via <em>Box::from_raw</em>, double-freeing may occur. At the LLVM IR layer, OmniScope will take note.</p><pre>sequenceDiagram<br>      participant R as Rust IR<br>      participant C as C IR<br>      participant CG as CallGraphPass<br>      participant MG as MemoryGraph<br>      participant PO as PointerOwnershipPass<br>      participant MS as MemorySafetyPass<br><br>      R-&gt;&gt;MG: Box::into_raw / allocation source<br>      R-&gt;&gt;CG: call extern C function<br>      CG-&gt;&gt;MG: CrossLangEdge with pointer arg<br>      C-&gt;&gt;MG: free(ptr)<br>      MG-&gt;&gt;MG: mark freed, record free_lang = C<br>      R-&gt;&gt;MG: Box::from_raw / drop path<br>      PO-&gt;&gt;MG: query alias and ownership state<br>      MS-&gt;&gt;MS: detect cross-language lifecycle / double-free</pre><p>The core point isn’t that OmniScope “understands Rust source code syntax,” but rather that it allows you to see the following in LLVM IR:</p><ul><li>Pointers returned or passed to C ABIs from Rust functions</li><li>Pointers freed by C</li><li>Whether pointers are subsequently dropped/deallocated by Rust</li><li>Whether the allocation language and the free language are different</li><li>Whether aliases point to the same allocation</li></ul><h4>IR Layer Perspective: Why it’s More Stable Than Source Code Rules</h4><p>Common issues with source code-level rules:</p><ul><li>Semantics are not clear after Rust macro expansion</li><li>C/C++ typedefs, macros, and templates can change the surface appearance</li><li>Zig comptime generates a large amount of code</li><li>Go cgo goes through a bridging layer</li><li>Cross-language calls are not necessarily visible in a single source code repository</li></ul><p>Advantages of LLVM IR:</p><ul><li>Call relationships are closer to the actual compiled output</li><li>Pointer operations are unified as load/store/call/gep/bitcast</li><li>Allocators/free ultimately lead to identifiable function calls or intrinsics</li><li>Multiple languages ​​can enter the same IR analysis pipeline</li><li>Source code location can be traced using debug info</li></ul><p>Of course, the IR layer also has challenges:</p><ul><li>Optimizations can change control flow and variable appearance</li><li>Debug info may be missing</li><li>Function names may be mangled</li><li>High-level semantics need to be recovered using registry and patterns</li><li>Noise can be introduced from different language runtimes</li></ul><p>OmniScope is designed around these challenges: language detector, zone classifier, semantic registry, danger Surface, memory graph, and global alloc tracker all compensate for the “low-level but unified” characteristics of the IR layer.</p><h4>Summary</h4><p>The challenge of FFI (Functional Fidelity Integrity) lies not merely in “calling external functions,” but in the escape of ownership from one language’s type system into another’s convention system.</p><p>The core value of OmniScope is to reconstruct a cross-language ownership graph on the common underlying layer of LLVM IR: who allocates, who borrows, who transfers, who releases, and who mistakenly reuses.</p><p>For modern system software, language boundaries are increasingly complex: Rust calls C, Go calls C, Zig embeds C, and C++ exposes opaque handles. Single-language security models cannot cover these boundaries, and this is precisely where LLVM IR static analysis can play a crucial role.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2919e418ca61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OmniScope Design Concept]]></title>
            <link>https://medium.com/@jinhopers/omniscope-design-concept-3f163dcb42f4?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f163dcb42f4</guid>
            <category><![CDATA[architecture-design]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Tue, 19 May 2026 04:02:39 GMT</pubDate>
            <atom:updated>2026-05-19T05:48:23.066Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, previously, I only gave a brief overview of this project. Now, I’ll break down the architecture and share my design insights.</p><p>This project aims to solve memory leak issues in cross-language calls. Unlike general-purpose security detection tools, my design focuses 90% of my effort on analyzing <strong>unsafe/ffi</strong> code, and only 10% (and perhaps even less) on general security detection.</p><h4>Why zig?</h4><p>Initially, I didn’t know what to do, choosing between Rust and C++. However, Rust’s compilation speed was too slow, and although it has an excellent memory management model, analyzing unsafe code might require a lot of unsafe code, which deterred me. As for C++, I’m sorry, I’m not very good at it. So I switched to Zig, and this was my first attempt at creating a small tool using Zig.</p><h4>Why IR？</h4><p>I’ve been thinking that many FIF implementations aren’t limited to Rust ←-&gt; C, but also include C ←&gt; C++, and Go ← → C. If I were to adapt for each language, it would be a catastrophic workload. So, I realized that the commonality among these languages ​​is that they all use LLVM as their compiler backend. Therefore, I started researching (yes, I’m not a very competent developer; I don’t even understand compilers very well). I dissected the compiler and realized that the Instructions Repository (IR) contains a large amount of information about the program; this might be my breakthrough point.</p><p>Then I started designing the architecture. Besides researching on my own, I consulted senior development engineers and various AIs (GPT, CC). I started by creating a simple demo, for example, zig ←-&gt; C. So I looked at the zig source code to find out how zig and C interact… and did all sorts of other work, also taking various compiler notes (but that’s another story). Then the first version of the code was runnable. I also designed various bugs in the project, namely red team vs. blue team battles, to test the TP and FP of this demo. The first run results were pretty good, at least not too bad, which was a good start for me.</p><h4>How to abstract?</h4><p>After successfully running the Zig←-&gt;C demo, my confidence soared, and I switched to Rust←-&gt;C. Little did I know this would be the beginning of a nightmare. The Rust compiler generated a massive amount of intermediate results, storing them all in the Instructions Redirect (IR). The project’s TP remained consistently low, below 20%, and I even considered giving up at one point.</p><p>For a long time afterward, I didn’t want to touch this project until I thought of something: since so many intermediate products are generated, why don’t I just ignore them, assume they are trustworthy, and only analyze the content in the user-defined program?</p><p>Then, I excitedly opened the Rust source code and, with the help of AI, read the Rust compiler source code. The goal was to find what the compiler produced, and use that as a safe zone (this is how Java, Python, etc., were designed later).</p><h4>Why Memory diagram?</h4><p>With this idea in mind, I started working on the project. Zone filtering was successful, but the TP (True Positive Rate) was still low. After analysis, I realized the issue was with the program’s context awareness. I consulted the AI, which suggested adding a whitelist, a suggestion I initially agreed to. However, after implementing it, I discovered that maintaining a very large whitelist was necessary, which wasn’t what I wanted. So I went back to my previous notes…</p><p>Since there’s a deficiency in context awareness, I might as well build a memory graph and a call graph during IR scanning, recording the complete call stack, and then analyze the graph. I’ll only focus on the FHI part; I don’t care about the other parts.</p><p>I got right to it, and the results were surprisingly good. My confidence soared, and I started challenging existing open-source projects, relentlessly adding various red team and blue team tests.</p><p>From the initial sqlite3 to various Rust-based cryptographic libraries and game libraries, all the actual analysis data is documented in the project <a href="https://github.com/Timwood0x10/OmniScope/tree/master/docs">documentation.</a></p><p>When memory-safe languages meet legacy C code, the safety net usually tears at the FFI boundary. OmniScope is built to continuous-stitch this gap.</p><p>This is the entire development process of the project. I hope this tool can be helpful to you. It may not be perfect, but your feedback is appreciated. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f163dcb42f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OmniScope: Detecting Real Rust/C FFI Ownership Bugs at LLVM IR Level]]></title>
            <link>https://medium.com/@jinhopers/omniscope-a-zig-powered-llvm-ir-analyzer-that-finds-real-cross-language-ffi-bugs-d1bb27712b51?source=rss-59d77e44f709------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1bb27712b51</guid>
            <category><![CDATA[cross-lang]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[memory-safety]]></category>
            <dc:creator><![CDATA[TimWood]]></dc:creator>
            <pubDate>Mon, 18 May 2026 01:28:09 GMT</pubDate>
            <atom:updated>2026-05-20T00:56:01.300Z</atom:updated>
            <content:encoded><![CDATA[<p>— -</p><p>Hi, I’m Timwood (Timwood0x10 on GitHub).</p><p>I spend most of my time building systems tools in Rust, Zig, and LLVM. One problem that kept biting me (and many others) is <strong>FFI memory safety</strong> — Rust’s borrow checker stops at `extern “C”`, C doesn’t understand Rust ownership, and Go’s runtime can’t see into native code.</p><p>So I built <strong>OmniScope</strong>: a static analyzer that works directly on <strong>LLVM IR</strong> to see across language boundaries.</p><p>ling : <a href="https://github.com/Timwood0x10/OmniScope">OmniScope</a></p><h4>The Core Innovation: Smart Zone Classification</h4><p>OmniScope intelligently skips safe code and focuses on the dangerous parts:</p><p><strong>Safe Zone</strong> → Compiler-guaranteed code (skip)<br><strong>Runtime Internal</strong> → Standard libraries (skip)<br><strong>Unknown / FFI Zone </strong>→ Deep analysis</p><p>This typically skips ~64%+ of the codebase while concentrating analysis power where bugs actually hide.</p><h4>Real-World Validation: Wasmtime Case Study</h4><p>I tested OmniScope on <strong>Wasmtime</strong>(the high-performance WebAssembly runtime written in Rust). Here’s what it found:</p><p><strong>619 functions </strong>analyzed<br><strong>130 FFI boundaries</strong> detected<br><strong>44 issues</strong> reported (with significantly improved precision after recent refinements)</p><p>Two notable patterns it flagged (later verified in source code):</p><p>1. <strong>fiber_start</strong> ignoring the return value of <strong>VMFuncRef::array_call</strong> (with a TODO comment in the code)<br>2. <strong>occupy_next_slots</strong> missing capacity checks (comment claims a check exists, but implementation directly increments length)</p><p>These patterns relate to known issues, including <strong>GHSA-4pww-gw9q-vvvh</strong> (High-severity sandbox escape). You can read the full investigation reports here:</p><p><a href="https://github.com/Timwood0x10/OmniScope/blob/master/docs/investigation_reports/en/wasmtime.md">Wasmtime Investigation Report</a><br><a href="https://github.com/Timwood0x10/OmniScope/blob/master/docs/investigation_reports/en/wasmtime_source.md">Wasmtime Source Code Verification</a></p><h4>Project Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1_CJqA8r7JIO8Qz_jrfrQ.png" /></figure><p>Key Capabilities</p><p>Detects 20+ issue types: Use-after-free, double-free, borrow escape across FFI, tainted data to dangerous sinks, etc.<br>SARIF output → native GitHub Code Scanning integration<br>Extremely fast: ~150ms per 1,000 functions in ReleaseFast mode<br>Supports Rust, C/C++, Zig, Go at LLVM IR level</p><p>Try It Yourself</p><pre>git clone https://github.com/Timwood0x10/OmniScope.git<br>cd OmniScope<br>make build<br><br># Quick test<br>./zig-out/bin/OmniScope your_project.ll - sarif &gt; results.sarif</pre><p>Full quick start and corpus examples are in the repo.</p><p>I Need Your Feedback</p><p>This is still early (v0.1.8), but the foundation is solid and precision has improved dramatically.</p><p>If you work with:</p><ul><li>Rust FFI-heavy libraries</li><li>Polyglot systems (Rust + C, Zig interop, etc.)</li><li>WebAssembly / Wasmtime</li><li>Security research or systems programming</li></ul><p>…I’d love for you to try OmniScope and tell me what breaks or what’s missing.</p><p>Stars, issues, PRs, and real usage feedback are all extremely welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1bb27712b51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>