title: Stack problems when calling printf from an ARM assembly function
body: <p>I have an ARM assembly function that is called from a C function.</p>
  
  <p>At some point, I do something like this:</p>
  
  <pre><code>.syntax unified  
  .arm
  .text
  .globl myfunc
  .extern printf
  
  myfunc:     
  stmdb sp!, {r4-r11}     // save stack from C call
  </code></pre>
  
  <p>... do stuff ...   </p>
  
  <pre><code>// (NOT SHOWN): Load values into r1 and r2 to be printed by format string above 
  ldr     r0, =message  // Load format string above
  push {lr}   // me attempting to preserve my stack
  bl      printf  // actual call to printf
  pop {lr}    // me attempting to recover my stack
  ldmia sp!, {r4-r11} // recover stack from C call
  mov r0, r2     // Move return value into r0
  mov pc, lr     //  Return to C
  .section data
   message:  
  .asciz "Output: %d, %d\n"
  .end
  </code></pre>
  
  <p>This runs sometimes, crashes sometimes, runs a few times then crashes, etc.  It actually runs on a quasi bare-metal context, so I can't run a debugger.  I'm 99% sure it's a stack -- or alignment? -- thing, as per this <a href="https://stackoverflow.com/questions/19359804/printf-change-values-in-registers-arm-assembly">Printf Change values in registers, ARM Assembly</a> and this <a href="https://stackoverflow.com/questions/1550758/call-c-function-from-assembly-the-application-freezes-at-call-printf-and-i">Call C function from Assembly -- the application freezes at &quot;call printf&quot; and I have no idea why</a>.  </p>
  
  <p>Can anyone provide some specific ideas for how to get the above chunk of code running, and perhaps general ideas for best practices here? Ideally I'd like to be able to call the same output function multiple times in my assembly file, to debug things as I go.  </p>
  
  <p>Thanks in advance!</p>