README.rst 46.1 KB
Newer Older
1
2
How can I run Magic Lantern in QEMU?
====================================
alex@thinkpad's avatar
alex@thinkpad committed
3
4
5
6
7

This guide shows you how to emulate Magic Lantern (or plain Canon firmware) in QEMU.

Eager to get started? Scroll down to `Installation`_.

8
9
10
11
12
13
14
15
.. class:: align-center

|pic1| |pic2|

.. |pic1| image:: doc/img/qemu-60D.png
    :width: 30 %
.. |pic2| image:: doc/img/qemu-M2-hello.jpg
    :width: 32.3 %
alex@thinkpad's avatar
alex@thinkpad committed
16
17
18
19
20
21

Current state
-------------

What works:

alex@thinkpad's avatar
alex@thinkpad committed
22
- Canon GUI with menu navigation - most DIGIC 4 and 5 models, some DIGIC 3 models
alex@thinkpad's avatar
alex@thinkpad committed
23
24
25
26
27
28
29
30
31
- Limited support for DIGIC 2, 3, 6 and 7 models
- Limited support for some PowerShot models
- Limited support for secondary DryOS cores (such as Eeko or 5D4 AE processor)
- File I/O works on most models (both SD and CF); might be unreliable
- Bootloader emulation works on all supported models (from DIGIC 2 to DIGIC 7)
- Loading AUTOEXEC.BIN / DISKBOOT.BIN from the virtual SD/CF card (from DIGIC 2 to DIGIC 6)
- Unmodified autoexec.bin works on many single-core camera models
  (and, with major limitations, on dual-core models)
- ML modules and Lua scripts (within the limitations of the emulation)
alex@thinkpad's avatar
alex@thinkpad committed
32
- DryOS/VxWorks timer (heartbeat) and task switching (all supported models)
alex@thinkpad's avatar
alex@thinkpad committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
- UART emulation (DryOS shell aka Dry-shell or DrySh on DIGIC 4 and 5 models)
- Deterministic execution with the ``-icount`` option (SD models only)
- Cache hacks are emulated to some extent (but "uninstalling" them does not work)
- EDMAC memcpy, including geometry parameters (matches the hardware closely, but not perfectly)
- Debugging with GDB:

  - assembly level for Canon code
  - source level for ML code (if compiled with -ggdb3 or similar)
  - ML stubs can be loaded as debugging symbols for Canon code (todo: also import from IDA or other systems)
  - predefined GDB scripts (log calls to DebugMsg, task_create, register_interrupt and a few others)
  - front-ends tested: cgdb (``splitgdb.sh``), DDD, gdbgui

- Debug messages at QEMU console:

  - Use qprintf / qprint / qprintn / qdisas for printing to QEMU console
  - Compile Magic Lantern with ``CONFIG_QEMU=y``
  - By default (``CONFIG_QEMU=n``), the debug messages are not compiled
    (therefore not increasing the size of the executable that runs on the camera)

- Log various actions of the guest operating system (Canon firmware, ML):

  - execution trace: ``-d exec,nochain -singlestep``
alex@thinkpad's avatar
alex@thinkpad committed
55
56
  - I/O trace: ``-d io``, ``-d io,int``
  - log hardware devices: ``-d mpu/sflash/sdcf/uart/int``
alex@thinkpad's avatar
alex@thinkpad committed
57
58
59
  - log all debug messages from Canon: ``-d debugmsg``
  - log all memory accesses: ``-d rom/ram/romr/ramw/etc``
  - log all function calls: ``-d calls``, ``-d calls,tail``
alex@thinkpad's avatar
alex@thinkpad committed
60
  - log all DryOS/VxWorks task switches: ``-d tasks``
alex@thinkpad's avatar
alex@thinkpad committed
61
62
63
64
  - track all function calls to provide a stack trace: ``-d callstack``
  - export all called functions to IDC script: ``-d idc``
  - identify memory blocks copied from ROM to RAM: ``-d romcpy``
  - check for memory errors (a la valgrind): ``-d memchk``
alex@thinkpad's avatar
alex@thinkpad committed
65
  - list all available items: ``-d help`` 
alex@thinkpad's avatar
alex@thinkpad committed
66
67
68
69
70
71
72
73
74

What does not work (yet):

- LiveView (WIP, very hard);
- Still photo capture (WIP - the capture process itself works);
- Image review (WIP);
- Dual core emulation aka IPC (WIP);
- Touch screen (TODO);
- Flash reprogramming (TODO, low priority);
alex@thinkpad's avatar
alex@thinkpad committed
75
- Most hardware devices (audio chip, ADTG, FPGAs, JPCORE, image processing engine...);
alex@thinkpad's avatar
alex@thinkpad committed
76
77
78
79
80
- Properties that require MPU communication (very hard; may require emulating the MPU code);
- Lens communication (done via MPU); initial lens info is replayed on startup on some models, but that's pretty much it;
- Cache behavior is not emulated (very hard; feel free to point us to code that can be reused);
- Native Windows build (QEMU can be compiled on Windows => contribution welcome).

81
82
Common issues and workarounds
`````````````````````````````
alex@thinkpad's avatar
alex@thinkpad committed
83

alex@thinkpad's avatar
alex@thinkpad committed
84
85
86
87
88
89
90
91
92
- Firmware version mismatch when trying to load ML

  - see `Incorrect firmware version?`_

- Camera was not shut down cleanly - Skipping module loading

  - closing QEMU window does not perform a clean shutdown
  - ``Machine -> Power Down`` - see `Shutdown and reboot`_ for more info

alex@thinkpad's avatar
alex@thinkpad committed
93
94
95
- dm-spy-experiments: saving the log and anything executed afterwards may not work

  - issue: cache hacks are not emulated very well
alex@thinkpad's avatar
alex@thinkpad committed
96
  - workaround: compile with ``CONFIG_QEMU=y``
alex@thinkpad's avatar
alex@thinkpad committed
97

alex@thinkpad's avatar
alex@thinkpad committed
98
99
100
101
102
- Program counter not exact in MMIO logs?

  - short answer: ``-d io,nochain -singlestep``
  - see `Execution trace incomplete? PC values from MMIO logs not correct?`_

103
104
105
106
107
108
109
110
111
112
113
114
- Netcat issues when interacting with ``qemu.monitor``

  There are many versions of netcat around.
  Newer variants of openbsd netcat
  (`since 1.111, Mar 2013 <https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/nc/netcat.c.diff?r1=1.110&r2=1.111&f=h>`_)
  require ``-N``, but older versions do not have ``-N`` and will print an error if you attempt to use it. GNU netcat or other variants were not tested.
  
  TLDR: try openbsd netcat. If you get an error after copy/pasting some ``nc`` command from this guide, simply remove the ``-N``.
  
  Look in ``run_tests.sh`` for a slightly more portable workaround.
  

alex@thinkpad's avatar
alex@thinkpad committed
115
116
117
118
119
120
121
122
Installation
------------

It is recommended to install from the `qemu <https://bitbucket.org/hudson/magic-lantern/branch/qemu>`_
branch, as it will contain the latest developments. The installation will be performed
outside the main magic-lantern directory, therefore you will be able to emulate any ML branch
without additional gymnastics (you will **not** have to merge ``qemu`` into your working branch or worry about it).

123
124
125
126
127
128
129
1. Clone the ``magic-lantern`` repository if you haven't already:

   .. code:: shell

     hg clone https://bitbucket.org/hudson/magic-lantern
     cd magic-lantern

alex@thinkpad's avatar
alex@thinkpad committed
130
131
   |

132
133
2. Run ``install.sh`` from the ``qemu`` branch:

alex@thinkpad's avatar
alex@thinkpad committed
134
   .. code:: shell
135

