title: Generating .gcda coverage files via QEMU/GDB
body: <p><strong>Executive summary:</strong> I want to use GDB to extract the coverage execution counts stored in memory in my embedded target, and use them to create <code>.gcda</code> files (for feeding to <em>gcov/lcov</em>).</p>
  
  <p><strong>The setup</strong>:</p>
  
  <ul>
  <li>I can successfully cross-compile my binary, targeting my specific embedded target - and then execute it under QEMU. </li>
  <li>I can also use QEMU's GDB support to debug the binary (i.e. use <code>tar extended-remote localhost:...</code> to attach to the running QEMU GDB server, and fully control the execution of my binary).</li>
  </ul>
  
  <p><strong>Coverage:</strong>
  Now, to perform "on-target" coverage analysis, I cross-compile with 
  <code>-fprofile-arcs -ftest-coverage</code>. GCC then emits 64-bit counters to keep track of execution counts of specific code blocks. </p>
  
  <p>Under normal (i.e. host-based, not cross-compiled) execution, when the app finishes <code>__gcov_exit</code> is called - and gathers all these execution counts into <code>.gcda</code>files (that gcov then uses to report coverage details). </p>
  
  <p>In my embedded target however, there's no filesystem to speak of - and libgcov basically contains empty stubs for all <code>__gcov_...</code> functions. </p>
  
  <p><strong>Workaround via QEMU/GDB:</strong> To address this, and do it in a GCC-version-agnostic way, I could list the coverage-related symbols in my binary via <code>MYPLATFORM-readelf</code>, and <code>grep</code>-out the relevant ones (e.g. <code>__gcov0.Task1_EntryPoint</code>, <code>__gcov0.worker</code>, etc):</p>
  
  <pre><code>$ MYPLATFORM-readelf -s binary | grep __gcov
  ...
  46: 40021498  48 OBJECT  LOCAL  DEFAULT 4 __gcov0.Task1_EntryPoint
  ...
  </code></pre>
  
  <p>I could then use the offsets/sizes reported to automatically create a GDB script - a script that extracts the counters' data via simple memory dumps (from <em>offset</em>, dump <em>length</em> bytes to a local file). </p>
  
  <p>What I don't know (and failed to find any relevant info/tool), is how to convert the resulting pairs of <em>(memory offset,memory data)</em> into <code>.gcda</code> files. If such a tool/script exists, I'd have a portable (platform-agnostic) way to do coverage on any QEMU-supported platform.</p>
  
  <p>Is there such a tool/script?</p>
  
  <p>Any suggestions/pointers would be most appreciated.</p>
  
  <p><strong>UPDATE</strong>: I solved this myself, as you can read below - and wrote a <a href="https://www.thanassis.space/coverage.html" rel="nofollow">blog post about it</a>.</p>