Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / native_client_sdk / src / doc / devguide / devcycle / debugging.rst
1 .. _devcycle-debugging:
2
3 #########
4 Debugging
5 #########
6
7 This document describes tools and techniques you can use to debug, monitor,
8 and measure your application's performance.
9
10 .. contents:: Table Of Contents
11   :local:
12   :backlinks: none
13   :depth: 3
14
15 Diagnostic information
16 ======================
17
18 Viewing process statistics with the task manager
19 ------------------------------------------------
20
21 You can use Chrome's Task Manager to display information about a Native Client
22 application:
23
24 #. Open the Task Manager by clicking the menu icon |menu-icon| and choosing
25    **Tools > Task manager**.
26 #. When the Task Manager window appears, verify that the columns displaying
27    memory information are visible. If they are not, right click in the header
28    row and select the memory items from the popup menu that appears.
29
30 A browser window running a Native Client application has at least two processes
31 associated with it: a process for the app's top level (the render process
32 managing the page including its HTML and JavaScript) and one or more
33 processes for each instance of a Native Client module embedded in the page
34 (each process running native code from one nexe or pexe file). The top-level
35 process appears with the application's icon and begins with the text "Tab:". 
36 A Native Client process appears with a Chrome extension icon (a jigsaw puzzle
37 piece |puzzle|) and begins with the text "Native Client module:" followed by the
38 URL of its manifest file.
39
40 From the Task Manager you can view the changing memory allocations of all the
41 processes associated with a Native Client application. Each process has its own
42 memory footprint. You can also see the rendering rate displayed as frames per
43 second (FPS). Note that the computation of render frames can be performed in
44 any process, but the rendering itself is always done in the top level
45 application process, so look for the rendering rate there.
46
47 Controlling the level of Native Client error and warning messages
48 -----------------------------------------------------------------
49
50 Native Client prints warning and error messages to stdout and stderr. You can
51 increase the amount of Native Client's diagnostic output by setting the
52 following `environment variables
53 <http://en.wikipedia.org/wiki/Environment_variable>`_:
54
55 * ``NACL_PLUGIN_DEBUG=1``
56 * ``NACL_SRPC_DEBUG=[1-255]`` (use a higher number for more verbose debug
57   output)
58 * ``NACLVERBOSITY=[1-255]``
59
60 Basic debugging
61 ===============
62
63 Writing messages to the JavaScript console
64 ------------------------------------------
65
66 You can send messages from your C/C++ code to JavaScript using the 
67 ``PostMessage()`` call in the :doc:`Pepper messaging system 
68 <../coding/message-system>`. When the JavaScript code receives a message, its 
69 message event handler can call `console.log() 
70 <https://developer.mozilla.org/en/DOM/console.log>`_ to write the message to the
71 JavaScript `console </devtools/docs/console-api>`_ in Chrome's Developer Tools.
72
73 Debugging with printf
74 ---------------------
75
76 Your C/C++ code can perform inline printf debugging to stdout and stderr by
77 calling fprintf() directly, or by using cover functions like these:
78
79 .. naclcode::
80
81   #include <stdio.h>
82   void logmsg(const char* pMsg){
83     fprintf(stdout,"logmsg: %s\n",pMsg);
84   }
85   void errormsg(const char* pMsg){
86     fprintf(stderr,"logerr: %s\n",pMsg);
87   }
88
89 .. _using-chromes-stdout-and-stderr:
90
91 Using Chrome's stdout and stderr Streams
92 ----------------------------------------
93
94 By default stdout and stderr will appear in Chrome's stdout and stderr stream
95 but they can also be redirected to log files. (See the next section.) On Mac and
96 Linux, launching Chrome from a terminal makes stderr and stdout appear in that
97 terminal. If you launch Chrome this way, be sure it doesn't attach to an existing
98 instance. One simple way to do this is to pass a new directory to chrome as your
99 user data directory (``chrome --user-data-dir=<newdir>``). 
100
101 .. _redirecting-output-to-log:
102
103 Redirecting output to log files
104 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
105
106 You can redirect stdout and stderr to output files by setting these environment
107 variables:
108
109 * ``NACL_EXE_STDOUT=c:\nacl_stdout.log``
110 * ``NACL_EXE_STDERR=c:\nacl_stderr.log``
111
112 There is another variable, ``NACLLOG``, that you can use to redirect Native
113 Client's internally-generated messages. This variable is set to stderr by
114 default; you can redirect these messages to an output file by setting the
115 variable as follows:
116
117 * ``NACLLOG=c:\nacl.log``
118
119 .. Note::
120   :class: note
121
122   **Note:** If you set the ``NACL_EXE_STDOUT``, ``NACL_EXE_STDERR``, or
123   ``NACLLOG`` variables to redirect output to a file, you must run Chrome with
124   the ``--no-sandbox`` flag.  You must also be careful that each variable points
125   to a different file.
126
127 Logging calls to Pepper interfaces
128 ----------------------------------
129
130 You can log all Pepper calls your module makes by passing the following flags
131 to Chrome on startup::
132
133   --vmodule=ppb*=4 --enable-logging=stderr
134
135
136 The ``vmodule`` flag tells Chrome to log all calls to C Pepper interfaces that
137 begin with "ppb" (that is, the interfaces that are implemented by the browser
138 and that your module calls). The ``enable-logging`` flag tells Chrome to log
139 the calls to stderr.
140
141 .. _visual_studio:
142
143 Debugging with Visual Studio
144 ----------------------------
145
146 If you develop on a Windows platform you can use the :doc:`Native Client Visual
147 Studio add-in <vs-addin>` to write and debug your code. The add-in defines new
148 project platforms that let you run your module in two different modes: As a
149 Pepper plugin and as a Native Client module. When running as a Pepper plugin
150 you can use the built-in Visual Studio debugger. When running as a Native
151 Client module Visual Studio will launch an instance of nacl-gdb for you and
152 link it to the running code.
153
154 .. _using_gdb:
155
156 Debugging with nacl-gdb
157 -----------------------
158
159 The Native Client SDK includes a command-line debugger that you can use to
160 debug Native Client modules. The debugger is based on the GNU debugger `gdb
161 <http://www.gnu.org/software/gdb/>`_, and is located at
162 ``pepper_<version>/toolchain/<platform>_x86_newlib/bin/x86_64-nacl-gdb`` (where
163 *<platform>* is the platform of your development machine: ``win``, ``mac``, or
164 ``linux``).
165
166 Note that this same copy of GDB can be used to debug any NaCl program,
167 whether built using newlib or glibc for x86-32, x86-64 or ARM.  In the SDK,
168 ``i686-nacl-gdb`` is an alias for ``x86_64-nacl-gdb``, and the ``newlib``
169 and ``glibc`` toolchains both contain the same version of GDB.
170
171 .. _debugging_pnacl_pexes:
172
173 Debugging PNaCl pexes (Pepper 35 or later)
174 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
175
176 If you want to use GDB to debug a program that is compiled with the PNaCl
177 toolchain, you must have a copy of the pexe from **before** running
178 ``pnacl-finalize``. The ``pnacl-finalize`` tool converts LLVM bitcode
179 to the stable PNaCl bitcode format, but it also strips out debug
180 metadata, which we need for debugging. In this section we'll give the
181 LLVM bitcode file a ``.bc`` file extension, and the PNaCl bitcode file
182 a ``.pexe`` file extension. The actual extension should not matter, but
183 it helps distinguish between the two types of files.
184
185 **Note** unlike the finalized copy of the pexe, the non-finalized debug copy
186 is not considered stable. This means that a debug copy of the PNaCl
187 application created by a Pepper N SDK is only guaranteed to run
188 with a matching Chrome version N. If the version of the debug bitcode pexe
189 does not match that of Chrome then the translation process may fail, and
190 you will see an error message in the JavaScript console.
191
192 Also, make sure you are passing the ``-g`` :ref:`compile option <compile_flags>`
193 to ``pnacl-clang`` to enable generating debugging info.  You might also want to
194 omit ``-O2`` from the compile-time and link-time options, otherwise GDB not
195 might be able to print variables' values when debugging (this is more of a
196 problem with the PNaCl/LLVM toolchain than with GCC).
197
198 Once you have built a non-stable debug copy of the pexe, list the URL of
199 that copy in your application's manifest file:
200
201 .. naclcode::
202
203   {
204     "program": {
205       "portable": {
206         "pnacl-translate": {
207           "url": "release_version.pexe",
208           "optlevel": 2
209         },
210         "pnacl-debug": {
211           "url": "debug_version.bc",
212           "optlevel": 0
213         }
214       }
215     }
216   }
217
218 Copy the ``debug_version.bc`` and ``nmf`` files to the location that
219 your local web server serves files from.
220
221 When you run Chrome with ``--enable-nacl-debug``, Chrome will translate
222 and run the ``debug_version.bc`` instead of ``release_version.pexe``.
223 Once the debug version is loaded, you are ready to :ref:`run nacl-gdb
224 <running_nacl_gdb>`
225
226 Whether you publish the NMF file containing the debug URL to the
227 release web server, is up to you. One reason to avoid publishing the
228 debug URL is that it is only guaranteed to work for the Chrome version
229 that matches the SDK version. Developers who may have left the
230 ``--enable-nacl-debug`` flag turned on may end up loading the debug
231 copy of your application (which may or may not work, depending on
232 their version of Chrome).
233
234
235 Debugging PNaCl pexes (with older Pepper toolchains)
236 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
237
238 If you want to use GDB to debug a program that is compiled with the PNaCl
239 toolchain, you must convert the ``pexe`` file to a ``nexe``.  (You can skip
240 this step if you are using the GCC toolchain, or if you are using
241 pepper 35 or later.)
242
243 * Firstly, make sure you are passing the ``-g`` :ref:`compile option
244   <compile_flags>` to ``pnacl-clang`` to enable generating debugging info.
245   You might also want to omit ``-O2`` from the compile-time and link-time
246   options.
247
248 * Secondly, use ``pnacl-translate`` to convert your ``pexe`` to one or more
249
250   ``nexe`` files.  For example:
251
252   .. naclcode::
253     :prettyprint: 0
254
255     nacl_sdk/pepper_<version>/toolchain/win_pnacl/bin/pnacl-translate \
256       --allow-llvm-bitcode-input hello_world.pexe -arch x86-32 \
257       -o hello_world_x86_32.nexe
258     nacl_sdk/pepper_<version>/toolchain/win_pnacl/bin/pnacl-translate \
259       --allow-llvm-bitcode-input hello_world.pexe -arch x86-64 \
260       -o hello_world_x86_64.nexe
261
262   For this, use the non-finalized ``pexe`` file produced by
263   ``pnacl-clang``, not the ``pexe`` file produced by ``pnacl-finalize``.
264   The latter ``pexe`` has debugging info stripped out.  The option
265   ``--allow-llvm-bitcode-input`` tells ``pnacl-translate`` to accept a
266   non-finalized ``pexe``.
267
268 * Replace the ``nmf`` :ref:`manifest file <manifest_file>` that points to
269   your ``pexe`` file with one that points to the ``nexe`` files.  For the
270   example ``nexe`` filenames above, the new ``nmf`` file would contain:
271
272   .. naclcode::
273     :prettyprint: 0
274
275     {
276       "program": {
277         "x86-32": {"url": "hello_world_x86_32.nexe"},
278         "x86-64": {"url": "hello_world_x86_64.nexe"},
279       }
280     }
281
282 * Change the ``<embed>`` HTML element to use
283   ``type="application/x-nacl"`` rather than
284   ``type="application/x-pnacl"``.
285
286 * Copy the ``nexe`` and ``nmf`` files to the location that your local web
287   server serves files from.
288
289 .. Note::
290   :class: note
291
292   **Note:** If you know whether Chrome is using the x86-32 or x86-64
293   version of the NaCl sandbox on your system, you can translate the
294   ``pexe`` once to a single x86-32 or x86-64 ``nexe``.  Otherwise, you
295   might find it easier to translate the ``pexe`` to both ``nexe``
296   formats as described above.
297
298 .. _running_nacl_gdb:
299
300 Running nacl-gdb
301 ~~~~~~~~~~~~~~~~
302
303 Before you start using nacl-gdb, make sure you can :doc:`build <building>` your
304 module and :doc:`run <running>` your application normally. This will verify
305 that you have created all the required :doc:`application parts
306 <../coding/application-structure>` (.html, .nmf, and .nexe files, shared
307 libraries, etc.), that your server can access those resources, and that you've
308 configured Chrome correctly to run your application.  The instructions below
309 assume that you are using a :ref:`local server <web_server>` to run your
310 application; one benefit of doing it this way is that you can check the web
311 server output to confirm that your application is loading the correct
312 resources. However, some people prefer to run their application as an unpacked
313 extension, as described in :doc:`Running Native Client Applications <running>`.
314
315 Follow the instructions below to debug your module with nacl-gdb:
316
317 #. Compile your module with the ``-g`` flag so that your .nexe retains symbols
318    and other debugging information (see the :ref:`recommended compile flags
319    <compile_flags>`).
320 #. Launch a local web server (e.g., the :ref:`web server <web_server>` included
321    in the SDK).
322 #. Launch Chrome with these three required flags: ``--enable-nacl --enable-nacl-debug --no-sandbox``.
323
324    You may also want to use some of the optional flags listed below. A typical
325    command looks like this::
326
327      chrome --enable-nacl --enable-nacl-debug --no-sandbox --disable-hang-monitor localhost:5103
328
329    **Required flags:**
330
331    ``--enable-nacl``
332      Enables Native Client for all applications, including those that are
333      launched outside the Chrome Web Store.
334
335    ``--enable-nacl-debug``
336      Turns on the Native Client debug stub, opens TCP port 4014, and pauses
337      Chrome to let the debugger connect.
338
339    ``--no-sandbox``
340      Turns off the Chrome sandbox (not the Native Client sandbox). This enables
341      the stdout and stderr streams, and lets the debugger connect.
342
343    **Optional flags:**
344
345    ``--disable-hang-monitor``
346      Prevents Chrome from displaying a warning when a tab is unresponsive.
347
348    ``--user-data-dir=<directory>``
349      Specifies the `user data directory
350      <http://www.chromium.org/user-experience/user-data-directory>`_ from which
351      Chrome should load its state.  You can specify a different user data
352      directory so that changes you make to Chrome in your debugging session do
353      not affect your personal Chrome data (history, cookies, bookmarks, themes,
354      and settings).
355
356    ``--nacl-debug-mask=<nmf_url_mask1,nmf_url_mask2,...>``
357      Specifies a set of debug mask patterns. This allows you to selectively
358      choose to debug certain applications and not debug others. For example, if
359      you only want to debug the NMF files for your applications at
360      ``https://example.com/app``, and no other NaCl applications found on the
361      web, specify ``--nacl-debug-mask=https://example.com/app/*.nmf``.  This
362      helps prevent accidentally debugging other NaCl applications if you like
363      to leave the ``--enable-nacl-debug`` flag turned on.  The pattern language
364      for the mask follows `chrome extension match patterns
365      </extensions/match_patterns>`_.  The pattern set can be inverted by
366      prefixing the pattern set with the ``!`` character.
367
368    ``<URL>``
369      Specifies the URL Chrome should open when it launches. The local server
370      that comes with the SDK listens on port 5103 by default, so the URL when
371      you're debugging is typically ``localhost:5103`` (assuming that your
372      application's page is called index.html and that you run the local server
373      in the directory where that page is located).
374
375 #. Navigate to your application's page in Chrome. (You don't need to do this if
376    you specified a URL when you launched Chrome in the previous step.) Chrome
377    will start loading the application, then pause and wait until you start
378    nacl-gdb and run the ``continue`` command.
379
380 #. Go to the directory with your source code, and run nacl-gdb from there. For
381    example::
382
383      cd nacl_sdk/pepper_<version>/examples/demo/drive
384      nacl_sdk/pepper_<version>/toolchain/win_x86_newlib/bin/x86_64-nacl-gdb
385
386    The debugger will start and show you a gdb prompt::
387
388      (gdb)
389
390 #. Run the debugging command lines.
391
392    **For PNaCl**::
393    
394      (gdb) target remote localhost:4014
395      (gdb) remote get nexe <path-to-save-translated-nexe-with-debug-info>
396      (gdb) file <path-to-save-translated-nexe-with-debug-info>
397      (gdb) remote get irt <path-to-save-NaCl-integrated-runtime>
398      (gdb) nacl-irt <path-to-saved-NaCl-integrated-runtime>
399
400    **For NaCl**::
401    
402      (gdb) target remote localhost:4014
403      (gdb) nacl-manifest <path-to-your-.nmf-file>
404      (gdb) remote get irt <path-to-save-NaCl-integrated-runtime>
405      (gdb) nacl-irt <path-to-saved-NaCl-integrated-runtime>
406
407 #. The command used for PNaCl and NaCl are described below:
408
409    ``target remote localhost:4014``
410      Tells the debugger how to connect to the debug stub in the Native Client
411      application loader. This connection occurs through TCP port 4014 (note
412      that this port is distinct from the port which the local web server uses
413      to listen for incoming requests, typically port 5103). If you are
414      debugging multiple applications at the same time, the loader may choose
415      a port that is different from the default 4014 port. See the Chrome
416      task manager for the debug port.
417
418    ``remote get nexe <path>``
419      This saves the application's main executable (nexe) to ``<path>``.
420      For PNaCl, this provides a convenient way to access the nexe that is
421      a **result** of translating your pexe. This can then be loaded with
422      the ``file <path>`` command.
423
424    ``nacl-manifest <path>``
425      For NaCl (not PNaCl), this tells the debugger where to find your
426      application's executable (.nexe) files. The application's manifest
427      (.nmf) file lists your application's executable files, as well as any
428      libraries that are linked with the application dynamically.
429
430    ``remote get irt <path>``
431      This saves the Native Client Integrated Runtime (IRT). Normally,
432      the IRT is located in the same directory as the Chrome executable,
433      or in a subdirectory named after the Chrome version. For example, if
434      you're running Chrome canary on Windows, the path to the IRT typically
435      looks something like ``C:/Users/<username>/AppData/Local/Google/Chrome
436      SxS/Application/23.0.1247.1/nacl_irt_x86_64.nexe``.
437      The ``remote get irt <path>`` saves that to the current working
438      directory so that you do not need to find where exactly the IRT
439      is stored.
440
441    ``nacl-irt <path>``
442      Tells the debugger where to find the Native Client Integrated Runtime
443      (IRT). ``<path>`` can either be the location of the copy saved by
444      ``remote get irt <path>`` or the copy that is installed alongside Chrome.
445
446    A couple of notes on how to specify path names in the nacl-gdb commands
447    above:
448
449    * You can use a forward slash to separate directories on Linux, Mac, and
450      Windows. If you use a backslash to separate directories on Windows, you
451      must escape the backslash by using a double backslash "\\" between
452      directories.
453    * If any directories in the path have spaces in their name, you must put
454      quotation marks around the path.
455
456    As an example, here is a what these nacl-gdb commands might look like on
457    Windows::
458
459      target remote localhost:4014
460      nacl-manifest "C:/nacl_sdk/pepper_<version>/examples/hello_world_gles/newlib/Debug/hello_world_gles.nmf"
461      nacl-irt "C:/Users/<username>/AppData/Local/Google/Chrome SxS/Application/23.0.1247.1/nacl_irt_x86_64.nexe"
462
463    To save yourself some typing, you can put put these nacl-gdb commands in a
464    script file, and execute the file when you run nacl-gdb, like so::
465
466      nacl_sdk/pepper_<version>/toolchain/win_x86_newlib/bin/x86_64-nacl-gdb -x <nacl-script-file>
467
468    If nacl-gdb connects successfully to Chrome, it displays a message such as
469    the one below, followed by a gdb prompt::
470
471      0x000000000fc00200 in _start ()
472      (gdb)
473
474    If nacl-gdb can't connect to Chrome, it displays a message such as
475    "``localhost:4014: A connection attempt failed``" or "``localhost:4014:
476    Connection timed out.``" If you see a message like that, make sure that you
477    have launched a web server, launched Chrome, and navigated to your
478    application's page before starting nacl-gdb.
479
480 Once nacl-gdb connects to Chrome, you can run standard gdb commands to execute
481 your module and inspect its state. Some commonly used commands are listed
482 below.
483
484 ``break <location>``
485   set a breakpoint at <location>, e.g.::
486
487     break hello_world.cc:79
488     break hello_world::HelloWorldInstance::HandleMessage
489     break Render
490
491 ``continue``
492   resume normal execution of the program
493
494 ``next``
495   execute the next source line, stepping over functions
496
497 ``step``
498   execute the next source line, stepping into functions
499
500 ``print <expression>``
501   print the value of <expression> (e.g., variables)
502
503 ``backtrace``
504   print a stack backtrace
505
506 ``info breakpoints``
507   print a table of all breakpoints
508
509 ``delete <breakpoint>``
510   delete the specified breakpoint (you can use the breakpoint number displayed
511   by the info command)
512
513 ``help <command>``
514   print documentation for the specified gdb <command>
515
516 ``quit``
517   quit gdb
518
519 See the `gdb documentation
520 <http://sourceware.org/gdb/current/onlinedocs/gdb/#toc_Top>`_ for a
521 comprehensive list of gdb commands. Note that you can abbreviate most commands
522 to just their first letter (``b`` for break, ``c`` for continue, and so on).
523
524 To interrupt execution of your module, press <Ctrl-c>. When you're done
525 debugging, close the Chrome window and type ``q`` to quit gdb.
526
527 Debugging with other tools
528 ==========================
529
530 If you cannot use the :ref:`Visual Studio add-in <visual_studio>`, or you want
531 to use a debugger other than nacl-gdb, you must manually build your module as a
532 Pepper plugin (sometimes referred to as a "`trusted
533 <http://www.chromium.org/nativeclient/getting-started/getting-started-background-and-basics#TOC-Trusted-vs-Untrusted>`_"
534 or "in-process" plugin).  Pepper plugins (.DLL files on Windows; .so files on
535 Linux; .bundle files on Mac) are loaded directly in either the Chrome renderer
536 process or a separate plugin process, rather than in Native Client. Building a
537 module as a trusted Pepper plugin allows you to use standard debuggers and
538 development tools on your system, but when you're finished developing the
539 plugin, you need to port it to Native Client (i.e., build the module with one of
540 the toolchains in the NaCl SDK so that the module runs in Native Client).  For
541 details on this advanced development technique, see `Debugging a Trusted Plugin
542 <http://www.chromium.org/nativeclient/how-tos/debugging-documentation/debugging-a-trusted-plugin>`_.
543 Note that starting with the ``pepper_22`` bundle, the NaCl SDK for Windows
544 includes pre-built libraries and library source code, making it much easier to
545 build a module into a .DLL.
546
547 .. |menu-icon| image:: /images/menu-icon.png
548 .. |puzzle| image:: /images/puzzle.png