alex@thinkpad's avatar
alex@thinkpad committed
136
137
138
     /path/to/magic-lantern$  hg update qemu -C
     /path/to/magic-lantern$  cd contrib/qemu
     /path/to/magic-lantern/contrib/qemu$  ./install.sh
139

alex@thinkpad's avatar
alex@thinkpad committed
140
141
   |

142
143
3. Follow the instructions; you will have to supply your ROM files and compile QEMU:

alex@thinkpad's avatar
alex@thinkpad committed
144
   .. code:: shell
145

alex@thinkpad's avatar
alex@thinkpad committed
146
147
148
149
150
151
     # replace camera model (60D) with yours
     /path/to/qemu$  cp /path/to/sdcard/ML/LOGS/ROM*.BIN 60D/
     /path/to/qemu$  cd qemu-2.5.0
     /path/to/qemu/qemu-2.5.0$  ../configure_eos.sh
     /path/to/qemu/qemu-2.5.0$  make -j2
     /path/to/qemu/qemu-2.5.0$  cd ..
152

153
154
155
156
157
158
159
160
161
162
163
164
   Some recent camera models also use a serial flash. To list them, run this command:

   .. code:: shell
   
     cat qemu-2.5.0/hw/eos/model_list.c | grep -B 10 serial_flash_size | grep -E "\.(serial_flash_size|name) "

   or just watch out for an error about missing ``SFDATA.BIN`` when trying next step.

   If your camera requires a serial flash, compile the 
   `sf_dump module <https://bitbucket.org/hudson/magic-lantern/src/unified/modules/sf_dump>`_
   and run it on your camera to get this file.
   
alex@thinkpad's avatar
alex@thinkpad committed
165

166
4. Test your installation.
alex@thinkpad's avatar
alex@thinkpad committed
167

alex@thinkpad's avatar
alex@thinkpad committed
168
   The pre-installed SD/CF images come with a small autoexec.bin
alex@thinkpad's avatar
alex@thinkpad committed
169
170
171
   (the `portable display test <http://www.magiclantern.fm/forum/index.php?topic=14732.0>`_)
   that works on all supported EOS models. It does not work on PowerShot models
   (including recent EOS M models based on PowerShot firmware).
172

alex@thinkpad's avatar
alex@thinkpad committed
173
   .. code:: shell
174
 
alex@thinkpad's avatar
alex@thinkpad committed
175
176
     # all EOS models should run this without any trickery
     /path/to/qemu$  ./run_canon_fw.sh 60D,firmware="boot=1"
177

alex@thinkpad's avatar
alex@thinkpad committed
178
179
   |

180
181
5. Compile and run Magic Lantern

alex@thinkpad's avatar
alex@thinkpad committed
182
   .. code:: shell
183

alex@thinkpad's avatar
alex@thinkpad committed
184
185
186
187
188
     # from your magic-lantern directory
     /path/to/magic-lantern$  hg update your-working-branch -C # e.g. "hg update unified -C"
     /path/to/magic-lantern$  cd platform/60D.111
     /path/to/magic-lantern/platform/60D.111$ make clean; make
     /path/to/magic-lantern/platform/60D.111$ make install_qemu
189

alex@thinkpad's avatar
alex@thinkpad committed
190
   .. code:: shell
191

alex@thinkpad's avatar
alex@thinkpad committed
192
193
194
     # from the QEMU directory
     # some models will work only with this:
     /path/to/qemu$  ./run_canon_fw.sh 60D,firmware="boot=1"
195

alex@thinkpad's avatar
alex@thinkpad committed
196
     # some models require running under GDB (they won't boot the GUI otherwise)
alex@thinkpad's avatar
alex@thinkpad committed
197
     /path/to/qemu$  ./run_canon_fw.sh EOSM,firmware="boot=1" -s -S & arm-none-eabi-gdb -x EOSM/patches.gdb
alex@thinkpad's avatar
alex@thinkpad committed
198

alex@thinkpad's avatar
alex@thinkpad committed
199
200
   |

alex@thinkpad's avatar
alex@thinkpad committed
201
202
203
204
For reference, you may also look at `our test suite <https://builds.magiclantern.fm/jenkins/view/QEMU/job/QEMU-tests/lastSuccessfulBuild/console>`_,
where QEMU is installed from scratch every time the tests are run.
These logs can be very useful for troubleshooting.

alex@thinkpad's avatar
alex@thinkpad committed
205
206
While we don't provide a native Windows build yet,
it is possible to install QEMU and ML development tools
207
`under the Windows 10 Linux Subsystem (WSL) <http://www.magiclantern.fm/forum/index.php?topic=20214.0>`_.
alex@thinkpad's avatar
alex@thinkpad committed
208
209
210
211
212
213
214
215
216

Running Canon firmware
----------------------

From the QEMU directory, use the ``run_canon_fw.sh`` script and make sure
the `boot flag <http://magiclantern.wikia.com/wiki/Bootflags>`_ is disabled:

.. code:: shell

alex@thinkpad's avatar
alex@thinkpad committed
217
218
  # from the qemu directory
  ./run_canon_fw.sh 60D,firmware="boot=0"
alex@thinkpad's avatar
alex@thinkpad committed
219
220
221
222
223
224

Some models may need additional patches to run - these are stored under ``CAM/patches.gdb``.
To emulate these models, you will also need arm-none-eabi-gdb:

.. code:: shell

alex@thinkpad's avatar
alex@thinkpad committed
225
  ./run_canon_fw.sh EOSM,firmware="boot=0" -s -S & arm-none-eabi-gdb EOSM/patches.gdb
alex@thinkpad's avatar
alex@thinkpad committed
226
227
228
229
230

You'll probably want to see a few internals as well. To get started, try these:

.. code:: shell

alex@thinkpad's avatar
alex@thinkpad committed
231
232
233
234
235
  ./run_canon_fw.sh 60D,firmware="boot=0" -d debugmsg
  ./run_canon_fw.sh 60D,firmware="boot=0" -d debugmsg,tasks
  ./run_canon_fw.sh 60D,firmware="boot=0" -d debugmsg,io
  ./run_canon_fw.sh 60D,firmware="boot=0" -d io,int
  ./run_canon_fw.sh 60D,firmware="boot=0" -d help
alex@thinkpad's avatar
alex@thinkpad committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259

Running Magic Lantern
---------------------

As you already know, Magic Lantern runs from the SD or CF card. For emulation,
we provide two card images (sd.img and cf.img) which you can mount on your operating system
and copy files on them. If these images use a FAT filesystem (they do, by default), we prefer 
`mtools <https://www.gnu.org/software/mtools/>`_ for automated tasks
(such as copying files to/from the card images without mounting them).

To install Magic Lantern to the virtual card, you may:

- mount the card image (sd.img or cf.img) as /whatever/EOS_DIGITAL,
  then run ``make install`` from your platform directory:

  .. code:: shell

    # from the magic-lantern directory
    cd platform/60D.111
    make clean; make
    # make sure your virtual card is mounted (this step is operating system specific)
    make install
    # make sure your virtual card is no longer mounted

alex@thinkpad's avatar
alex@thinkpad committed
260
261
  |

alex@thinkpad's avatar
alex@thinkpad committed
262
263
264
- use ``make install_qemu`` from your platform directory
  (requires mtools, but you do not have to mount your card images)

265
  .. code:: shell
alex@thinkpad's avatar
alex@thinkpad committed
266
267
268
269
270
271

    # from the magic-lantern directory
    cd platform/60D.111
    make clean; make
    make install_qemu

alex@thinkpad's avatar
alex@thinkpad committed
272
273
  |

alex@thinkpad's avatar
alex@thinkpad committed
274
275
276
277
278
279
280
281
282
283
284
285
The included card images are already bootable for EOS firmwares (but not for PowerShots).

