Debian Codegraph @

gcc/ada/doc/gnat_ugn/platform_specific_information.rst

raw
1 .. role:: switch(samp)
2
3 .. -- Non-breaking space in running text
4 -- E.g. Ada |nbsp| 95
5
6 .. |nbsp| unicode:: 0xA0
7 :trim:
8
9 .. _Platform_Specific_Information:
10
11 *****************************
12 Platform-Specific Information
13 *****************************
14
15 This appendix contains information relating to the implementation
16 of run-time libraries on various platforms. It also covers topics
17 related to the GNAT implementation on specific Operating Systems.
18
19 .. _`Run_Time_Libraries`:
20
21 Run-Time Libraries
22 ==================
23
24 .. index:: Tasking and threads libraries
25 .. index:: Threads libraries and tasking
26 .. index:: Run-time libraries (platform-specific information)
27
28 The GNAT run-time implementation may vary with respect to both the
29 underlying threads library and the exception-handling scheme.
30 For threads support, the default run-time will bind to the thread
31 package of the underlying operating system.
32
33 For exception handling, either or both of two models are supplied:
34
35 .. index:: Zero-Cost Exceptions
36 .. index:: ZCX (Zero-Cost Exceptions)
37
38 * **Zero-Cost Exceptions** ("ZCX"),
39 which uses binder-generated tables that
40 are interrogated at run time to locate a handler.
41
42 .. index:: setjmp/longjmp Exception Model
43 .. index:: SJLJ (setjmp/longjmp Exception Model)
44
45 * **setjmp / longjmp** ('SJLJ'),
46 which uses dynamically-set data to establish
47 the set of handlers
48
49 Most programs should experience a substantial speed improvement by
50 being compiled with a ZCX run-time.
51 This is especially true for
52 tasking applications or applications with many exception handlers.
53 Note however that the ZCX run-time does not support asynchronous abort
54 of tasks (``abort`` and ``select-then-abort`` constructs) and will instead
55 implement abort by polling points in the runtime. You can also add additional
56 polling points explicitly if needed in your application via ``pragma
57 Abort_Defer``.
58
59 This section summarizes which combinations of threads and exception support
60 are supplied on various GNAT platforms.
61
62 .. _Summary_of_Run-Time_Configurations:
63
64 Summary of Run-Time Configurations
65 ----------------------------------
66
67 +-----------------+--------------+-------------------------+------------+
68 | Platform | Run-Time | Tasking | Exceptions |
69 +=================+==============+=========================+============+
70 | GNU/Linux | rts-native | pthread library | ZCX |
71 | | (default) | | |
72 | +--------------+-------------------------+------------+
73 | | rts-sjlj | pthread library | SJLJ |
74 +-----------------+--------------+-------------------------+------------+
75 | Windows | rts-native | native Win32 threads | ZCX |
76 | | (default) | | |
77 | +--------------+-------------------------+------------+
78 | | rts-sjlj | native Win32 threads | SJLJ |
79 +-----------------+--------------+-------------------------+------------+
80 | Mac OS | rts-native | pthread library | ZCX |
81 +-----------------+--------------+-------------------------+------------+
82
83
84 .. _Specifying_a_Run-Time_Library:
85
86 Specifying a Run-Time Library
87 =============================
88
89 The :file:`adainclude` subdirectory containing the sources of the GNAT
90 run-time library and the :file:`adalib` subdirectory containing the
91 :file:`ALI` files and the static and/or shared GNAT library are located
92 in the gcc target-dependent area:
93
94
95 ::
96
97 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
98
99 As indicated above, on some platforms, several run-time libraries are supplied.
100 These libraries are installed in the target dependent area and
101 contain a complete source and binary subdirectory. The detailed description
102 below explains the differences between the different libraries in terms of
103 their thread support.
104
105 The default run-time library (when GNAT is installed) is *rts-native*.
106 This default run-time is selected by the means of soft links.
107 For example on x86-linux:
108
109 .. --
110 -- $(target-dir)
111 -- |
112 -- +--- adainclude----------+
113 -- | |
114 -- +--- adalib-----------+ |
115 -- | | |
116 -- +--- rts-native | |
117 -- | | | |
118 -- | +--- adainclude <---+
119 -- | | |
120 -- | +--- adalib <----+
121 -- |
122 -- +--- rts-sjlj
123 -- |
124 -- +--- adainclude
125 -- |
126 -- +--- adalib
127
128 .. only:: html or latex
129
130 .. image:: rtlibrary-structure.png
131
132 .. only:: not (html or latex)
133
134 ::
135
136 $(target-dir)
137 __/ / \ \___
138 _______/ / \ \_________________
139 / / \ \
140 / / \ \
141 ADAINCLUDE ADALIB rts-native rts-sjlj
142 : : / \ / \
143 : : / \ / \
144 : : / \ / \
145 : : / \ / \
146 +-------------> adainclude adalib adainclude adalib
147 : ^
148 : :
149 +---------------------+
150
151 Run-Time Library Directory Structure
152 (Upper-case names and dotted/dashed arrows represent soft links)
153
154 If you want to select the *rts-sjlj* library on a permanent basis,
155 you can modify these soft links with the following commands:
156
157 ::
158
159 $ cd $target
160 $ rm -f adainclude adalib
161 $ ln -s rts-sjlj/adainclude adainclude
162 $ ln -s rts-sjlj/adalib adalib
163
164 Alternatively, you can specify :file:`rts-sjlj/adainclude` in the file
165 :file:`$target/ada_source_path` and :file:`rts-sjlj/adalib` in
166 :file:`$target/ada_object_path`.
167
168 .. index:: --RTS switch
169
170 You can select another run-time library temporarily
171 by using the :switch:`--RTS` switch, e.g., :switch:`--RTS=sjlj`
172
173
174 .. index:: Linux
175 .. index:: GNU/Linux
176
177 .. _GNU_Linux_Topics:
178
179 GNU/Linux Topics
180 ================
181
182 This section describes topics that are specific to GNU/Linux platforms.
183
184 .. _Required_packages_on_GNU_Linux:
185
186 Required Packages on GNU/Linux
187 ------------------------------
188
189 GNAT requires the C library developer's package to be installed.
190 The name of of that package depends on your GNU/Linux distribution:
191
192 * RedHat, SUSE: ``glibc-devel``;
193 * Debian, Ubuntu: ``libc6-dev`` (normally installed by default).
194
195 If you're using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
196 you'll need the 32-bit version of the following packages:
197
198 * RedHat, SUSE: ``glibc.i686``, ``glibc-devel.i686``, ``ncurses-libs.i686``
199 * SUSE: ``glibc-locale-base-32bit``
200 * Debian, Ubuntu: ``libc6:i386``, ``libc6-dev:i386``, ``lib32ncursesw5``
201
202 Other GNU/Linux distributions might choose different name
203 for those packages.
204
205
206 .. _PIE_Enabled_By_Default_On_Linux:
207
208 Position Independent Executable (PIE) Enabled by Default on Linux
209 -----------------------------------------------------------------
210
211 GNAT generates Position Independent Executable (PIE) code by default.
212 PIE binaries are loaded into random memory locations, introducing
213 an additional layer of protection against attacks.
214
215 Building PIE binaries requires that all of their dependencies also be
216 built as Position Independent. If the link of your project fails with
217 an error like::
218
219 /[...]/ld: /path/to/object/file: relocation R_X86_64_32S against symbol
220 `symbol name' can not be used when making a PIE object;
221 recompile with -fPIE
222
223 it means the identified object file has not been built as Position
224 Independent.
225
226 If you are not interested in building PIE binaries, you can simply
227 turn this feature off by first compiling your code with :samp:`-fno-pie`
228 and then by linking with :samp:`-no-pie` (note the subtle but important
229 difference in the names of the switches -- the linker switch does **not**
230 have an `f` after the dash!). When using gprbuild, you do this
231 by updating the *Required_Switches* attribute in package `Compiler`
232 and, depending on your type of project, either attribute *Switches*
233 or attribute *Library_Options* in package `Linker`.
234
235 On the other hand, if you would like to build PIE binaries and you are
236 getting the error above, a quick and easy workaround to allow linking
237 to succeed again is to disable PIE during the link, thus temporarily
238 lifting the requirement that all dependencies also be Position
239 Independent code. To do so, you simply need to add :samp:`-no-pie` to
240 the list of switches passed to the linker. As part of this workaround,
241 there is no need to adjust the compiler switches.
242
243 From there, to be able to link your binaries with PIE and therefore
244 drop the :samp:`-no-pie` workaround, you'll need to get the identified
245 dependencies rebuilt with PIE enabled (compiled with :samp:`-fPIE`
246 and linked with :samp:`-pie`).
247
248 .. _Choosing_the_Scheduling_Policy_With_GNU_Linux:
249
250 .. index:: SCHED_FIFO scheduling policy
251 .. index:: SCHED_RR scheduling policy
252 .. index:: SCHED_OTHER scheduling policy
253
254 Choosing the Scheduling Policy with GNU/Linux
255 ---------------------------------------------
256
257 When using a POSIX threads implementation, you have a choice of several
258 scheduling policies: ``SCHED_FIFO``, ``SCHED_RR`` and ``SCHED_OTHER``.
259
260 Typically, the default is ``SCHED_OTHER``, while using ``SCHED_FIFO``
261 or ``SCHED_RR`` requires special (e.g., root) privileges.
262
263 .. index:: pragma Time_Slice
264 .. index:: -T0 switch
265 .. index:: pragma Task_Dispatching_Policy
266
267
268 By default, GNAT uses the ``SCHED_OTHER`` policy. To specify
269 ``SCHED_FIFO``,
270 you can use one of the following:
271
272 * ``pragma Time_Slice (0.0)``
273 * the corresponding binder switch :switch:`-T0`
274 * ``pragma Task_Dispatching_Policy (FIFO_Within_Priorities)``
275
276 To specify ``SCHED_RR``,
277 you should use ``pragma Time_Slice`` with a
278 value greater than 0.0, or else use the corresponding :switch:`-T`
279 binder switch.
280
281 To make sure a program is running as root, you can put something like
282 this in a library package body in your application:
283
284 .. code-block:: ada
285
286 function geteuid return Integer;
287 pragma Import (C, geteuid, "geteuid");
288 Ignore : constant Boolean :=
289 (if geteuid = 0 then True else raise Program_Error with "must be root");
290
291 This gets the effective user id and if it's not 0 (i.e. root), it raises
292 Program_Error. Note that if you're running the code in a container, this may
293 not be sufficient as you may have sufficient privilege on the container,
294 but not on the host machine running the container, so check that you also
295 have sufficient priviledge for running the container image.
296
297 .. _A_GNU_Linux_debug_quirk:
298
299 A GNU/Linux Debug Quirk
300 -----------------------
301
302 On SuSE 15, some kernels have a defect causing issues when debugging
303 programs using threads or Ada tasks. Due to the lack of documentation
304 found regarding this kernel issue, we can only provide limited
305 information about which kernels are impacted. Kernel version 5.3.18 is
306 known to be impacted and kernels in the 5.14 range or newer are
307 believed to fix this problem.
308
309 The bug affects the debugging of 32-bit processes on a 64-bit system.
310 Symptoms can vary: Unexpected ``SIGABRT`` signals being received by
311 the program, "The futex facility returned an unexpected error code"
312 error message, and inferior programs hanging indefinitely range among
313 the symptoms most commonly observed.
314
315 .. index:: Windows
316
317 .. _Microsoft_Windows_Topics:
318
319 Microsoft Windows Topics
320 ========================
321
322 This section describes topics that are specific to the Microsoft Windows
323 platforms.
324
325
326 .. only:: PRO
327
328 .. rubric:: Installing from the Command Line
329
330 By default the GNAT installers display a GUI that prompts you to enter
331 the installation path and similar information and then guides you through the
332 installation process. You can also perform silent installations
333 using the command-line interface.
334
335 To install one of the GNAT installers from the command
336 line, you should pass parameter :switch:`/S` (and, optionally,
337 :switch:`/D=<directory>`) as command-line arguments.
338
339 For example, for an unattended installation of
340 GNAT 19.2 into the default directory :file:`C:\\GNATPRO\\19.2` you
341 would run::
342
343 gnatpro-19.2-x86-windows-bin /S
344
345 To install into a custom directory, say, :file:`C:\\TOOLS\\GNATPRO\\19.2`::
346
347 gnatpro-19.2-x86-windows-bin /S /D=C:\TOOLS\GNATPRO\19.2
348
349 You can use the same syntax for all installers.
350
351 Note that unattended installations don't modify system path, nor create file
352 associations, so you need to do such activities by hand.
353
354
355 .. _Using_GNAT_on_Windows:
356
357 Using GNAT on Windows
358 ---------------------
359
360 One of the strengths of the GNAT technology is that its tool set
361 (``gcc``, ``gnatbind``, ``gnatlink``, ``gnatmake``, the
362 ``gdb`` debugger, etc.) is used in the same way regardless of the
363 platform.
364
365 On Windows, this tool set is complemented by a number of Microsoft-specific
366 tools that have been provided to facilitate interoperability with Windows
367 when this is required. With these tools:
368
369
370 * You can build applications using the ``CONSOLE`` or ``WINDOWS``
371 subsystems.
372
373 * You can use any Dynamically Linked Library (DLL) in your Ada code (both
374 relocatable and non-relocatable DLLs are supported).
375
376 * You can build Ada DLLs for use in other applications. You can write
377 these applications in a language other than Ada (e.g., C, C++,
378 etc). Again, both relocatable and non-relocatable Ada DLLs are
379 supported.
380
381 * You can include Windows resources in your Ada application.
382
383 * You can use or create COM/DCOM objects.
384
385 Listed immediately below are all known general GNAT-for-Windows
386 restrictions. We list other restrictions about specific features such
387 as Windows Resources and DLLs in separate sections below.
388
389 * You cannot use ``GetLastError`` and ``SetLastError``
390 when tasking, protected records, or exceptions are used. In these
391 cases, in order to implement Ada semantics, the GNAT run-time system
392 calls certain Win32 routines that set the last error variable to 0 upon
393 success. You may be able to use ``GetLastError`` and
394 ``SetLastError`` when tasking, protected record, and exception
395 features are not used, but it is not guaranteed to work.
396
397 * You cannot link against Microsoft C++ libraries except for
398 import libraries. You must do interfacing by means of DLLs.
399
400 * You can link against Microsoft C libraries. However, the preferred
401 solution is to use C/C++ compiler that comes with GNAT, since it
402 doesn't require having two different development environments and makes the
403 inter-language debugging experience smoother.
404
405 * When the compilation environment is located on FAT32 drives, you may
406 experience recompilations of source files that have not changed if
407 Daylight Saving Time (DST) state has changed since the last time files
408 were compiled. NTFS drives do not have this problem.
409
410 * No components of the GNAT toolset use any entries in the Windows
411 registry. The only entries installation of GNAT may create are file
412 associations and PATH settings, provided you chose to
413 create them at installation time, as well as some minimal
414 bookkeeping information needed to correctly uninstall or integrate
415 different GNAT products.
416
417
418 .. _Using_a_network_installation_of_GNAT:
419
420 Using a network installation of GNAT
421 ------------------------------------
422
423 Make sure the system on which GNAT is installed is accessible from the
424 current machine, i.e., the install location is shared over the network.
425 Shared resources are accessed on Windows by means of UNC paths, which
426 have the format ``\\\\server\\sharename\\path``
427
428 In order to use such a network installation, simply add the UNC path of the
429 :file:`bin` directory of your GNAT installation in front of your PATH. For
430 example, if GNAT is installed in :file:`\\GNAT` directory of a share location
431 called :file:`c-drive` on a machine :file:`LOKI`, the following command will
432 make it available:
433
434 ::
435
436 $ path \\loki\c-drive\gnat\bin;%path%`
437
438 Be aware that every compilation using the network installation results in the
439 transfer of large amounts of data across the network and will likely cause
440 a serious performance penalty.
441
442 .. _CONSOLE_and_WINDOWS_subsystems:
443
444 CONSOLE and WINDOWS subsystems
445 ------------------------------
446
447 .. index:: CONSOLE Subsystem
448 .. index:: WINDOWS Subsystem
449 .. index:: -mwindows
450
451 There are two main subsystems under Windows. The ``CONSOLE`` subsystem
452 (which is the default subsystem) always creates a console when
453 launching the application. This is not something desirable when the
454 application has a Windows GUI. To remove this console, your
455 application must use the ``WINDOWS`` subsystem. To do so, you must
456 specify the :switch:`-mwindows` linker switch.
457
458 ::
459
460 $ gnatmake winprog -largs -mwindows
461
462 .. _Temporary_Files:
463
464 Temporary Files
465 ---------------
466
467 .. index:: Temporary files
468
469 You can control where temporary files get created by setting the
470 :envvar:`TMP` environment variable. The file will be created:
471
472 * Under the directory pointed to by the :envvar:`TMP` environment variable if
473 this directory exists.
474
475 * Under :file:`c:\\temp`, if the :envvar:`TMP` environment variable is not
476 set (or not pointing to a directory) and if this directory exists.
477
478 * Under the current working directory otherwise.
479
480 This allows you to determine exactly where the temporary
481 file will be created. This is particularly useful in networked
482 environments where you may not have write access to some
483 directories.
484
485 Disabling Command Line Argument Expansion
486 -----------------------------------------
487
488 .. index:: Command Line Argument Expansion
489
490 By default, an executable compiled for the Windows platform will do
491 the following postprocessing on the arguments passed on the command
492 line:
493
494 * If the argument contains the characters ``*`` and/or ``?``,
495 file expansion will be attempted. For example, if the current directory
496 contains :file:`a.txt` and :file:`b.txt`, then when calling::
497
498 $ my_ada_program *.txt
499
500 The following arguments will effectively be passed to the main program
501 (for example when using ``Ada.Command_Line.Argument``)::
502
503 Ada.Command_Line.Argument (1) -> "a.txt"
504 Ada.Command_Line.Argument (2) -> "b.txt"
505
506 * You can disable filename expansion for a given argument by using single
507 quotes. Thus, calling::
508
509 $ my_ada_program '*.txt'
510
511 will result in::
512
513 Ada.Command_Line.Argument (1) -> "*.txt"
514
515 Note that if the program is launched from a shell such as Cygwin Bash,
516 quote removal might be performed by that shell.
517
518 In some contexts, it might be useful to disable this feature (for example if
519 the program performs its own argument expansion). In order to do this, a C
520 symbol needs to be defined and set to ``0``. You can do this by
521 adding the following code fragment in one of your Ada units:
522
523 .. code-block:: ada
524
525 Do_Argv_Expansion : Integer := 0;
526 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
527
528 The results of previous examples will be respectively::
529
530 Ada.Command_Line.Argument (1) -> "*.txt"
531
532 and::
533
534 Ada.Command_Line.Argument (1) -> "'*.txt'"
535
536 .. _Choosing_the_Scheduling_Policy_With_Windows:
537
538 Choosing the Scheduling Policy with Windows
539 -------------------------------------------
540
541 Under Windows, the standard 31 priorities of the Ada model are mapped onto
542 Window's seven standard priority levels by default: Idle, Lowest, Below Normal,
543 Normal, Above Normal,
544
545 When using the ``FIFO_Within_Priorities`` task dispatching policy, GNAT
546 assigns the ``REALTIME_PRIORITY_CLASS`` priority class to the application
547 and maps the Ada priority range to the sixteen priorities made available under
548 ``REALTIME_PRIORITY_CLASS``.
549
550 For details on the values of the different priority mappings, see declarations
551 in :file:`system.ads`. For more information about Windows priorities, please
552 refer to Microsoft documentation.
553
554 Windows Socket Timeouts
555 -----------------------
556
557 Microsoft Windows desktops older than ``8.0`` and Microsoft Windows Servers
558 older than ``2019`` set a socket timeout 500 milliseconds longer than the value
559 set by setsockopt with ``SO_RCVTIMEO`` and ``SO_SNDTIMEO`` options. The GNAT
560 runtime makes a correction for the difference in the corresponding Windows
561 versions. For Windows Server starting with version ``2019``, you must
562 provide a manifest file for the GNAT runtime to be able to recognize that
563 the Windows version does not need the timeout correction. The manifest file
564 should be located in the same directory as the executable file and its file
565 name must match the executable name suffixed by ``.manifest``. For example,
566 if the executable name is :file:`sock_wto.exe`, the manifest file name
567 must be :file:`sock_wto.exe.manifest`. The manifest file must contain at
568 least the following data::
569
570 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
571 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
572 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
573 <application>
574 <!-- Windows Vista -->
575 <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
576 <!-- Windows 7 -->
577 <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
578 <!-- Windows 8 -->
579 <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
580 <!-- Windows 8.1 -->
581 <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
582 <!-- Windows 10 -->
583 <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
584 </application>
585 </compatibility>
586 </assembly>
587
588 Without the manifest file, the socket timeout will be overcorrected on
589 these Windows Server versions and the actual time wil be 500
590 milliseconds shorter than what was set with
591 ``GNAT.Sockets.Set_Socket_Option``. Note that on Microsoft Windows
592 versions where correction is necessary, there is no way to set a
593 socket timeout shorter than 500 ms. If a socket timeout shorter than
594 500 ms is needed on these Windows versions, you should add a call to
595 ``Check_Selector`` before any socket read or write
596 operations.
597
598
599 .. _Mixed-Language_Programming_on_Windows:
600
601 Mixed-Language Programming on Windows
602 -------------------------------------
603
604 Developing pure Ada applications on Windows is no different than on
605 other GNAT-supported platforms. However, when developing or porting an
606 application that contains a mix of Ada and C/C++, the choice of your
607 Windows C/C++ development environment conditions your overall
608 interoperability strategy.
609
610 If you use ``gcc`` or Microsoft C to compile the non-Ada part of
611 your application, there are no Windows-specific restrictions that
612 affect the overall interoperability with your Ada code. If you do want
613 to use the Microsoft tools for your C++ code, you have two choices:
614
615 * You can encapsulate your C++ code in a DLL to be linked with your Ada
616 application. In this case, use the Microsoft or other environment to
617 build the DLL and use GNAT to build your executable
618 (:ref:`Using_DLLs_with_GNAT`).
619
620 * You can encapsulate your Ada code in a DLL to be linked with the
621 other part of your application. In this case, use GNAT to build the DLL
622 (:ref:`Building_DLLs_with_GNAT_Project_files`) and use the Microsoft
623 or other environment to build your executable.
624
625 In addition to the description about C ``main`` in
626 :ref:`Mixed_Language_Programming` section, if the C ``main`` uses a
627 stand-alone library, it is required on x86-windows to
628 setup the SEH context. For this, the C ``main`` must looks like this:
629
630
631 .. code-block:: c
632
633 /* main.c */
634 extern void adainit (void);
635 extern void adafinal (void);
636 extern void __gnat_initialize(void*);
637 extern void call_to_ada (void);
638
639 int main (int argc, char *argv[])
640 {
641 int SEH [2];
642
643 /* Initialize the SEH context */
644 __gnat_initialize (&SEH);
645
646 adainit();
647
648 /* Then call Ada services in the stand-alone library */
649
650 call_to_ada();
651
652 adafinal();
653 }
654
655 Note that you need not do this on x86_64-windows where the Windows
656 native SEH support is used.
657
658
659 .. _Windows_Calling_Conventions:
660
661 Windows Calling Conventions
662 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
663
664 .. index:: Stdcall
665 .. index:: APIENTRY
666
667 This section pertain only to Win32. On Win64, there is a single native
668 calling convention. All convention specifiers are ignored on this
669 platform.
670
671 When a subprogram ``F`` (caller) calls a subprogram ``G``
672 (callee), there are several ways to push ``G``\ 's parameters on the
673 stack and there are several possible scenarios to clean up the stack
674 upon ``G``\ 's return. A calling convention is an agreed upon software
675 protocol whereby the responsibilities between the caller (``F``) and
676 the callee (``G``) are clearly defined. Several calling conventions
677 are available for Windows:
678
679 * ``C`` (Microsoft defined)
680
681 * ``Stdcall`` (Microsoft defined)
682
683 * ``Win32`` (GNAT specific)
684
685 * ``DLL`` (GNAT specific)
686
687
688 .. _C_Calling_Convention:
689
690 ``C`` Calling Convention
691 """"""""""""""""""""""""
692
693 This is the default calling convention used when interfacing to C/C++
694 routines compiled with either ``gcc`` or Microsoft Visual C++.
695
696 In the ``C`` calling convention, subprogram parameters are pushed on the
697 stack by the caller from right to left. The caller itself is in charge of
698 cleaning up the stack after the call. In addition, the name of a routine
699 with ``C`` calling convention is mangled by adding a leading underscore.
700
701 The name to use on the Ada side when importing (or exporting) a routine
702 with ``C`` calling convention is the name of the routine. For
703 example you should import the C function:
704
705 ::
706
707 int get_val (long);
708
709 from Ada as follows:
710
711 .. code-block:: ada
712
713 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
714 pragma Import (C, Get_Val, External_Name => "get_val");
715
716 Note that in this particular case, you could have omitted the
717 ``External_Name`` parameter since, when missing, this parameter is set
718 to the name of the Ada entity in lower case. When the ``Link_Name``
719 parameter is missing, as in the above example, this parameter is set
720 the ``External_Name`` with a leading underscore.
721
722 When importing a variable defined in C, you should always use the ``C``
723 calling convention unless the object containing the variable is part of a
724 DLL (in which case you should use the ``Stdcall`` calling
725 convention, :ref:`Stdcall_Calling_Convention`).
726
727
728 .. _Stdcall_Calling_Convention:
729
730 ``Stdcall`` Calling Convention
731 """"""""""""""""""""""""""""""
732
733 This convention, which was the calling convention used for Pascal
734 programs, is used by Microsoft for all the routines in the Win32 API for
735 efficiency reasons. You must use it to import any routine for which this
736 convention was specified.
737
738 In the ``Stdcall`` calling convention, subprogram parameters are also pushed
739 on the stack by the caller from right to left. However, the callee, not the
740 caller, is in charge of cleaning up the stack on routine exit. In addition,
741 the name of a routine with ``Stdcall`` calling convention is mangled by
742 adding a leading underscore (as for the ``C`` calling convention) and a
743 trailing :samp:`@{nn}`, where ``nn`` is the overall size (in
744 bytes) of the parameters passed to the routine.
745
746 The name to use on the Ada side when importing a C routine with a
747 ``Stdcall`` calling convention is the name of the C routine. The leading
748 underscore and trailing :samp:`@{nn}` are added automatically by
749 the compiler. For example, you could import the Win32 function:
750
751 ::
752
753 APIENTRY int get_val (long);
754
755 from Ada as follows:
756
757 .. code-block:: ada
758
759 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
760 pragma Import (Stdcall, Get_Val);
761 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@4"
762
763 Like the case for the ``C`` calling convention, when the
764 ``External_Name`` parameter is missing, it is the name of the Ada
765 entity in lower case. If instead of writing the above import pragma
766 you write:
767
768 .. code-block:: ada
769
770 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
771 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
772
773 the imported routine is ``_retrieve_val@4``. However, if instead
774 of specifying the ``External_Name`` parameter, you specify the
775 ``Link_Name`` as in the following example:
776
777 .. code-block:: ada
778
779 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
780 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
781
782 the imported routine is ``retrieve_val``. There is no
783 decoration at all; no leading underscore and no Stdcall suffix
784 :samp:`@{nn}`.
785
786 This is especially important as in some special cases a DLL's entry
787 point name lacks a trailing :samp:`@{nn}` while the exported
788 name generated for a call has it.
789
790 You can also import variables defined in a DLL by using an
791 import pragma for a variable. As an example, if a DLL contains a
792 variable defined as:
793
794 .. code-block:: c
795
796 int my_var;
797
798 then, to access this variable from Ada you should write:
799
800 .. code-block:: ada
801
802 My_Var : Interfaces.C.int;
803 pragma Import (Stdcall, My_Var);
804
805 Note that to ease building cross-platform bindings, this convention
806 will be handled as a ``C`` calling convention on non-Windows platforms.
807
808
809 .. _Win32_Calling_Convention:
810
811 ``Win32`` Calling Convention
812 """"""""""""""""""""""""""""
813
814 This convention, which is GNAT-specific, is fully equivalent to the
815 ``Stdcall`` calling convention described above.
816
817
818 .. _DLL_Calling_Convention:
819
820 ``DLL`` Calling Convention
821 """"""""""""""""""""""""""
822
823 This convention, which is GNAT-specific, is fully equivalent to the
824 ``Stdcall`` calling convention described above.
825
826
827 .. _Introduction_to_Dynamic_Link_Libraries_DLLs:
828
829 Introduction to Dynamic Link Libraries (DLLs)
830 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
831
832 .. index:: DLL
833
834 A Dynamically Linked Library (DLL) is a library that can be shared by
835 several applications running under Windows. A DLL can contain any number of
836 routines and variables.
837
838 One advantage of DLLs is that you can change and enhance them without
839 forcing all the applications that depend on them to be relinked or
840 recompiled. However, you should be aware than all calls to DLL routines are
841 slower since, as you will understand below, such calls are indirect.
842
843 To illustrate the remainder of this section, suppose that an application
844 wants to use the services of a DLL :file:`API.dll`. To use the services
845 provided by :file:`API.dll`, you must statically link against the DLL or
846 an import library which contains a jump table with an entry for each
847 routine and variable exported by the DLL. In the Microsoft world, this
848 import library is called :file:`API.lib`. When using GNAT, this import
849 library is called either :file:`libAPI.dll.a`, :file:`libapi.dll.a`,
850 :file:`libAPI.a` or :file:`libapi.a` (names are case insensitive).
851
852 After you have linked your application with the DLL or the import library
853 and you run your application, here is what happens:
854
855 * Your application is loaded into memory.
856
857 * The DLL :file:`API.dll` is mapped into the address space of your
858 application. This means that:
859
860 - The DLL uses the stack of the calling thread.
861
862 - The DLL uses the virtual address space of the calling process.
863
864 - The DLL allocates memory from the virtual address space of the calling
865 process.
866
867 - Handles (pointers) can be safely exchanged between routines in the DLL
868 routines and routines in the application using the DLL.
869
870 * The entries in the jump table (from the import library :file:`libAPI.dll.a`
871 or :file:`API.lib` or automatically created when linking against a DLL)
872 which is part of your application are initialized with the addresses
873 of the routines and variables in :file:`API.dll`.
874
875 * If present in :file:`API.dll`, routines ``DllMain`` or
876 ``DllMainCRTStartup`` are invoked. These routines typically contain
877 the initialization code needed for the well-being of the routines and
878 variables exported by the DLL.
879
880 There is an additional point which is worth mentioning. In the Windows
881 world, there are two kind of DLLs: relocatable and non-relocatable
882 DLLs. Non-relocatable DLLs can only be loaded at a specific address
883 in the target application address space. If the addresses of two
884 non-relocatable DLLs overlap and these happen to be used by the same
885 application, a conflict occurs and the application will run
886 incorrectly. Hence, when possible, you should always use and
887 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
888 supported by GNAT. Note that the :switch:`-s` linker switch (see GNU Linker
889 User's Guide) removes the debugging symbols from the DLL, but the DLL can
890 still be relocated.
891
892 As a side note, an interesting difference between Microsoft DLLs and
893 Unix shared libraries is the fact that on most Unix systems all public
894 routines are exported by default in a Unix shared library, while under
895 Windows it is possible (but not required) to list exported routines in
896 a definition file (see :ref:`The Definition File <The_Definition_File>`).
897
898
899 .. _Using_DLLs_with_GNAT:
900
901 Using DLLs with GNAT
902 ^^^^^^^^^^^^^^^^^^^^
903
904 To use the services of a DLL, say :file:`API.dll`, in your Ada application
905 you must have:
906
907 * The Ada spec for the routines and/or variables you want to access in
908 :file:`API.dll`. If not available, you must build this Ada spec from the
909 C/C++ header files provided with the DLL.
910
911 * The import library (:file:`libAPI.dll.a` or :file:`API.lib`). As previously
912 mentioned, an import library is a statically linked library containing the
913 import table, which is filled at load time to point to the actual
914 :file:`API.dll` routines. Sometimes you don't have an import library for the
915 DLL you want to use. The following sections will explain how to build
916 one. Note that this is optional.
917
918 * The actual DLL, :file:`API.dll`.
919
920 Once you have all the above, to compile an Ada application that uses the
921 services of :file:`API.dll` and whose main subprogram is ``My_Ada_App``,
922 you simply issue the command
923
924 ::
925
926 $ gnatmake my_ada_app -largs -lAPI
927
928 The argument :switch:`-largs -lAPI` at the end of the ``gnatmake`` command
929 tells the GNAT linker to look for an import library. The linker will
930 look for a library name in this specific order:
931
932 * :file:`libAPI.dll.a`
933 * :file:`API.dll.a`
934 * :file:`libAPI.a`
935 * :file:`API.lib`
936 * :file:`libAPI.dll`
937 * :file:`API.dll`
938
939 The first three are the GNU-style import libraries. The third is the
940 Microsoft-style import libraries. The last two are the actual DLL names.
941
942 Note that if the Ada package spec for :file:`API.dll` contains the
943 following pragma
944
945 .. code-block:: ada
946
947 pragma Linker_Options ("-lAPI");
948
949 you do not have to add :switch:`-largs -lAPI` at the end of the
950 ``gnatmake`` command.
951
952 If any one of the items above is missing, you will have to create it
953 yourself. The following sections explain how to do so using as an
954 example a fictitious DLL called :file:`API.dll`.
955
956
957 .. _Creating_an_Ada_Spec_for_the_DLL_Services:
958
959 Creating an Ada Spec for the DLL Services
960 """""""""""""""""""""""""""""""""""""""""
961
962 A DLL typically comes with a C/C++ header file which provides the
963 definitions of the routines and variables exported by the DLL. The Ada
964 equivalent of this header file is a package spec that contains definitions
965 for the imported entities. If the DLL you intend to use does not come with
966 an Ada spec, you have to generate such a spec yourself. For example, if
967 the header file of :file:`API.dll` is a file :file:`api.h` containing the
968 following two definitions:
969
970 .. code-block:: c
971
972 int some_var;
973 int get (char *);
974
975 then the equivalent Ada spec could be:
976
977 .. code-block:: ada
978
979 with Interfaces.C.Strings;
980 package API is
981 use Interfaces;
982
983 Some_Var : C.int;
984 function Get (Str : C.Strings.Chars_Ptr) return C.int;
985
986 private
987 pragma Import (C, Get);
988 pragma Import (DLL, Some_Var);
989 end API;
990
991
992 .. _Creating_an_Import_Library:
993
994 Creating an Import Library
995 """"""""""""""""""""""""""
996
997 .. index:: Import library
998
999 If a Microsoft-style import library :file:`API.lib` or a GNAT-style
1000 import library :file:`libAPI.dll.a` or :file:`libAPI.a` is available
1001 with :file:`API.dll` you can skip this section. You can also skip this
1002 section if :file:`API.dll` or :file:`libAPI.dll` is built with GNU tools
1003 as in this case it is possible to link directly against the
1004 DLL. Otherwise read on.
1005
1006
1007 .. index:: Definition file
1008
1009 .. _The_Definition_File:
1010
1011 .. rubric:: The Definition File
1012
1013 As previously mentioned, and unlike Unix systems, the list of symbols
1014 that are exported from a DLL must be provided explicitly in Windows.
1015 The main goal of a definition file is precisely that: list the symbols
1016 exported by a DLL. A definition file (usually a file with a ``.def``
1017 suffix) has the following structure:
1018
1019 ::
1020
1021 [LIBRARY ``name``]
1022 [DESCRIPTION ``string``]
1023 EXPORTS
1024 ``symbol1``
1025 ``symbol2``
1026 ...
1027
1028 *LIBRARY name*
1029 This section, which is optional, gives the name of the DLL.
1030
1031
1032 *DESCRIPTION string*
1033 This section, which is optional, gives a description string that will be
1034 embedded in the import library.
1035
1036
1037 *EXPORTS*
1038 This section gives the list of exported symbols (procedures, functions or
1039 variables). For example, in the case of :file:`API.dll` the ``EXPORTS``
1040 section of :file:`API.def` looks like:
1041
1042 ::
1043
1044 EXPORTS
1045 some_var
1046 get
1047
1048 Note that you must specify the correct suffix (:samp:`@{nn}`)
1049 (see :ref:`Windows_Calling_Conventions`) for a Stdcall
1050 calling convention function in the exported symbols list.
1051
1052 There can actually be other sections in a definition file, but these
1053 sections are not relevant to the discussion at hand.
1054
1055
1056 .. _Create_Def_File_Automatically:
1057
1058 .. rubric:: Creating a Definition File Automatically
1059
1060 You can automatically create the definition file :file:`API.def`
1061 (see :ref:`The Definition File <The_Definition_File>`) from a DLL.
1062 To do that, use the ``dlltool`` program as follows:
1063
1064 ::
1065
1066 $ dlltool API.dll -z API.def --export-all-symbols
1067
1068 Note that if some routines in the DLL have the ``Stdcall`` convention
1069 (:ref:`Windows_Calling_Conventions`) with stripped :samp:`@{nn}`
1070 suffix then you'll have to edit :file:`api.def` to add it and specify
1071 :switch:`-k` to ``gnatdll`` when creating the import library.
1072
1073 Here are some hints to find the right :samp:`@{nn}` suffix.
1074
1075 - If you have the Microsoft import library (.lib), you may be able
1076 to find the right symbols by using the Microsoft ``dumpbin`` tool
1077 (see the corresponding Microsoft documentation for further
1078 details).
1079
1080 ::
1081
1082 $ dumpbin /exports api.lib
1083
1084 - If you get a message about a missing symbol at link time, the compiler
1085 tells you what symbol is expected. You then can go back to the
1086 definition file and add the right suffix.
1087
1088
1089 .. _GNAT-Style_Import_Library:
1090
1091 .. rubric:: GNAT-Style Import Library
1092
1093 To create a static import library from :file:`API.dll` with the GNAT tools,
1094 you should create the :file:`.def` file and use the ``gnatdll`` tool
1095 (see :ref:`Using_gnatdll`) as follows:
1096
1097 ::
1098
1099 $ gnatdll -e API.def -d API.dll
1100
1101 ``gnatdll`` takes as input a definition file :file:`API.def` and the
1102 name of the DLL containing the services listed in the definition file
1103 :file:`API.dll`. The name of the static import library generated is
1104 computed from the name of the definition file as follows: if the
1105 definition file name is :file:`xyz.def`, the import library name will
1106 be :file:`libxyz.a`. Note that in the previous example, the switch
1107 :switch:`-e` could have been removed because the name of the definition
1108 file (before the ``.def`` suffix) is the same as the name of the
1109 DLL (:ref:`Using_gnatdll` for more information about ``gnatdll``).
1110
1111
1112 .. _MSVS-Style_Import_Library:
1113
1114 .. rubric:: Microsoft-Style Import Library
1115
1116 A Microsoft import library is needed only if you plan to make an
1117 Ada DLL available to applications developed with Microsoft
1118 tools (:ref:`Mixed-Language_Programming_on_Windows`).
1119
1120 To create a Microsoft-style import library for :file:`API.dll` you
1121 should create the :file:`.def` file, then build the actual import library using
1122 Microsoft's ``lib`` utility:
1123
1124 ::
1125
1126 $ lib -machine:IX86 -def:API.def -out:API.lib
1127
1128 If you use the above command, the definition file :file:`API.def` must
1129 contain a line giving the name of the DLL:
1130
1131 ::
1132
1133 LIBRARY "API"
1134
1135 See the Microsoft documentation for further details about the usage of
1136 ``lib``.
1137
1138
1139 .. _Building_DLLs_with_GNAT_Project_files:
1140
1141 Building DLLs with GNAT Project files
1142 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1143
1144 .. index:: DLLs, building
1145
1146 There is nothing specific to Windows in the build process.
1147 See the *Library Projects* section in the *GNAT Project Manager*
1148 chapter of the *GPRbuild User's Guide*.
1149
1150 Due to a system limitation, you cannot create threads under Windows
1151 when inside the ``DllMain`` routine which is used for auto-initialization
1152 of shared libraries, so you can't have library level tasks in SALs.
1153
1154
1155 .. _Building_DLLs_with_GNAT:
1156
1157 Building DLLs with GNAT
1158 ^^^^^^^^^^^^^^^^^^^^^^^
1159
1160 .. index:: DLLs, building
1161
1162 This section explains how to build DLLs using the GNAT built-in DLL
1163 support. With the following procedure, it is straightforward to build
1164 and use DLLs with GNAT.
1165
1166
1167 * Building object files.
1168 The first step is to build all objects files that are to be included
1169 into the DLL. This is done using the standard ``gnatmake`` tool.
1170
1171 * Building the DLL.
1172 To build the DLL, you must use the ``gcc`` :switch:`-shared` and
1173 :switch:`-shared-libgcc` switches. It's quite simple to use this method:
1174
1175 ::
1176
1177 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
1178
1179 It's important to note that in this case all symbols found in the
1180 object files are automatically exported. You can restrict
1181 the set of symbols to export by passing to ``gcc`` a definition
1182 file (see :ref:`The Definition File <The_Definition_File>`).
1183 For example:
1184
1185 ::
1186
1187 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
1188
1189 If you use a definition file, you must export the elaboration procedures
1190 for every package that requires one. Elaboration procedures are named
1191 using the package name followed by "_E".
1192
1193 * Preparing DLL to be used.
1194 For the DLL to be used by client programs, the bodies must be hidden
1195 from it and the :file:`.ali` set with read-only attribute. This is very
1196 important because otherwise GNAT will recompile all packages and will not
1197 actually use the code in the DLL. For example:
1198
1199 ::
1200
1201 $ mkdir apilib
1202 $ copy *.ads *.ali api.dll apilib
1203 $ attrib +R apilib\\*.ali
1204
1205 At this point, you can use the DLL by directly linking
1206 against it. Note that you must use the GNAT shared runtime when using
1207 GNAT shared libraries. You do this with the :switch:`-shared` binder
1208 switch.
1209
1210 ::
1211
1212 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
1213
1214
1215 .. _Building_DLLs_with_gnatdll:
1216
1217 Building DLLs with gnatdll
1218 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1219
1220 .. index:: DLLs, building
1221
1222 Note that it is preferred to use GNAT Project files
1223 (:ref:`Building_DLLs_with_GNAT_Project_files`) or the built-in GNAT
1224 DLL support (:ref:`Building_DLLs_with_GNAT`) to build DLLs.
1225
1226 This section explains how to build DLLs containing Ada code using
1227 ``gnatdll``. These DLLs will be referred to as Ada DLLs in the
1228 remainder of this section.
1229
1230 The steps required to build an Ada DLL that is to be used by Ada as well as
1231 non-Ada applications are as follows:
1232
1233 * You need to mark each Ada entity exported by the DLL with a ``C`` or
1234 ``Stdcall`` calling convention to avoid any Ada name mangling for the
1235 entities exported by the DLL
1236 (see :ref:`Exporting Ada Entities <Exporting_Ada_Entities>`). You can
1237 skip this step if you plan to use the Ada DLL only from Ada applications.
1238
1239 * Your Ada code must export an initialization routine which calls the routine
1240 ``adainit`` (generated by ``gnatbind``) to perform the elaboration of
1241 the Ada code in the DLL (:ref:`Ada_DLLs_and_Elaboration`). The initialization
1242 routine exported by the Ada DLL must be invoked by the clients of the DLL
1243 to initialize the DLL.
1244
1245 * When useful, the DLL should also export a finalization routine which calls
1246 routine ``adafinal`` (also generated by ``gnatbind``) to perform the
1247 finalization of the Ada code in the DLL (:ref:`Ada_DLLs_and_Finalization`).
1248 The finalization routine exported by the Ada DLL must be invoked by the
1249 clients of the DLL when the DLL services are no further needed.
1250
1251 * You must provide a spec for the services exported by the Ada DLL in each
1252 of the programming languages to which you plan to make the DLL available.
1253
1254 * You must provide a definition file listing the exported entities
1255 (:ref:`The Definition File <The_Definition_File>`).
1256
1257 * Finally, you must use ``gnatdll`` to produce the DLL and the import
1258 library (:ref:`Using_gnatdll`).
1259
1260 Note that a relocatable DLL stripped using the ``strip``
1261 binutils tool is no longer relocatable. To build a DLL without
1262 debug information, pass :switch:`-largs -s` to ``gnatdll``. This
1263 restriction does not apply to a DLL built using a Library Project.
1264 See the *Library Projects* section in the *GNAT Project Manager*
1265 chapter of the *GPRbuild User's Guide*.
1266
1267
1268 .. Limitations_When_Using_Ada_DLLs_from Ada:
1269
1270 Limitations When Using Ada DLLs from Ada
1271 """"""""""""""""""""""""""""""""""""""""
1272
1273 When using Ada DLLs from Ada applications there is a limitation you
1274 should be aware of. On Windows, the GNAT run-time is not in a DLL of
1275 its own, so each Ada DLL includes a part of the GNAT run-time. Specifically,
1276 each Ada DLL includes the services of the GNAT run-time that are necessary
1277 for the Ada code inside the DLL. As a result, when an Ada program uses an
1278 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
1279 one in the main program.
1280
1281 It is therefore not possible to exchange GNAT run-time objects between the
1282 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
1283 handles (e.g., ``Text_IO.File_Type``), tasks types, protected objects
1284 types, etc.
1285
1286 It is completely safe to exchange plain elementary, array or record types,
1287 Windows object handles, etc.
1288
1289
1290 .. _Exporting_Ada_Entities:
1291
1292 Exporting Ada Entities
1293 """"""""""""""""""""""
1294
1295 .. index:: Export table
1296
1297 Building a DLL is a way to encapsulate a set of services usable from any
1298 application. As a result, the Ada entities exported by a DLL should be
1299 exported with the ``C`` or ``Stdcall`` calling conventions to avoid
1300 any Ada name mangling. As an example here is an Ada package
1301 ``API``, spec and body, exporting two procedures, a function, and a
1302 variable:
1303
1304
1305 .. code-block:: ada
1306
1307 with Interfaces.C; use Interfaces;
1308 package API is
1309 Count : C.int := 0;
1310 function Factorial (Val : C.int) return C.int;
1311
1312 procedure Initialize_API;
1313 procedure Finalize_API;
1314 -- Initialization & Finalization routines. More in the next section.
1315 private
1316 pragma Export (C, Initialize_API);
1317 pragma Export (C, Finalize_API);
1318 pragma Export (C, Count);
1319 pragma Export (C, Factorial);
1320 end API;
1321
1322 .. code-block:: ada
1323
1324 package body API is
1325 function Factorial (Val : C.int) return C.int is
1326 Fact : C.int := 1;
1327 begin
1328 Count := Count + 1;
1329 for K in 1 .. Val loop
1330 Fact := Fact * K;
1331 end loop;
1332 return Fact;
1333 end Factorial;
1334
1335 procedure Initialize_API is
1336 procedure Adainit;
1337 pragma Import (C, Adainit);
1338 begin
1339 Adainit;
1340 end Initialize_API;
1341
1342 procedure Finalize_API is
1343 procedure Adafinal;
1344 pragma Import (C, Adafinal);
1345 begin
1346 Adafinal;
1347 end Finalize_API;
1348 end API;
1349
1350 If the Ada DLL you are building will only be used by Ada applications,
1351 you do not have to export Ada entities with a ``C`` or ``Stdcall``
1352 convention. As an example, the previous package could be written as
1353 follows:
1354
1355 .. code-block:: ada
1356
1357 package API is
1358 Count : Integer := 0;
1359 function Factorial (Val : Integer) return Integer;
1360
1361 procedure Initialize_API;
1362 procedure Finalize_API;
1363 -- Initialization and Finalization routines.
1364 end API;
1365
1366 .. code-block:: ada
1367
1368 package body API is
1369 function Factorial (Val : Integer) return Integer is
1370 Fact : Integer := 1;
1371 begin
1372 Count := Count + 1;
1373 for K in 1 .. Val loop
1374 Fact := Fact * K;
1375 end loop;
1376 return Fact;
1377 end Factorial;
1378
1379 ...
1380 -- The remainder of this package body is unchanged.
1381 end API;
1382
1383 Note that if you do not export the Ada entities with a ``C`` or
1384 ``Stdcall`` convention, you will have to provide the mangled Ada names
1385 in the definition file of the Ada DLL
1386 (:ref:`Creating_the_Definition_File`).
1387
1388
1389 .. _Ada_DLLs_and_Elaboration:
1390
1391 Ada DLLs and Elaboration
1392 """"""""""""""""""""""""
1393
1394 .. index:: DLLs and elaboration
1395
1396 The DLL that you are building contains your Ada code as well as all the
1397 routines in the Ada library that are needed by it. The first thing a
1398 user of your DLL must do is elaborate the Ada code
1399 (:ref:`Elaboration_Order_Handling_in_GNAT`).
1400
1401 To allow this, you must export an initialization routine
1402 (``Initialize_API`` in the previous example), which must be invoked
1403 before using any of the DLL services. This elaboration routine must call
1404 the Ada elaboration routine ``adainit`` generated by the GNAT binder
1405 (:ref:`Binding_with_Non-Ada_Main_Programs`). See the body of
1406 ``Initialize_Api`` for an example. Note that the GNAT binder is
1407 automatically invoked during the DLL build process by the ``gnatdll``
1408 tool (:ref:`Using_gnatdll`).
1409
1410 When a DLL is loaded, Windows systematically invokes a routine called
1411 ``DllMain``. It should therefore be possible to call ``adainit``
1412 directly from ``DllMain`` without having to provide an explicit
1413 initialization routine. Unfortunately, you can't call
1414 ``adainit`` from the ``DllMain`` if your program has library level
1415 tasks because access to the ``DllMain`` entry point is serialized by
1416 the system (that is, only a single thread can execute 'through' it at a
1417 time), which means that the GNAT run-time will deadlock waiting for a
1418 newly created task to complete its initialization.
1419
1420
1421 .. _Ada_DLLs_and_Finalization:
1422
1423 Ada DLLs and Finalization
1424 ^^^^^^^^^^^^^^^^^^^^^^^^^
1425
1426 .. index:: DLLs and finalization
1427
1428 When the services of an Ada DLL are no longer needed, the client code should
1429 invoke the DLL finalization routine, if available. The DLL finalization
1430 routine is in charge of releasing all resources acquired by the DLL. In the
1431 case of the Ada code contained in the DLL, this is achieved by calling
1432 routine ``adafinal`` generated by the GNAT binder
1433 (:ref:`Binding_with_Non-Ada_Main_Programs`).
1434 See the body of ``Finalize_Api`` for an
1435 example. As already pointed out the GNAT binder is automatically invoked
1436 during the DLL build process by the ``gnatdll`` tool
1437 (:ref:`Using_gnatdll`).
1438
1439
1440 .. _Creating_a_Spec_for_Ada_DLLs:
1441
1442 Creating a Spec for Ada DLLs
1443 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1444
1445 To use the services exported by the Ada DLL from another programming
1446 language (e.g., C), you have to translate the specs of the exported Ada
1447 entities in that language. For instance in the case of ``API.dll``,
1448 the corresponding C header file could look like:
1449
1450 .. code-block:: c
1451
1452 extern int *_imp__count;
1453 #define count (*_imp__count)
1454 int factorial (int);
1455
1456 It is important to understand that when building an Ada DLL to be used by
1457 other Ada applications, you need two different specs for the packages
1458 contained in the DLL: one for building the DLL and the other for using
1459 the DLL. This is because the ``DLL`` calling convention is needed to
1460 use a variable defined in a DLL, but when building the DLL, the variable
1461 must have either the ``Ada`` or ``C`` calling convention. As an
1462 example consider a DLL consisting of the following package ``API``:
1463
1464 .. code-block:: ada
1465
1466 package API is
1467 Count : Integer := 0;
1468 ...
1469 -- Remainder of the package omitted.
1470 end API;
1471
1472 After producing a DLL containing package ``API``, the spec that
1473 must be used to import ``API.Count`` from Ada code outside of the
1474 DLL is:
1475
1476 .. code-block:: ada
1477
1478 package API is
1479 Count : Integer;
1480 pragma Import (DLL, Count);
1481 end API;
1482
1483
1484 .. _Creating_the_Definition_File:
1485
1486 Creating the Definition File
1487 """"""""""""""""""""""""""""
1488
1489 The definition file is the last file you need to build the DLL. It lists
1490 the exported symbols. As an example, the definition file for a DLL
1491 containing only package ``API`` above (where all the entities are exported
1492 with a ``C`` calling convention) is:
1493
1494 ::
1495
1496 EXPORTS
1497 count
1498 factorial
1499 finalize_api
1500 initialize_api
1501
1502 If the ``C`` calling convention is missing from package ``API``,
1503 the definition file contains the mangled Ada names of the above
1504 entities, which in this case are:
1505
1506 ::
1507
1508 EXPORTS
1509 api__count
1510 api__factorial
1511 api__finalize_api
1512 api__initialize_api
1513
1514
1515 .. _Using_gnatdll:
1516
1517 Using ``gnatdll``
1518 """""""""""""""""
1519
1520 .. index:: gnatdll
1521
1522 ``gnatdll`` is a tool to automate the DLL build process once all the Ada
1523 and non-Ada sources that make up your DLL have been compiled.
1524 ``gnatdll`` is actually in charge of two distinct tasks: building both the
1525 static import library for the DLL and the actual DLL. You invoke the
1526 ``gnatdll`` command as
1527
1528 ::
1529
1530 $ gnatdll [ switches ] list-of-files [ -largs opts ]
1531
1532 where ``list-of-files`` is a list of ALI and object files. The object
1533 file list must be the exact list of objects corresponding to the non-Ada
1534 sources whose services are to be included in the DLL. The ALI file list
1535 must be the exact list of ALI files for the corresponding Ada sources
1536 whose services are to be included in the DLL. If ``list-of-files`` is
1537 missing, only the static import library is generated.
1538
1539 You may specify any of the following switches to ``gnatdll``:
1540
1541
1542 .. index:: -a (gnatdll)
1543
1544 :switch:`-a[{address}]`
1545 Build a non-relocatable DLL at ``address``. If you don't specify
1546 ``address``, ``gnatdll`` uses the default address of ``0x11000000``. By
1547 default, when this switch is missing, ``gnatdll`` builds a
1548 relocatable DLL. We advise you to build relocatable DLL.
1549
1550
1551 .. index:: -bargs (gnatdll)
1552
1553 :switch:`-bargs {opts}`
1554 Binder switches. Pass ``opts`` to the binder.
1555
1556
1557 .. index:: -d (gnatdll)
1558
1559 :switch:`-d {dllfile}`
1560 ``dllfile`` is the name of the DLL. You must specify this switch for
1561 ``gnatdll`` to do anything. ``gnatdll`` names the generated import library
1562 algorithmically from ``dllfile`` as shown in the following
1563 example: if ``dllfile`` is :file:`xyz.dll`, the import library name is
1564 :file:`libxyz.dll.a`. ``gnatdll`` obtains the name of the definition file (if not specified
1565 by switch :switch:`-e`) algorithmically from ``dllfile``
1566 as shown in the following example:
1567 if ``dllfile`` is :file:`xyz.dll`, the definition
1568 file used is :file:`xyz.def`.
1569
1570
1571 .. index:: -e (gnatdll)
1572
1573 :switch:`-e {deffile}`
1574 ``deffile`` is the name of the definition file.
1575
1576
1577 .. index:: -g (gnatdll)
1578
1579 :switch:`-g`
1580 Generate debugging information. This information is stored in the object
1581 file and copied from there to the final DLL file by the linker,
1582 where it can be read by the debugger. You must use the
1583 :switch:`-g` switch if you plan on using the debugger or the symbolic
1584 stack traceback.
1585
1586
1587 .. index:: -h (gnatdll)
1588
1589 :switch:`-h`
1590 Help mode. Displays ``gnatdll`` switch usage information.
1591
1592
1593 .. index:: -I (gnatdll)
1594
1595 :switch:`-I{dir}`
1596 Direct ``gnatdll`` to search the ``dir`` directory for source and
1597 object files needed to build the DLL.
1598 (:ref:`Search_Paths_and_the_Run-Time_Library_RTL`).
1599
1600
1601 .. index:: -k (gnatdll)
1602
1603 :switch:`-k`
1604 Removes the :samp:`@{nn}` suffix from the import library's exported
1605 names, but keeps them for the link names. You must specify this
1606 switch if you want to use a ``Stdcall`` function in a DLL for which
1607 the :samp:`@{nn}` suffix has been removed. This is the case for most
1608 of the Windows NT DLL for example. This switch has no effect if you
1609 specify the :switch:`-n` switch.
1610
1611
1612 .. index:: -l (gnatdll)
1613
1614 :switch:`-l {file}`
1615 The list of ALI and object files used to build the DLL are listed in
1616 ``file``, instead of being given in the command line. Each line in
1617 ``file`` contains the name of an ALI or object file.
1618
1619
1620 .. index:: -n (gnatdll)
1621
1622 :switch:`-n`
1623 No Import. Do not create the import library.
1624
1625
1626 .. index:: -q (gnatdll)
1627
1628 :switch:`-q`
1629 Quiet mode. Do not display unnecessary messages.
1630
1631
1632 .. index:: -v (gnatdll)
1633
1634 :switch:`-v`
1635 Verbose mode. Display extra information.
1636
1637
1638 .. index:: -largs (gnatdll)
1639
1640 :switch:`-largs {opts}`
1641 Linker switches. Pass ``opts`` to the linker.
1642
1643
1644 .. rubric:: ``gnatdll`` Example
1645
1646 As an example, the command to build a relocatable DLL from :file:`api.adb`
1647 once :file:`api.adb` has been compiled and :file:`api.def` created is
1648
1649 ::
1650
1651 $ gnatdll -d api.dll api.ali
1652
1653 The above command creates two files: :file:`libapi.dll.a` (the import
1654 library) and :file:`api.dll` (the actual DLL). If you want to create
1655 only the DLL, just type:
1656
1657 ::
1658
1659 $ gnatdll -d api.dll -n api.ali
1660
1661 Alternatively, if you want to create just the import library, type:
1662
1663 ::
1664
1665 $ gnatdll -d api.dll
1666
1667
1668 .. rubric:: ``gnatdll`` behind the Scenes
1669
1670 This section details the steps involved in creating a DLL. ``gnatdll``
1671 does these steps for you. Unless you are interested in understanding what
1672 goes on behind the scenes, you should skip this section.
1673
1674 We use the previous example of a DLL containing the Ada package ``API``,
1675 to illustrate the steps necessary to build a DLL. The starting point is a
1676 set of objects that make up the DLL and the corresponding ALI
1677 files. In the case of this example, this means :file:`api.o` and
1678 :file:`api.ali`. To build a relocatable DLL, ``gnatdll`` does
1679 the following:
1680
1681 * builds the base file (:file:`api.base`). A base file gives
1682 the information necessary to generate relocation information for the
1683 DLL.
1684
1685 ::
1686
1687 $ gnatbind -n api
1688 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
1689
1690 In addition to the base file, the ``gnatlink`` command generates an
1691 output file :file:`api.jnk`, which can be discarded. The :switch:`-mdll` switch
1692 asks ``gnatlink`` to generate the routines ``DllMain`` and
1693 ``DllMainCRTStartup`` that are called by the Windows loader when the DLL
1694 is loaded into memory.
1695
1696 * uses ``dlltool`` (see :ref:`Using dlltool <Using_dlltool>`) to build the
1697 export table (:file:`api.exp`). The export table contains the relocation
1698 information in a form which can be used during the final link to ensure
1699 that the Windows loader is able to place the DLL anywhere in memory.
1700
1701 ::
1702
1703 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
1704 --output-exp api.exp
1705
1706 * builds the base file using the new export table. Note that
1707 ``gnatbind`` must be called once again since the binder generated file
1708 has been deleted during the previous call to ``gnatlink``.
1709
1710 ::
1711
1712 $ gnatbind -n api
1713 $ gnatlink api -o api.jnk api.exp -mdll
1714 -Wl,--base-file,api.base
1715
1716
1717 * builds the new export table using the new base file and
1718 generates the DLL import library :file:`libAPI.dll.a`.
1719
1720
1721 ::
1722
1723 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
1724 --output-exp api.exp --output-lib libAPI.a
1725
1726 * Finally, builds the relocatable DLL using the final export table.
1727
1728 ::
1729
1730 $ gnatbind -n api
1731 $ gnatlink api api.exp -o api.dll -mdll
1732
1733
1734 .. _Using_dlltool:
1735
1736 .. rubric:: Using ``dlltool``
1737
1738 ``dlltool`` is the low-level tool used by ``gnatdll`` to build
1739 DLLs and static import libraries. This section summarizes the most
1740 common ``dlltool`` switches. You run ``dlltool`` as follows:
1741
1742 ::
1743
1744 $ dlltool [`switches`]
1745
1746 ``dlltool`` switches include:
1747
1748
1749 .. index:: --base-file (dlltool)
1750
1751 :switch:`--base-file {basefile}`
1752 Read the base file ``basefile`` generated by the linker. You use this switch
1753 to create a relocatable DLL.
1754
1755
1756 .. index:: --def (dlltool)
1757
1758 :switch:`--def {deffile}`
1759 Read the definition file.
1760
1761
1762 .. index:: --dllname (dlltool)
1763
1764 :switch:`--dllname {name}`
1765 Gives the name of the DLL. You use this switch to embed the name of the
1766 DLL in the static import library generated by ``dlltool`` with switch
1767 :switch:`--output-lib`.
1768
1769
1770 .. index:: -k (dlltool)
1771
1772 :switch:`-k`
1773 Kill :samp:`@{nn}` from exported names
1774 (:ref:`Windows_Calling_Conventions`
1775 for a discussion about ``Stdcall``-style symbols).
1776
1777
1778 .. index:: --help (dlltool)
1779
1780 :switch:`--help`
1781 Prints the ``dlltool`` switches with a concise description.
1782
1783
1784 .. index:: --output-exp (dlltool)
1785
1786 :switch:`--output-exp {exportfile}`
1787 Generate an export file ``exportfile``. The export file contains the
1788 export table (list of symbols in the DLL) and is used to create the DLL.
1789
1790
1791 .. index:: --output-lib (dlltool)
1792
1793 :switch:`--output-lib {libfile}`
1794 Generate a static import library ``libfile``.
1795
1796
1797 .. index:: -v (dlltool)
1798
1799 :switch:`-v`
1800 Verbose mode.
1801
1802
1803 .. index:: --as (dlltool)
1804
1805 :switch:`--as {assembler-name}`
1806 Use ``assembler-name`` as the assembler. The default is ``as``.
1807
1808
1809 .. _GNAT_and_Windows_Resources:
1810
1811 GNAT and Windows Resources
1812 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1813
1814 .. index:: Resources, windows
1815
1816 Resources are an easy way to add Windows-specific objects to your
1817 application. The objects that you can add as resources include:
1818
1819 * menus
1820
1821 * accelerators
1822
1823 * dialog boxes
1824
1825 * string tables
1826
1827 * bitmaps
1828
1829 * cursors
1830
1831 * icons
1832
1833 * fonts
1834
1835 * version information
1836
1837 You can use a version information resource to embed information into
1838 an executable or a DLL. This information can be viewed using the file
1839 properties from the Windows Explorer. Here's an example of a version
1840 information resource:
1841
1842 ::
1843
1844 1 VERSIONINFO
1845 FILEVERSION 1,0,0,0
1846 PRODUCTVERSION 1,0,0,0
1847 BEGIN
1848 BLOCK "StringFileInfo"
1849 BEGIN
1850 BLOCK "080904E4"
1851 BEGIN
1852 VALUE "CompanyName", "My Company Name"
1853 VALUE "FileDescription", "My application"
1854 VALUE "FileVersion", "1.0"
1855 VALUE "InternalName", "my_app"
1856 VALUE "LegalCopyright", "My Name"
1857 VALUE "OriginalFilename", "my_app.exe"
1858 VALUE "ProductName", "My App"
1859 VALUE "ProductVersion", "1.0"
1860 END
1861 END
1862
1863 BLOCK "VarFileInfo"
1864 BEGIN
1865 VALUE "Translation", 0x809, 1252
1866 END
1867 END
1868
1869 The value ``0809`` (langID) is for the U.K English language and
1870 ``04E4`` (charsetID), which is equal to ``1252`` decimal, for
1871 multilingual.
1872
1873 This section explains how to build, compile and use resources. Note that this
1874 section does not cover all resource objects; for a complete description see
1875 the corresponding Microsoft documentation.
1876
1877
1878 .. _Building_Resources:
1879
1880 Building Resources
1881 """"""""""""""""""
1882
1883 .. index:: Resources, building
1884
1885 A resource file is an ASCII file. By convention, resource files have an
1886 :file:`.rc` extension.
1887 The easiest way to build a resource file is to use Microsoft tools
1888 such as ``imagedit.exe`` to build bitmaps, icons and cursors and
1889 ``dlgedit.exe`` to build dialogs.
1890 You can always build an :file:`.rc` file yourself by writing a
1891 resource script.
1892
1893 It's not our objective to explain how to write a resource file. A
1894 complete description of the resource script language can be found in
1895 the Microsoft documentation.
1896
1897
1898 .. _Compiling_Resources:
1899
1900 Compiling Resources
1901 """""""""""""""""""
1902
1903 .. index:: rc
1904 .. index:: windres
1905 .. index:: Resources, compiling
1906
1907 This section describes how you can build a GNAT-compatible (COFF) object file
1908 containing the resources. You do this using the Resource Compiler
1909 ``windres`` as follows:
1910
1911 ::
1912
1913 $ windres -i myres.rc -o myres.o
1914
1915 By default ``windres`` runs ``gcc`` to preprocess the :file:`.rc`
1916 file. You can specify an alternate preprocessor (usually named
1917 :file:`cpp.exe`) using the ``windres`` :switch:`--preprocessor`
1918 parameter. You can obtain a list of all possible switches by entering
1919 the command ``windres`` :switch:`--help`.
1920
1921 You can also use the Microsoft resource compiler ``rc.exe``
1922 to produce a :file:`.res` file (binary resource file). See the
1923 corresponding Microsoft documentation for further details. In this case,
1924 you need to use ``windres`` to translate the :file:`.res` file to a
1925 GNAT-compatible object file as follows:
1926
1927 ::
1928
1929 $ windres -i myres.res -o myres.o
1930
1931
1932 .. _Using_Resources:
1933
1934 Using Resources
1935 """""""""""""""
1936
1937 .. index:: Resources, using
1938
1939 To include the resource file in your program just add the
1940 GNAT-compatible object file for the resource(s) to the linker
1941 arguments. With ``gnatmake`` you do this using the :switch:`-largs`
1942 switch:
1943
1944 ::
1945
1946 $ gnatmake myprog -largs myres.o
1947
1948
1949 .. _Using_GNAT_DLL_from_MSVS:
1950
1951 Using GNAT DLLs from Microsoft Visual Studio Applications
1952 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1953
1954 .. index:: Microsoft Visual Studio, use with GNAT DLLs
1955
1956 This section describes a common case of mixed GNAT/Microsoft Visual
1957 Studio application development, where the main program is developed
1958 using MSVS and is linked with a DLL developed using GNAT. You should
1959 develop such a mixed application following the general guidelines
1960 outlined above; below is the cookbook-style sequence of steps to
1961 follow:
1962
1963 1. First develop and build the GNAT shared library using a library project
1964 (let's assume the project is :file:`mylib.gpr`, producing the library :file:`libmylib.dll`):
1965
1966 ::
1967
1968 $ gprbuild -p mylib.gpr
1969
1970 2. Produce a :file:`.def` file for the symbols you need to interface
1971 with, either by hand or automatically with possibly some manual
1972 adjustments (see :ref:`Creating Definition File Automatically
1973 <Create_Def_File_Automatically>`):
1974
1975 ::
1976
1977 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
1978
1979 3. Make sure that MSVS command-line tools are accessible on the path.
1980
1981 4. Create the Microsoft-style import library (see :ref:`MSVS-Style Import Library <MSVS-Style_Import_Library>`):
1982
1983 ::
1984
1985 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
1986
1987 If you are using a 64-bit toolchain, the above becomes...
1988
1989 ::
1990
1991 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
1992
1993 5. Build the C ``main``:
1994
1995 ::
1996
1997 $ cl /O2 /MD main.c libmylib.lib
1998
1999 6. Before running the executable, make sure you have set the PATH to
2000 include the DLL or copy the DLL into into the directory containing
2001 the :file:`.exe`.
2002
2003
2004 .. _Debugging_a_DLL:
2005
2006 Debugging a DLL
2007 ^^^^^^^^^^^^^^^
2008
2009 .. index:: DLL debugging
2010
2011 Debugging a DLL is similar to debugging a standard program, but
2012 you have to deal with two different executable parts: the DLL and the
2013 program that uses it. There are the following four possibilities:
2014
2015 * The program and DLL are built with GCC/GNAT.
2016 * The program is built with foreign tools and the DLL is built with
2017 GCC/GNAT.
2018 * The program is built with GCC/GNAT and the DLL is built with
2019 foreign tools.
2020
2021 In this section we address only cases one and two above. Note that
2022 there is no point in trying to debug a DLL with GNU/GDB if there is no
2023 GDB-compatible debugging information in it. To do so, you must use a
2024 debugger compatible with the tools suite used to build the DLL.
2025
2026 .. _Program_and_DLL_Both_Built_with_GCC/GNAT:
2027
2028 Program and DLL Both Built with GCC/GNAT
2029 """"""""""""""""""""""""""""""""""""""""
2030
2031 This is the simplest case. Both the DLL and the program have ``GDB``
2032 compatible debugging information. You can then break anywhere in
2033 the process. Let's suppose the main procedure is named
2034 ``ada_main`` and in the DLL there's an entry point named
2035 ``ada_dll``.
2036
2037 The DLL (:ref:`Introduction_to_Dynamic_Link_Libraries_DLLs`) and
2038 program must have been built with the debugging information (see the GNAT
2039 :switch:`-g` switch). Here are the step-by-step instructions for debugging it:
2040
2041 * Launch ``GDB`` on the main program.
2042
2043 ::
2044
2045 $ gdb -nw ada_main
2046
2047 * Start the program and stop at the beginning of the main procedure
2048
2049 ::
2050
2051 (gdb) start
2052
2053 This step is required to be able to set a breakpoint inside
2054 the DLL. Until the program is run, the DLL is not loaded. This has
2055 the consequence that the DLL debugging information is also not
2056 loaded, so it is not possible to set a breakpoint in the DLL.
2057
2058 * Set a breakpoint inside the DLL
2059
2060 ::
2061
2062 (gdb) break ada_dll
2063 (gdb) cont
2064
2065 At this stage, a breakpoint is set inside the DLL. From there on
2066 you can use standard ``GDB`` commands to debug the whole program
2067 (:ref:`Running_and_Debugging_Ada_Programs`).
2068
2069
2070 .. _Program_Built_with_Foreign_Tools_and_DLL_Built_with_GCC/GNAT:
2071
2072 Program Built with Foreign Tools and DLL Built with GCC/GNAT
2073 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
2074
2075 In this case, things are slightly more complex because you can't
2076 start the main program and then break at the beginning to load the DLL and the
2077 associated DLL debugging information. It's not possible to break at the
2078 beginning of the program because there's no ``GDB`` debugging information,
2079 and therefore there's no direct way of getting initial control. This
2080 section addresses this issue by describing some methods that you can use
2081 to break somewhere in the DLL to debug it.
2082
2083 First, suppose that the main procedure is named ``main`` (this is the
2084 case, for example, for some C code built with Microsoft Visual C) and that
2085 there's a DLL named ``test.dll`` containing an Ada entry point named
2086 ``ada_dll``.
2087
2088 The DLL (see :ref:`Introduction_to_Dynamic_Link_Libraries_DLLs`) must have
2089 been built with debugging information (see the GNAT :switch:`-g` switch).
2090
2091
2092 .. rubric:: Debugging the DLL Directly
2093
2094 * Determine the executable's starting address
2095
2096 ::
2097
2098 $ objdump --file-header main.exe
2099
2100 The starting address is reported on the last line. For example:
2101
2102 ::
2103
2104 main.exe: file format pei-i386
2105 architecture: i386, flags 0x0000010a:
2106 EXEC_P, HAS_DEBUG, D_PAGED
2107 start address 0x00401010
2108
2109 * Launch the debugger on the executable.
2110
2111 ::
2112
2113 $ gdb main.exe
2114
2115 * Set a breakpoint at the starting address and launch the program.
2116
2117 ::
2118
2119 $ (gdb) break *0x00401010
2120 $ (gdb) run
2121
2122 The program will stop at the specified address.
2123
2124 * Set a breakpoint on a DLL subroutine.
2125
2126 ::
2127
2128 (gdb) break ada_dll.adb:45
2129
2130 Or if you want to break using a symbol on the DLL, you need first to
2131 select the Ada language (language used by the DLL).
2132
2133 ::
2134
2135 (gdb) set language ada
2136 (gdb) break ada_dll
2137
2138 * Continue the program.
2139
2140 ::
2141
2142 (gdb) cont
2143
2144 This runs the program until it reaches the breakpoint that you've
2145 set. From that point, you can use standard ``GDB`` commands to debug
2146 a program as described in
2147 (:ref:`Running_and_Debugging_Ada_Programs`).
2148
2149 You can also debug the DLL by attaching ``GDB`` to a running process.
2150
2151
2152 .. rubric:: Attaching to a Running Process
2153
2154 .. index:: DLL debugging, attach to process
2155
2156 With ``GDB``, you can always debug a running process by attaching to
2157 it. It's possible to debug a DLL this way. The limitation of this
2158 approach is that the DLL must run long enough to perform the attach
2159 operation. To ensure this, you may want, for example, to insert a
2160 time-wasting loop in the code of the DLL to allow this to happen.
2161
2162 * Launch the main program :file:`main.exe`.
2163
2164 ::
2165
2166 $ main
2167
2168 * Use the Windows *Task Manager* to find the process ID. Let's say
2169 that the process PID for :file:`main.exe` is 208.
2170
2171 * Launch gdb.
2172
2173 ::
2174
2175 $ gdb
2176
2177 * Attach to the running process to be debugged.
2178
2179 ::
2180
2181 (gdb) attach 208
2182
2183 * Load the process debugging information.
2184
2185 ::
2186
2187 (gdb) symbol-file main.exe
2188
2189 * Break somewhere in the DLL.
2190
2191 ::
2192
2193 (gdb) break ada_dll
2194
2195 * Continue process execution.
2196
2197 ::
2198
2199 (gdb) cont
2200
2201 This last step will resume the process execution and stop at
2202 the breakpoint we have set. From there you can use standard
2203 ``GDB`` commands to debug a program, as described in
2204 :ref:`Running_and_Debugging_Ada_Programs`.
2205
2206
2207 .. _Setting_Stack_Size_from_gnatlink:
2208
2209 Setting Stack Size from ``gnatlink``
2210 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2211
2212 You can specify the program stack size at link time. On most versions
2213 of Windows, starting with XP, this is mostly useful to set the size of
2214 the main stack (environment task). The other task stacks are set with
2215 pragma Storage_Size or with the *gnatbind -d* command.
2216
2217 Since very old versions of Windows (2000, NT4, etc.) don't allow setting the
2218 reserve size of individual tasks, the link-time stack size applies to all
2219 tasks, and pragma Storage_Size has no effect.
2220 In particular, Stack Overflow checks are made against this
2221 link-time specified size.
2222
2223 You can set this with ``gnatlink`` using either of the following:
2224
2225
2226 * :switch:`-Xlinker` linker switch
2227
2228 ::
2229
2230 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
2231
2232
2233 This sets the stack reserve size to 0x10000 bytes and the stack commit
2234 size to 0x1000 bytes.
2235
2236 * :switch:`-Wl` linker switch
2237
2238 ::
2239
2240 $ gnatlink hello -Wl,--stack=0x1000000
2241
2242 This sets the stack reserve size to 0x1000000 bytes. Note that with
2243 :switch:`-Wl` switch, you can't also set the stack commit size
2244 because the comma is a separator for this switch.
2245
2246
2247 .. _Setting_Heap_Size_from_gnatlink:
2248
2249 Setting Heap Size from ``gnatlink``
2250 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2251
2252 Under Windows systems, it is possible to specify the program heap size from
2253 ``gnatlink`` using either of the following:
2254
2255 * :switch:`-Xlinker` linker switch
2256
2257 ::
2258
2259 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
2260
2261 This sets the heap reserve size to 0x10000 bytes and the heap commit
2262 size to 0x1000 bytes.
2263
2264 * :switch:`-Wl` linker switch
2265
2266 ::
2267
2268 $ gnatlink hello -Wl,--heap=0x1000000
2269
2270
2271 This sets the heap reserve size to 0x1000000 bytes. Note that with
2272 :switch:`-Wl` switch, you can't also set the heap commit size
2273 because the comma is a separator for this switch.
2274
2275
2276 .. _Win32_Specific_Addons:
2277
2278 Windows Specific Add-Ons
2279 -------------------------
2280
2281 This section describes the Windows specific add-ons.
2282
2283 .. _Win32Ada:
2284
2285 Win32Ada
2286 ^^^^^^^^
2287
2288 ``Win32Ada`` is a binding for the Microsoft Win32 API, which you can
2289 easily install using the provided installer. To use it,
2290 you need to use a project file and add a single with_clause
2291 to give you full access to the ``Win32Ada`` binding sources and ensure
2292 that the proper libraries are passed to the linker.
2293
2294 .. code-block:: gpr
2295
2296 with "win32ada";
2297 project P is
2298 for Sources use ...;
2299 end P;
2300
2301 To build the application, you just need to call ``gprbuild`` for the
2302 application's project, here :file:`p.gpr`:
2303
2304 .. code-block:: sh
2305
2306 gprbuild p.gpr
2307
2308 .. _wPOSIX:
2309
2310 wPOSIX
2311 ^^^^^^
2312
2313 ``wPOSIX`` is a minimal POSIX binding whose goal is to help with building
2314 cross-platforms applications. This binding is not complete though, as
2315 the Win32 API does not provide the necessary support for all POSIX APIs.
2316
2317 To use the ``wPOSIX`` binding, you need to use a project file and add
2318 a single *with* clause to give you full access to the ``wPOSIX`` binding
2319 sources and ensure that the proper libraries are passed to the linker.
2320
2321 .. code-block:: gpr
2322
2323 with "wposix";
2324 project P is
2325 for Sources use ...;
2326 end P;
2327
2328 To build the application, you just need to call ``gprbuild`` for the
2329 application's project, here :file:`p.gpr`:
2330
2331 .. code-block:: sh
2332
2333 gprbuild p.gpr
2334
2335
2336 .. _Mac_OS_Topics:
2337
2338 Mac OS Topics
2339 =============
2340
2341 .. index:: OS X
2342
2343 This section describes topics that are specific to Apple's OS X
2344 platform.
2345
2346 Codesigning the Debugger
2347 ------------------------
2348
2349 The Darwin Kernel, used by Apple's OS X, requires the debugger to have
2350 special permissions before it's allowed to control other
2351 processes. These permissions are granted by codesigning the GDB
2352 executable. Without these permissions, the debugger will report error
2353 messages such as::
2354
2355 Starting program: /x/y/foo
2356 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
2357 (please check gdb is codesigned - see taskgated(8))
2358
2359 Codesigning requires a certificate. The following procedure explains
2360 how to create one:
2361
2362 * Start the Keychain Access application (in
2363 /Applications/Utilities/Keychain Access.app)
2364
2365 * Select the Keychain Access -> Certificate Assistant ->
2366 Create a Certificate... menu
2367
2368 * Then:
2369
2370 * Choose a name for the new certificate (this procedure will use
2371 "gdb-cert" as an example)
2372
2373 * Set "Identity Type" to "Self Signed Root"
2374
2375 * Set "Certificate Type" to "Code Signing"
2376
2377 * Activate the "Let me override defaults" option
2378
2379
2380 * Click several times on "Continue" until the "Specify a Location
2381 For The Certificate" screen appears, then set "Keychain" to "System"
2382
2383 * Click on "Continue" until the certificate is created
2384
2385 * Finally, in the view, double-click on the new certificate,
2386 and set "When using this certificate" to "Always Trust"
2387
2388 * Exit the Keychain Access application and restart the computer
2389 (this is unfortunately required)
2390
2391
2392 Once you've created a certificate as above, you can codesign the debugger
2393 by running the following command in a Terminal:
2394
2395 ::
2396
2397 $ codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
2398
2399 with ``gdb-cert`` replaced by the actual certificate name chosen
2400 above, and ``gnat_install_prefix`` replaced by the location where you
2401 installed GNAT. Also, be sure that users of ``GDB`` are in the Unix
2402 group ``_developer``.