title: Understanding ARM Cortex-M0+ relocation
body: <p>I'm just getting started with embedded arm development, and there's a snippet of code that's really bugging me:</p>
  
  <pre class="lang-c prettyprint-override"><code>/* Initialize the relocate segment */
  pSrc = &amp;_etext;
  pDest = &amp;_srelocate;
  
  if (pSrc != pDest) 
  {
      while (pDest &lt; &amp;_erelocate) 
      {
          *pDest++ = *pSrc++;
      }
  }
  </code></pre>
  
  <p>Where <code>_etext</code> and <code>_srelocate</code> are symbols defined in the linker script:</p>
  
  <pre><code>. = ALIGN(4);
  _etext = .;
  
  .relocate : AT (_etext)
  {
      . = ALIGN(4);
      _srelocate = .;
      *(.ramfunc .ramfunc.*);
      *(.data .data.*);
      . = ALIGN(4);
      _erelocate = .;
  } &gt; ram
  </code></pre>
  
  <p>Where <code>ram</code> is a memory segment whose origin is <code>0x20000000</code>. The issue as I see it is that <code>_etext</code> is a symbol that marks the end boundary of the <code>.text</code> segment, which is a part of a different memory segment, <code>rom</code>. This means that unless the aforementioned memory segment was 100% full, <code>_etext != _srelocate</code> will always be true. What this means is that we're copying memory beyond the <code>.text</code> section where nothing is defined to live according to the linker script.</p>
  
  <p>To me, this leads to one of three scenarios, either A) There is garbage present in <code>rom</code> beyond the <code>.text</code> section, and it gets copied into <code>.relocate</code> (and subsequently <code>.data</code>), or B) The memory beyond <code>.text</code> is empty following a chip erase operation prior to device programming, in which case <code>.relocate</code> is zeroed, or C) There is some slight of hand magic happening here where <code>.data</code> values are placed after <code>.text</code> in <code>rom</code>, and must be loaded into <code>ram</code>; in which case the comment should be <code>s/relocate/data</code>.</p>
  
  <p>The third scenario seems the most likely, but according to the linker script this can't be true. Can someone shed some light on this?</p>