After you have copied Magic Lantern to the card, you may run it from the ``qemu`` directory
(near the ``magic-lantern`` one, at the same level). It's probably best to use a second terminal,
to avoid changing the directory between ML and QEMU.

.. code:: shell

  # from the qemu directory
  ./run_canon_fw.sh 60D,firmware="boot=1"
  
  # or, if your camera requires patches.gdb:
alex@thinkpad's avatar
alex@thinkpad committed
286
  ./run_canon_fw.sh EOSM,firmware="boot=1" -s -S & arm-none-eabi-gdb EOSM/patches.gdb
alex@thinkpad's avatar
alex@thinkpad committed
287
288
289
290
291
292


Incorrect firmware version?
```````````````````````````

If your camera model requires ``patches.gdb``, you may be in trouble:
alex@thinkpad's avatar
alex@thinkpad committed
293
many of these scripts will perform temporary changes to the ROM. However,
alex@thinkpad's avatar
alex@thinkpad committed
294
295
296
297
298
299
at startup, ML computes a simple signature of the firmware,
to make sure it is started on the correct camera model and firmware version
(and print an error message otherwise, with portable display routines).
These patches will change the firmware signature - so you'll get an error message
telling you the firmware version is incorrect (even though it is the right one).

alex@thinkpad's avatar
alex@thinkpad committed
300
To work around this issue, you may edit ``src/fw-signature.h``
alex@thinkpad's avatar
alex@thinkpad committed
301
and comment out the signature for your camera to disable this check.
alex@thinkpad's avatar
alex@thinkpad committed
302
Recompile and run ML as you already know:
alex@thinkpad's avatar
alex@thinkpad committed
303
304
305
306
307
308

.. code:: shell

  ./run_canon_fw.sh EOSM2,firmware="boot=1" -s -S & arm-none-eabi-gdb EOSM2/patches.gdb

The mere presence of a ``patches.gdb`` script in your camera subdirectory
alex@thinkpad's avatar
alex@thinkpad committed
309
310
does not automatically mean you'll get the above issue. Some patches modify Canon code
in a way that does not change the firmware signature (EOSM).
alex@thinkpad's avatar
alex@thinkpad committed
311

alex@thinkpad's avatar
alex@thinkpad committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
Navigating menus
````````````````

Press ``F1`` to show the available keys (they are model-specific), or just read them
from the emulation log. Some keys will only send "press" events, while others
will send "press and release" events (this is also model-specific
and printed on the console).

Scrollwheels, if turned very quickly, may send a single event that includes
more than one click. This complicates scrollwheel handling code on ML side
and often leads to subtle issues. Currently, this behavior is not emulated.

Shutdown and reboot
```````````````````

327
By default, closing the QEMU window is equivalent to unplugging the power cord
alex@thinkpad's avatar
alex@thinkpad committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
(if your camera is on external power source). This appears to be the default
with other operating systems as well, so we did not change it.

Please note: closing QEMU window is **not** equivalent to taking the battery out
- see `Opening the battery door`_ for details.

Shutting down
'''''''''''''

To perform a clean shutdown (similar to powering down the camera from the main switch),
you may:

- select ``Machine -> Power Down`` from the menu (QEMU window)
- send the ``system_powerdown`` command to QEMU monitor:

.. code:: shell

345
  echo "system_powerdown" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
346
347
348
349

Internally, Canon code refers to this kind of shutdown as ``SHUTDOWN_REQUEST``
(watch their debug messages with ``-d debugmsg``).

alex@thinkpad's avatar
alex@thinkpad committed
350
351
352
353
354
355
356
Caveat: the ``system_powerdown`` event does not guarantee a shutdown will actually occur
(either because the firmware handles this event in a different way, or if the execution
gets stuck for any reason). As a workaround, you could issue the ``quit`` command
after some timeout, if QEMU is still running:

.. code:: shell

357
  echo "system_powerdown" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
358
  sleep 2
359
360
  if nc -N -U qemu.monitor < /dev/null > /dev/null 2>&1; then
    echo "quit" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
361
362
  fi

alex@thinkpad's avatar
alex@thinkpad committed
363
364
365
366
367
368
369
370
371
372
373
374
375
Opening the card door
'''''''''''''''''''''

Opening the SD/CF card door is a clean (non-rushed) way to shut down Canon firmware (``SHUTDOWN_REQUEST``).
To emulate this kind of shutdown, press ``C`` to simulate opening the card door,
then wait for a few seconds for QEMU to shutdown.

Opening the card door and closing it back quickly enough may result
in shutdown being canceled. Closing the card door is not implemented,
therefore this behavior is not emulated yet.

Opening the battery door
''''''''''''''''''''''''
alex@thinkpad's avatar
alex@thinkpad committed
376

alex@thinkpad's avatar
alex@thinkpad committed
377
378
379
380
381
382
383
384
385
386
387
388
Opening the battery door is interpreted by Canon firmware as an emergency shutdown (``PROP_ABORT``),
but it's still a clean(ish) shutdown. To emulate this kind of shutdown, press ``B``,
then close the QEMU window manually (or send the ``quit`` command to QEMU monitor).
Currently we do not know how to trigger or recognize a hardware shutdown event.

Rebooting
'''''''''

The camera can be rebooted from software by triggering ``PROP_REBOOT``.
Canon firmware handles it as a regular shutdown (``SHUTDOWN_REQUEST``),
followed by a regular boot. In QEMU, triggering ``PROP_REBOOT`` from software
will perform a clean shutdown (rebooting is not implemented).
alex@thinkpad's avatar
alex@thinkpad committed
389
390

Running ML Lua scripts
alex@thinkpad's avatar
alex@thinkpad committed
391
``````````````````````
alex@thinkpad's avatar
alex@thinkpad committed
392
393
394
395
396
397
398
399
400
401
402

- Install ML on the virtual SD card

  .. code:: shell

    # from the qemu directory
    wget https://builds.magiclantern.fm/jenkins/job/lua_fix/415/artifact/platform/60D.111/magiclantern-lua_fix.2017Sep11.60D111.zip
    unzip magiclantern-lua_fix.2017Sep11.60D111.zip -d ml-tmp
    ./mtools_copy_ml.sh ml-tmp
    rm -rf ml-tmp/

alex@thinkpad's avatar
alex@thinkpad committed
403
404
  |

alex@thinkpad's avatar
alex@thinkpad committed
405
406
407
408
409
- Run QEMU

  .. code:: shell

    ./run_canon_fw.sh 60D,firmware="boot=1"
alex@thinkpad's avatar
alex@thinkpad committed
410

alex@thinkpad's avatar
alex@thinkpad committed
411
412
  |

alex@thinkpad's avatar
alex@thinkpad committed
413
- enable the Lua module
alex@thinkpad's avatar
alex@thinkpad committed
414
- reboot the virtual camera cleanly (menu: Machine -> Power Down, then start it again)
alex@thinkpad's avatar
alex@thinkpad committed
415
416
417
418
419
- run the Hello World script

TODO: make api_test.lua run, fix bugs, polish the guide.

Using multiple firmware versions
alex@thinkpad's avatar
alex@thinkpad committed
420
````````````````````````````````
alex@thinkpad's avatar
alex@thinkpad committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447

In most cases, Magic Lantern only supports one firmware version, to keep things simple.
However, there may be good reasons to support two firmware versions
(for example, on the 5D Mark III, there are valid reasons to choose
both `1.1.3 <http://www.magiclantern.fm/forum/index.php?topic=14704.0>`_
and `1.2.3 <http://www.magiclantern.fm/forum/index.php?topic=11017.0>`_)
or you may want to test both versions when porting Magic Lantern
`to a newer Canon firmware <https://www.magiclantern.fm/forum/index.php?topic=19417.0>`_.

The invocation looks like this (notice the ``113``):

.. code:: shell

  ./run_canon_fw.sh 5D3,firmware="113;boot=0" -s -S & arm-none-eabi-gdb -x 5D3/debugmsg.gdb

And the directory layout should be like this:

.. code::

  /path/to/qemu/5D3/113/ROM0.BIN
  /path/to/qemu/5D3/113/ROM1.BIN
  /path/to/qemu/5D3/123/ROM0.BIN
  /path/to/qemu/5D3/123/ROM1.BIN
  /path/to/qemu/5D3/113/ROM0.BIN
  /path/to/qemu/5D3/debugmsg.gdb  # common to both versions
  /path/to/qemu/5D3/patches.gdb   # common to both versions

448
Compare this to a camera model where only one firmware version is supported:
alex@thinkpad's avatar
alex@thinkpad committed
449
450
451
452
453
454

.. code::

  /path/to/qemu/60D/ROM0.BIN
  /path/to/qemu/60D/ROM1.BIN

alex@thinkpad's avatar
alex@thinkpad committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
Running from the physical SD/CF card
````````````````````````````````````

You may also start QEMU from the same card you use in the physical camera - 
this might be useful for troubleshooting issues with Magic Lantern.

The safest way (but requires some disk space) would be to create an image
of your SD (or CF) card (`tutorial for Windows and Mac <https://thepihut.com/blogs/raspberry-pi-tutorials/17789160-backing-up-and-restoring-your-raspberry-pis-sd-card>`_):

.. code:: shell

  dd if=/dev/your-sd-card of=sd.img bs=1M

and run QEMU from the resulting ``sd.img`` (or ``cf.img``).

To run the emulation directly from a physical SD/CF card:

- See `QEMU docs (Using host drives) <https://qemu.weilnetz.de/doc/qemu-doc.html#Using-host-drives>`_
  and `these warnings <https://wiki.archlinux.org/index.php/QEMU#Using_any_real_partition_as_the_single_primary_partition_of_a_hard_disk_image>`_
- Replace ``file=sd.img`` (or ``file=cf.img``) with ``file=/dev/your-sd-card`` in ``run_canon_fw.sh``
- Configure the appropriate permissions and run the emulation as usual.

**Warning: Canon firmware WILL write to the SD/CF card during startup, 
and might even attempt to format it if the filesystem is not recognized,
or because of emulation bugs. 
Be very careful not to give it write access to your physical hard-disk!!!**

Note: the ROM files will not be loaded from the SD/CF card.

alex@thinkpad's avatar
alex@thinkpad committed
484
485
486
487
488
489
490
Automation
----------

QEMU monitor
````````````

By default, the QEMU monitor console is available by default as a UNIX socket.
alex@thinkpad's avatar
alex@thinkpad committed
491
492
493
494
495
496
That means, during emulation you can interact with it using netcat:

- interactive console

  .. code:: shell

497
    nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
498

alex@thinkpad's avatar
alex@thinkpad committed
499
500
  |

alex@thinkpad's avatar
alex@thinkpad committed
501
- one-liner commands, usable from scripts:
alex@thinkpad's avatar
alex@thinkpad committed
502
503
504

  .. code:: shell

505
    echo "log io" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
506

alex@thinkpad's avatar
alex@thinkpad committed
507
508
  |

alex@thinkpad's avatar
alex@thinkpad committed
509
- check whether QEMU monitor is active:
alex@thinkpad's avatar
alex@thinkpad committed
510
511
512

  .. code:: shell

513
    if nc -N -U qemu.monitor < /dev/null > /dev/null 2>&1; then
alex@thinkpad's avatar
alex@thinkpad committed
514
515
      ...
    fi
alex@thinkpad's avatar
alex@thinkpad committed
516

alex@thinkpad's avatar
alex@thinkpad committed
517
518
  |

alex@thinkpad's avatar
alex@thinkpad committed
519
520
521
522
523
524
525
526
527
528
529
530
531
532
You can redirect the monitor console to stdio with... ``-monitor stdio``.

Taking screenshots
``````````````````

The easiest way is to use the ``screendump`` command from QEMU monitor.
In the following example, we'll redirect the monitor to stdio
and take a screenshot after 10 seconds.

.. code:: shell

  ( 
    sleep 10
    echo screendump snap.ppm
alex@thinkpad's avatar
alex@thinkpad committed
533
    echo system_powerdown
alex@thinkpad's avatar
alex@thinkpad committed
534
535
536
537
538
539
540
541
542
543
544
545
546
  ) | (
    ./run_canon_fw.sh 60D,firmware='boot=0' \
        -monitor stdio
  )

Another option is to use the VNC interface:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware='boot=0' \
        -vnc :1234 &
  sleep 10
  vncdotool -s :1234 capture snap.png
547
  echo "system_powerdown" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562

Sending keystrokes
``````````````````

From QEMU monitor:

.. code::

  (qemu) help
  sendkey keys [hold_ms] -- send keys to the VM (e.g. 'sendkey ctrl-alt-f1', default hold time=100 ms)

.. code:: shell

  ( 
    sleep 10
alex@thinkpad's avatar
alex@thinkpad committed
563
    echo sendkey m
alex@thinkpad's avatar
alex@thinkpad committed
564
565
    sleep 1
    echo screendump menu.ppm
alex@thinkpad's avatar
alex@thinkpad committed
566
    echo system_powerdown
alex@thinkpad's avatar
alex@thinkpad committed
567
568
569
570
571
  ) | (
    ./run_canon_fw.sh 60D,firmware='boot=0' \
        -monitor stdio
  )

alex@thinkpad's avatar
alex@thinkpad committed
572
573
574
575
576
577
578
Or, if QEMU runs as a background process:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware='boot=0' &
  
  sleep 10
579
  echo "sendkey m" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
580
  sleep 1
581
582
  echo "screendump menu.ppm" | nc -N -U qemu.monitor
  echo "system_powerdown" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
583

alex@thinkpad's avatar
alex@thinkpad committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
From VNC:

.. code:: shell

  vncdotool -h | grep key
  key KEY		send KEY to server, alphanumeric or keysym: ctrl-c, del
  keyup KEY		send KEY released
  keydown KEY		send KEY pressed

.. code:: shell

  ./run_canon_fw.sh 60D,firmware='boot=0' \
        -vnc :1234 &
  sleep 10
  vncdotool -s :1234 key m
  sleep 1
  vncdotool -s :1234 capture snap.png
601
  echo "system_powerdown" | nc -N -U qemu.monitor
alex@thinkpad's avatar
alex@thinkpad committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622

Running multiple ML builds from a single command
````````````````````````````````````````````````

You may run ML builds from multiple models, unattended,
with the ``run_ml_all_cams.sh`` script:

.. code:: shell

  env ML_PLATFORMS="500D.111/ 60D.111/" \
      TIMEOUT=10 \
      SCREENSHOT=1 \
      ./run_ml_all_cams.sh

Internally, this is how the emulator is invoked:

.. code:: shell

  ( 
    sleep 10
    echo screendump 60D.111.ppm
alex@thinkpad's avatar
alex@thinkpad committed
623
    echo system_powerdown
alex@thinkpad's avatar
alex@thinkpad committed
624
625
626
627
628
629
630
631
632
633
634
635
636
637
  ) | (
    ./run_canon_fw.sh 60D,firmware='boot=1' \
        -display none -monitor stdio  -s -S
  ) &> 60D.111.log


This script is very customizable (see the source code for available options).

More examples:

- `EOSM2 hello world <https://builds.magiclantern.fm/jenkins/view/QEMU/job/QEMU-EOSM2/18/console>`_
- running ML from the dm-spy-experiments branch in the emulator (`QEMU-dm-spy <https://builds.magiclantern.fm/jenkins/view/QEMU/job/QEMU-dm-spy/65/consoleFull>`_)
- running the FA_CaptureTestImage test based on the minimal ML target (`QEMU-FA_CaptureTestImage <https://builds.magiclantern.fm/jenkins/view/QEMU/job/QEMU-FA_CaptureTestImage>`_)

638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
Parallel execution
``````````````````

On modern machines, you will get significant speed gains by running multiple instances of QEMU in parallel.
This is tricky and not automated. You need to be careful with the following global resources:

- SD and CF images (``sd.img`` and ``cf.img``):

  If all your parallel instances require the same initial SD/CF card contents,
  and you do not need to inspect the changes to SD/CF after the experiment,
  you may use these files as read-only shared resources with the help of QEMU's
  `temporary snapshot <https://wiki.qemu.org/Documentation/CreateSnapshot#Temporary_snapshots>`_ feature
  (simply add ``-snapshot`` to your command line). This will discard any changes to ``sd.img`` and ``cf.img``.
  `Implementation details <https://lists.gnu.org/archive/html/qemu-devel/2008-09/msg00712.html>`_.

  Otherwise, you could allocate different SD/CF images for each instance, but it's up to you to modify the scripts to handle that.

- QEMU monitor socket (``qemu.monitor``):

  Set the ``QEMU_JOB_ID`` environment variable; it will be used as suffix for ``qemu.monitor``.
  
  Example: ``QEMU_JOB_ID=1 ./run_canon_fw.sh 5D3`` will use ``qemu.monitor1`` for monitor commands.

- GDB port (with ``-s -S``, this port is 1234):

663
  Set QEMU_JOB_ID to a small positive integer, for example:
664
665
666

  .. code:: shell

667
668
669
670
671
672
673
674
675
    export QEMU_JOB_ID=1
  
  |
  
  Then you'll be able to do this:

  .. code:: shell

    QEMU_MONITOR=qemu.monitor$QEMU_JOB_ID
676
677
678
679
680
681
    GDB_PORT=$((1234+$QEMU_JOB_ID))
    ./run_canon_fw.sh EOSM2 -S -gdb tcp::$GDB_PORT &
    arm-none-eabi-gdb -ex "set \$TCP_PORT=$GDB_PORT" -x EOSM2/patches.gdb -ex quit &
    
    # interact with monitor commands
    sleep 5
682
    echo "sendkey m" | nc -N -U $QEMU_MONITOR
683
684
685
    sleep 1

    # quit when finished
686
687
688
    echo "quit" | nc -N -U $QEMU_MONITOR

  |
689
690
691
692
693
694
695

- VNC display

  Same as above:

  .. code:: shell

696
    QEMU_MONITOR=qemu.monitor$QEMU_JOB_ID
697
698
699
700
701
    VNC_DISP=":$((12345+QEMU_JOB_ID))"
    ./run_canon_fw.sh 5D3 -vnc $VNC_DISP &
    
    # interact with vncdotool
    sleep 5
702
    vncdotool -s $VNC_DISP key m
703
704
705
    sleep 1
    
    # quit when finished
706
707
708
    echo "quit" | nc -N -U $QEMU_MONITOR

  |
709
710
711
712
713
714
715
716
717
718

- any temporary files you may want to use

  Use something like ``mktemp`` rather than hardcoding a filename.
  Or, try achieving the same thing without a temporary file (pipes, process substitution).

- any other global resources (you'll have to figure them out on your own).

TODO: can this be automated somehow with containers?

alex@thinkpad's avatar
alex@thinkpad committed
719
720
721
Debugging
---------

alex@thinkpad's avatar
alex@thinkpad committed
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
From the QEMU monitor
`````````````````````

.. code:: shell

  echo "help" | ./run_canon_fw.sh 60D -monitor stdio |& grep dump
  ...
  pmemsave addr size file -- save to disk physical memory dump starting at 'addr' of size 'size'
  xp /fmt addr -- physical memory dump starting at 'addr'

Using ``qprintf`` and friends
`````````````````````````````

The QEMU debugging API
(`qemu-util.h <https://bitbucket.org/hudson/magic-lantern/src/qemu/src/qemu-util.h>`_, included by default by ``dryos.h``)
exposes the following functions to be used in Magic Lantern code:

:qprintf: heavyweight, similar to printf; requires vsnprintf from Canon code
:qprint: lightweight, inline, similar to puts, without newline
:qprintn: lightweight, prints a 32-bit integer
:qdisas: lightweight, tells QEMU to disassemble one ARM or Thumb instruction at the given address

These functions will print to QEMU console whenever ML (or a subset of it)
is compiled with ``CONFIG_QEMU=y``. They won't get compiled in regular builds
(``CONFIG_QEMU=n`` is the default), therefore they won't increase the executable size.
For this reason, feel free to use them *anywhere*.

You may use the debugging API for either the entire ML, or just for a subset of it
- e.g. the source file(s) you are currently editing, or only some modules.
The lightweight functions can also be used in very early boot code,
where you can't call vsnprintf or you may not even have a stack properly set up.

CONFIG_QEMU
```````````

:``CONFIG_QEMU=n``: (default):

- regular build
- the executable works in QEMU (within the limitations of the emulation)
- no guest debugging code (no additional debugging facilities)

:``CONFIG_QEMU=y``: (optional, on the command line or in ``Makefile.user``):

- debug build for QEMU only
- does **not** run on the camera (!)
- enables ``qprintf`` and friends to print to the QEMU console
- enables unlimited number of ROM patches - useful for 
  `dm-spy-experiments <https://www.magiclantern.fm/forum/index.php?topic=2388.0>`_
  (in QEMU you can simply write to ROM as if it were RAM)
- may enable workarounds for models or features that are not emulated very well

Example:

.. code:: shell

    cd platform/550D.109
    make clean; make                            # regular build
    make clean; make CONFIG_QEMU=y              # debug build for QEMU
    make clean; make install_qemu               # build and install a regular build to the QEMU SD/CF image
    make clean; make install_qemu CONFIG_QEMU=y # build and install a QEMU build to the QEMU SD/CF image

It works for modules as well:

.. code:: shell

    cd modules/lua
    # add some qprintf call in lua_init for testing
    make clean; make                  # regular build
    make clean; make CONFIG_QEMU=y    # debug build for QEMU
    # todo: make install_qemu doesn't work here yet

Tracing guest events (execution, I/O, debug messages, RAM, function calls...)
`````````````````````````````````````````````````````````````````````````````

Execution trace:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d exec,nochain -singlestep

I/O trace (quick):

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d io

I/O trace (precise):

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d io,nochain -singlestep

I/O trace with interrupts (precise):

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d io,int,nochain -singlestep

I/O trace with Canon debug messages (quick):

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d debugmsg,io

Canon debug messages and task switches:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d debugmsg,tasks

Memory access trace (ROM reads, RAM writes) - very verbose:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d romr,ramw

Call/return trace:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d calls

Also with tail calls, redirected to a log file:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d calls,tail &> calls.log

Tip: set your editor to highlight the log file as if it were Python code.
You'll get collapse markers for free :)

Also with debug messages, I/O events and interrupts, redirected to file

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d debugmsg,calls,tail,io,int &> full.log

Filter the logs with grep:

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d debugmsg,io |& grep -C 5 "\[Display\]"

Only log autoexec.bin activity (skip logging the bootloader):

.. code:: shell

  ./run_canon_fw.sh 60D,firmware="boot=0" -d exec,io,int,autoexec


Execution trace incomplete? PC values from MMIO logs not correct?
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

That's because QEMU compiles multiple guest instructions into a single TranslationBlock,
for faster execution. In this mode, `-d exec` will print guest instructions as they are compiled
alex@thinkpad's avatar
alex@thinkpad committed
877
878
879
880
881
(for example, if you have a tight loop, only the first pass will be printed).

To log every single guest instruction, as executed, and get exact PC values
in execution traces and MMIO logs, you need to use `-d nochain -singlestep` 
(for example: `-d exec,nochain -singlestep` or `-d io,int,nochain -singlestep`)
alex@thinkpad's avatar
alex@thinkpad committed
882
883
884
885
886
- `source <http://qemu-discuss.nongnu.narkive.com/f8A4tqdT/singlestepping-target-assembly-instructions>`_.

Debugging with GDB
``````````````````

alex@thinkpad's avatar
alex@thinkpad committed
887
888
889
890
891
See `the EOS M2 example <http://www.magiclantern.fm/forum/index.php?topic=15895.msg186173#msg186173>`_:

.. code:: shell

    ./run_canon_fw.sh EOSM2,firmware="boot=1" -s -S & arm-none-eabi-gdb -x EOSM2/debugmsg.gdb
alex@thinkpad's avatar
alex@thinkpad committed
892

893
894
895
896
.. image:: doc/img/ddd.png
   :scale: 50 %
   :align: center

alex@thinkpad's avatar
alex@thinkpad committed
897

alex@thinkpad's avatar
alex@thinkpad committed
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
Instrumentation
---------------

`TODO (see QEMU forum thread) <http://www.magiclantern.fm/forum/index.php?topic=2864.msg184125#msg184125>`_

Hacking
-------

This is bleeding-edge development used primarily for reverse engineering.
You will want to modify the sources, sooner or later.

How is this code organazized?
`````````````````````````````
.. code:: shell

  magic-lantern/contrib/qemu/eos -> qemu/qemu-2.5.0/hw/eos/  (emulation sources)
  magic-lantern/contrib/qemu/eos/dbi -> qemu/qemu-2.5.0/hw/eos/dbi (instrumentation)
  magic-lantern/src/backtrace.[ch] -> qemu/qemu-2.5.0/hw/eos/dbi/backtrace.[ch] (shared with ML)
  magic-lantern/contrib/qemu/scripts -> qemu/ (helper scripts, such as run_canon_fw.sh)
  magic-lantern/contrib/qemu/scripts/*/*.gdb -> qemu/*/*.gdb (GDB scripts)
  magic-lantern/contrib/qemu/tests -> qemu/tests (guess)

MMIO handlers: eos_handle_whatever (with io_log for debug messages).

Useful: eos_get_current_task_name/id/stack, eos_mem_read/write.

alex@thinkpad's avatar
alex@thinkpad committed
924
925
926
To customize keys or add support for new buttons or GUI events,
edit ``mpu.c``, ``button_codes.h`` and ``extract_buton_codes.py``. 

927
928
929
930
931
932
933
934
935
936
937
938
Image capture emulation
```````````````````````

WIP, still pretty rough.

To capture a full-res image (aka FRSP) using a CR2 as reference data for the virtual sensor:

.. code:: shell

    make -C ../magic-lantern/minimal/qemu-frsp MODEL=5D3 CONFIG_QEMU=y clean install_qemu
    env QEMU_EOS_VRAM_PH_QR_RAW='/path/to/IMG_1234.CR2' ./run_canon_fw.sh 5D3,firmware="boot=1"

alex@thinkpad's avatar
alex@thinkpad committed
939
940
941
Adding support for a new camera model
`````````````````````````````````````

alex@thinkpad's avatar
alex@thinkpad committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
TLDR? Jump to step 3.

Initial firmware analysis
'''''''''''''''''''''''''

1) Find the ROM load address and the code start address.
   If unknown, use an initial guess to disassemble (even 0),
   then look for code jumping to or referencing some absolute address
   and make an educated guess from there.

   DIGIC 5 and earlier models will start the bootloader at ``0xFFFF0000`` (HIVECS)
   and will jump to main firmware at ``0xFF810000``, ``0xFF010000`` or ``0xFF0C0000``.
   There is one main ROM (ROM1) at 0xF8000000, 4/8/16/32 MiB mirrored until 0xF8000000,
   and there may be a second ROM (ROM0) at 0xF0000000, mirrored until 0xF8000000.

   DIGIC 6 will start at ``*(uint32_t*)0xFC000000``,
   bootloader is at 0xFE020000 and main firmware starts at 0xFE0A0000. There is
   a 32 MiB ROM mirrored at 0xFC000000 and 0xFE000000 (there may be others).

   The ROM load address is the one you have used when dumping it (usually one of the mirrors).
   The memory map is printed when starting QEMU - you'll see where each ROM is loaded
   and where are the mirrored copies, if any.

   The MPU/MMU configuration (printed in QEMU as soon as the guest code
   changes the relevant registers) is very useful for finding the memory map
   on new models (see the ARM ARM documentation for the CPU you are interested in --
   DIGIC 2..5: ARM946E-S, D6: Cortex R4, D7: Cortex A9).

2) (Re)load the code in the disassembler at the correct address:

   - `Loading into IDA <https://www.magiclantern.fm/forum/index.php?topic=6785.0>`_
   - `Tutorial: finding stubs (with disassemble.pl) <https://www.magiclantern.fm/forum/index.php?topic=12177.msg117735#msg117735>`_
   - `Loading into ARMu <https://www.magiclantern.fm/forum/index.php?topic=9827.0>`_
   - Other disassemblers will also work (the list is open).

alex@thinkpad's avatar
alex@thinkpad committed
977
978
   |

alex@thinkpad's avatar
alex@thinkpad committed
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
3) Add a very simple definition for your camera and get an `initial test run`_.
   Try to guess some missing bits from the error messages, if possible.

4) (optional) Export the functions called during your test run:

   .. code:: shell

     ./run_canon_fw.sh EOSM2,firmware="boot=0" -d idc
     ...
     EOSM2.idc saved.

   Load the IDC script into IDA, or convert it if you are using a different disassembler.

4) Code blocks copied from ROM to RAM

   .. code:: shell
  
     ./run_canon_fw.sh EOSM2,firmware="boot=0" -d romcpy |& grep ROMCPY
    [ROMCPY] 0xFFFF0000 -> 0x0        size 0x40       at 0xFFFF0980
    [ROMCPY] 0xFFFE0000 -> 0x100000   size 0xFF2C     at 0xFFFF0FCC
    [ROMCPY] 0xFFD1F02C -> 0x1900     size 0xB70A0    at 0xFF0C000C
    [ROMCPY] 0xFF0C0E04 -> 0x4B0      size 0x1E8      at 0xFF0C0D70

   You may extract these blobs with:

   .. code:: shell

     dd if=ROM1.BIN of=EOSM2.0x1900.BIN bs=1 skip=$((0xD1F0E4)) count=$((0xB70A0))

1008
   If you are analyzing the main firmware, load EOSM2.0x1900.BIN as an additional binary file
alex@thinkpad's avatar
alex@thinkpad committed
1009
1010
1011
1012
1013
1014
1015
1016
   (in IDA, choose segment 0, offset 0x1900). Do the same for the blob copied at 0x4B0.

   If you are analyzing the bootloader, extract and load the first two blobs in the same way.
   Other models may have slightly different configurations, so YMMV.

Initial test run
''''''''''''''''

alex@thinkpad's avatar
alex@thinkpad committed
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
Start by editing ``hw/eos/model_list.c``, where you'll need to add an entry
for your camera model. The simplest one would be:

.. code:: C

    {
        .name                   = "5DS",
        .digic_version          = 6,
    },

Then, run it and follow the errors:

.. code:: shell

  ./run_canon_fw.sh 5DS
  ...
  BooMEMIF NG MR05=00000000 FROM=00000001
  BTCM Start Master

What's that? Looks like some sort of error message, and indeed, it is.
In Canon parlance, NG means "not good" - see for example ``NG AllocateMemory``
on the "out of memory" code path. Let's check whether this error message has to do
with I/O activity (usually that's where most emulation issues come from):

.. code:: shell

  ./run_canon_fw.sh 5DS -d io
  ...
  [DIGIC6]   at 0xFE020CC8:FE020B5C [0xD203040C] <- 0x500     : MR (RAM manufacturer ID)
  [DIGIC6]   at 0xFE020CC8:FE020B5C [0xD203040C] <- 0x20500   : MR (RAM manufacturer ID)
  [DIGIC6]   at 0xFE020CC8:FE020B5C [0xD203040C] -> 0x0       : MR (RAM manufacturer ID)
  MEMIF NG MR05=00000000 FROM=00000001
  BTCM Start Master

OK, so the message appears to be related to these I/O registers.
Look up the code that's handling them (search for "RAM manufacturer ID").
You'll find it in eos.c:eos_handle_digic6, at the register 0xD203040C
(as expected), and you'll find it uses a model-specific constant:
1055
``s->model->ram_manufacturer_id``. Let's look around to see what's up with it:
alex@thinkpad's avatar
alex@thinkpad committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071

.. code:: C

  .name                   = "80D",
  .ram_manufacturer_id    = 0x18000103,   /* RAM manufacturer: Micron */

  .name                   = "750D",
  .ram_manufacturer_id    = 0x14000203,

  .name                   = "5D4",
  .ram_manufacturer_id    = 0x18000401,

Good - it's now clear you'll have to find this constant. You have many choices here:

- disassemble the ROM near the affected address,
  and try to understand what value Canon code expects from this register
1072
- use pattern matching and find it based on a similar camera model
alex@thinkpad's avatar
alex@thinkpad committed
1073
1074
1075
1076
1077
1078
1079
- try the values from another camera model, hoping for the best
- trial and error

Let's go for the last one (probably the easiest). If you look at the code,
you may notice the "5" corresponds to the least significant byte in this RAM ID.
If you didn't, don't worry - you can just try something like 0x12345678:

alex@thinkpad's avatar
alex@thinkpad committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
.. code:: C

    {
        .name                   = "5DS",
        .digic_version          = 6,
        .ram_manufacturer_id    = 0x12345678,
    },

and the new error message will tell you the answer right away:
alex@thinkpad's avatar
alex@thinkpad committed
1089
1090
1091
1092
1093
1094
1095
1096

.. code::

  MEMIF NG MR05=00000078 FROM=00000001

You now have at most 4 test runs to find this code :)

A more complete example: the `EOS M2 walkthrough <http://www.magiclantern.fm/forum/index.php?topic=15895.msg185103#msg185103>`_
1097
shows how to add support for this camera from scratch, right through to getting the Canon GUI to boot (and more!)
alex@thinkpad's avatar
alex@thinkpad committed
1098
1099

Although this model is already supported in the repository,
alex@thinkpad's avatar
alex@thinkpad committed
1100
1101
1102
you can always roll back to an older changeset (``3124887``) and follow the tutorial.


1103
1104
Adding support for a new Canon firmware version
```````````````````````````````````````````````
alex@thinkpad's avatar
alex@thinkpad committed
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114

You will have to update:

- GDB scripts (easy - copy/paste from ML stubs or look them up)
- expected test results (time-consuming, see the `Test suite`_)
- any hardcoded stubs that might be around (e.g. in ``dbi/memcheck.c``)

Most other emulation bits usually do not depend on the firmware version
(5D3 1.2.3 was an exception).

1115
`Updating Magic Lantern to run on a new Canon firmware version <https://www.magiclantern.fm/forum/index.php?topic=19417.0>`_
alex@thinkpad's avatar
alex@thinkpad committed
1116
is a bit more time-consuming, but it's not difficult.
alex@thinkpad's avatar
alex@thinkpad committed
1117

1118
1119
Are there any good docs on QEMU internals?
``````````````````````````````````````````
alex@thinkpad's avatar
alex@thinkpad committed
1120
1121
1122
1123
1124
1125

- http://nairobi-embedded.org/category/qemu.html
- http://blog.vmsplice.net
- QEMU mailing list (huge!)
- Xilinx QEMU

alex@thinkpad's avatar
alex@thinkpad committed
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
DryOS internals?
````````````````

This is the perfect tool for studying them. Start at:

- DryOS shell (View -> Serial in menu, then type ``akashimorino``)
- task_create (from GDB scripts)
- semaphores (some GDB scripts have them)
- message queues (some GDB scripts have them)
- heartbeat timer (dryos_timer_id/interrupt in `model_list.c <https://bitbucket.org/hudson/magic-lantern/src/qemu/contrib/qemu/eos/model_list.c>`_)
- interrupt handler (follow the code at 0x18)
- to debug: ``-d io,int`` is very helpful (although a bit too verbose)

alex@thinkpad's avatar
alex@thinkpad committed
1139
1140
|

1141
1142
1143
1144
.. image:: doc/img/drysh.png
   :scale: 50 %
   :align: center

alex@thinkpad's avatar
alex@thinkpad committed
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
Cross-checking the emulation with actual hardware
`````````````````````````````````````````````````

- dm-spy-experiments branch
- CONFIG_DEBUG_INTERCEPT_STARTUP=y
- run the same build on both camera and QEMU
- compare the logs (sorry, no good tool for this)
- add extra hooks as desired (dm-spy-extra.c)
- caveat: the order of execution is not deterministic.

Checking MMIO values from actual hardware
'''''''''''''''''''''''''''''''''''''''''

See `this commit <https://bitbucket.org/hudson/magic-lantern/commits/726806f3bc352c41bbd72bf40fdbab3c7245039d>`_.

Checking interrupts from actual hardware
''''''''''''''''''''''''''''''''''''''''

LOG_INTERRUPTS in dm-spy-experiments.

alex@thinkpad's avatar
alex@thinkpad committed
1165
MPU spells
alex@thinkpad's avatar
alex@thinkpad committed
1166
''''''''''
alex@thinkpad's avatar
alex@thinkpad committed
1167

alex@thinkpad's avatar
alex@thinkpad committed
1168
`mpu_send/recv <http://www.magiclantern.fm/forum/index.php?topic=2864.msg166938#msg166938>`_ in dm-spy-experiments.
alex@thinkpad's avatar
alex@thinkpad committed
1169
1170
1171
1172
1173
1174
1175
1176
1177

Committing your changes
```````````````````````

After editing the sources outside the magic-lantern directory, 
first make sure you are on the ``qemu`` branch:

.. code:: shell

alex@thinkpad's avatar
alex@thinkpad committed
1178
  # from the magic-lantern directory
alex@thinkpad's avatar
alex@thinkpad committed
1179
1180
  hg up qemu -C

1181
Then copy your changes back into the ML tree:
alex@thinkpad's avatar
alex@thinkpad committed
1182
1183
1184

.. code:: shell

alex@thinkpad's avatar
alex@thinkpad committed
1185
  # from the qemu directory
alex@thinkpad's avatar
alex@thinkpad committed
1186
1187
1188
1189
1190
1191
1192
  ./copy_back_to_contrib.sh

Then commit as usual, from the ``contrib/qemu`` directory.

Reverting your changes
``````````````````````

1193
1194
If you want to go back to an older changeset, or just undo any changes you
made outside the magic-lantern directory, you may run the install script
alex@thinkpad's avatar
alex@thinkpad committed
1195
1196
1197
1198
again. It will not re-download QEMU, but unfortunately you will have to
recompile QEMU from scratch (which is very slow).

If you have changed only the ``eos`` files, to avoid a full recompilation
1199
you may try a script similar to the following:
alex@thinkpad's avatar
alex@thinkpad committed
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218

.. code:: shell

    #!/bin/bash
    
    QEMU_PATH=${QEMU_PATH:=qemu-2.5.0}
    ML=${ML:=magic-lantern}
    
    cp -v ../$ML/contrib/qemu/eos/* $QEMU_PATH/hw/eos/
    cp -v ../$ML/contrib/qemu/eos/mpu_spells/* $QEMU_PATH/hw/eos/mpu_spells/
    cp -v ../$ML/contrib/qemu/eos/dbi/* $QEMU_PATH/hw/eos/dbi/
    cp -v ../$ML/src/backtrace.[ch] $QEMU_PATH/hw/eos/dbi/
    cp -vr ../$ML/contrib/qemu/tests/* tests/
    cp -vr ../magic-lantern/contrib/qemu/scripts/* .


Test suite
``````````

alex@thinkpad's avatar
alex@thinkpad committed
1219
Most Canon cameras are very similar inside - which is why one is able to run the same codebase
alex@thinkpad's avatar
alex@thinkpad committed
1220
1221
from DIGIC 2 (original 5D) all the way to DIGIC 5 (and soon 6) - yet, every camera model has its own quirks
(not only on the firmware, but also on the hardware side). Therefore, it's hard to predict whether a tiny change in the emulation, to fix a quirk for camera model X,
alex@thinkpad's avatar
alex@thinkpad committed
1222
will have a positive or negative or neutral impact on camera model Y. The test suite tries to answer this,
alex@thinkpad's avatar
alex@thinkpad committed
1223
1224
1225
1226
1227
1228
1229
1230
and covers the following:

- Bootloader code (to make sure AUTOEXEC.BIN is loaded from the card)
- Portable display test (all EOS models)
- Portable ROM dumper (EOS models with bootloader file write routines)
- Menu navigation (on supported models) - depends on user settings from the ROM
- Card formatting (and restoring ML)
- Call/return trace until booting the GUI (a rigid test that may have to be updated frequently)
1231
- Call/return trace on bootloader (likely independent of firmware version and user settings)
alex@thinkpad's avatar
alex@thinkpad committed
1232
1233
1234
1235
- Callstack consistency with call/return trace (at every DebugMsg call)
- File I/O (whether the firmware creates a DCIM directory on startup)
- FA_CaptureTestImage (basic image capture process, without compression or CR2 output)
- HPTimer (difficult to get right)
alex@thinkpad's avatar
alex@thinkpad committed
1236
- DryOS task information (current_task, current_interrupt)
alex@thinkpad's avatar
alex@thinkpad committed
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
- GDB scripts (just a few basics)
- DryOS shell (UART)
- PowerShot models (limited tests)
- Secondary DryOS cores (limited tests)

Limitations:

- The tests are tied to our copies of the ROMs (which also store various user settings);
  unfortunately, these ROMs are not public (see `ML FAQ <http://wiki.magiclantern.fm/faq>`_).
  
  Workarounds:
  
  - run the test suite for your camera model(s) only, e.g. ``./run_tests.sh 5D3 60D 70D``
alex@thinkpad's avatar
alex@thinkpad committed
1250
1251
1252
  - inspect the test results (e.g. screenshots) manually, and compare them to
    `our results from Jenkins <https://builds.magiclantern.fm/jenkins/view/QEMU/job/QEMU-tests/>`_
    to decide whether they are correct or not
alex@thinkpad's avatar
alex@thinkpad committed
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
  - if you have made changes to the emulation, just ask us to test them.

  Saving the ROM right after clearing camera settings may or may not give repeatable results (not tested).

- The test suite is very slow (30-60 minutes, even on decent hardware)

  Workarounds:

  - run the test suite for a small number of camera model(s): ``./run_tests.sh 5D3 60D 70D``
  - run only the test(s) you are interested in (add ``if false; then`` ... ``fi`` in the source)
  - leave the tests running overnight.

1265
  If you have any ideas on how to improve the tests, we are listening.
alex@thinkpad's avatar
alex@thinkpad committed
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303

To avoid committing (large) reference screenshots or log files,
a lot of expected test results are stored as MD5 sums. That's a bit rigid,
but it does the job for now. Where appropriate, we also have grep-based
tests or custom logic on log files.

The expected test results ("needles") are updated manually
(e.g. ``md5sum disp.ppm > disp.md5``). Suggestions welcome.

Code coverage?
``````````````

`Yes <https://builds.magiclantern.fm/jenkins/view/QEMU/job/QEMU-coverage/>`_.

History
-------

:2008: `SD1100 boot (CHDK) <http://chdk.wikia.com/wiki/GPL_Qemu>`_
:2009: `5D2/7D boot (Trammell) <http://magiclantern.wikia.com/wiki/Emulation>`_
:2012: `TriX_EOS (g3gg0) <http://www.magiclantern.fm/forum/index.php?topic=2882.0>`_
:2013: `Initial Hello World <http://www.magiclantern.fm/forum/index.php?topic=2864.msg26022#msg26022>`_
:2013: `g3gg0 ports TriX changes to QEMU <http://www.magiclantern.fm/forum/index.php?topic=2864.msg29748#msg29748>`_
:2013: `Antony Pavlov submits initial DIGIC support to QEMU mainline <https://lists.gnu.org/archive/html/qemu-devel/2013-08/msg04509.html>`_
:2013: `Nikon Hacker is light years ahead us <http://www.magiclantern.fm/forum/index.php?topic=8823.0>`_ (we are not competing; it was just a fun notice that motivated us)
:2014: `DryOS task scheduler running! <http://www.magiclantern.fm/forum/index.php?topic=2864.msg117430#msg117430>`_ (also ML menu and modules, but with massive hacks - emulating only a very small part of Canon firmware)
:2015: `Portable display test and Linux PoC working! <http://www.magiclantern.fm/forum/index.php?topic=2864.msg144760#msg144760>`_
:2015: `Canon GUI boots on 60D! <http://www.magiclantern.fm/forum/index.php?topic=2864.msg148240#msg148240>`_ (no menus yet, but most Canon tasks are working!)
:2015: `100D emulation, serial flash and GDB scripts from nkls <http://www.magiclantern.fm/forum/index.php?topic=2864.msg153064#msg153064>`_
:2016: `More EOS models boot Canon GUI (no menus yet) <http://www.magiclantern.fm/forum/index.php?topic=2864.msg168603#msg168603>`_
:2016: `Low-level button codes and GUI modes understood <http://www.magiclantern.fm/forum/index.php?topic=2864.msg169517#msg169517>`_
:2016: `Users start wondering why the heck are we spending most of our time on this <http://www.magiclantern.fm/forum/index.php?topic=2864.msg169970#msg169970>`_
:2016: `Leegong from Nikon Hacker starts documenting MPU messages <http://www.magiclantern.fm/forum/index.php?topic=17596.msg171304#msg171304>`_
:2017: `500D menu navigation! (Greg) <http://www.magiclantern.fm/forum/index.php?topic=2864.msg179867#msg179867>`_
:2017: `nkls solves an important issue that was very hard to track down! <http://www.magiclantern.fm/forum/index.php?topic=2864.msg183311#msg183311>`_
:2017: `Menu navigation works on most D4 and 5 models <http://www.magiclantern.fm/forum/index.php?topic=2864.msg181786#msg181786>`_
:2017:  Working on `Mac (dfort) <http://www.magiclantern.fm/forum/index.php?topic=2864.msg184981#msg184981>`_ 
        and `Windows 10 / Linux subsystem (g3gg0) <http://www.magiclantern.fm/forum/index.php?topic=20214.0>`_
:2017: `EOS M2 porting walkthrough <http://www.magiclantern.fm/forum/index.php?topic=15895.msg185103#msg185103>`_
alex@thinkpad's avatar
alex@thinkpad committed
1304
:2017: `Automated tests for ML builds in QEMU <http://www.magiclantern.fm/forum/index.php?topic=20560>`_
alex@thinkpad's avatar
alex@thinkpad committed
1305
1306
1307
1308



Happy hacking!